+ All Categories
Home > Documents > Basic Java Commands Examples - Faculty &...

Basic Java Commands Examples - Faculty &...

Date post: 11-Jun-2020
Category:
Upload: others
View: 13 times
Download: 1 times
Share this document with a friend
165
Basic Java Commands Examples SphereProperties is a program that will take as input the radius of a sphere and output the volume and surface area of the sphere. import java.util.Scanner; public class SphereProperties { /** * SphereProperties prints out the volume and surface area of * a sphere given its radius. * Author: Don Spickler * Date: 1/31/2011 */ public static void main(String[] args) { Scanner keyboard = new Scanner(System.in); System.out.print("Input the radius of the sphere: r = "); double radius = keyboard.nextDouble(); double area = 4*Math.PI*Math.pow(radius, 2); double volume = 4/3*Math.PI*Math.pow(radius, 3); System.out.printf("In a sphere of radius %.4f, the volume is %.4f and the surface area is %.4f.", radius, volume, area); } } CylinderVolume is a program that will take as input the radius and height of a cylinder and output its volume. import java.util.Scanner; public class CylinderVolume { /** * CylinderVolume prints out the volume of * a cylinder given its height and radius. * Author: Don Spickler * Date: 1/31/2011 */ public static void main(String[] args) { Scanner keyboard = new Scanner(System.in); System.out.print("Input the radius of the cylinder: r = "); double radius = keyboard.nextDouble(); System.out.print("Input the height of the cylinder: h = "); double height = keyboard.nextDouble(); double volume = Math.PI*Math.pow(radius, 2)*height; System.out.printf("A cylinder of radius %.4f, and height %.4f has volume %.4f.", radius, height, volume); } } Introductory Java Examples 1 of 165.
Transcript
Page 1: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

Basic Java Commands ExamplesSphereProperties is a program that will take as input the radius of a sphere and output the volume and surface area of the sphere.

import java.util.Scanner;public class SphereProperties {

/** * SphereProperties prints out the volume and surface area of * a sphere given its radius. * Author: Don Spickler * Date: 1/31/2011 */public static void main(String[] args) {

Scanner keyboard = new Scanner(System.in);System.out.print("Input the radius of the sphere: r = ");double radius = keyboard.nextDouble();double area = 4*Math.PI*Math.pow(radius, 2);double volume = 4/3*Math.PI*Math.pow(radius, 3);System.out.printf("In a sphere of radius %.4f, the volume is %.4f and the

surface area is %.4f.", radius, volume, area);}

}

CylinderVolume is a program that will take as input the radius and height of a cylinder and output its volume.

import java.util.Scanner;public class CylinderVolume {

/** * CylinderVolume prints out the volume of * a cylinder given its height and radius. * Author: Don Spickler * Date: 1/31/2011 */public static void main(String[] args) {

Scanner keyboard = new Scanner(System.in);System.out.print("Input the radius of the cylinder: r = ");double radius = keyboard.nextDouble();System.out.print("Input the height of the cylinder: h = ");double height = keyboard.nextDouble();double volume = Math.PI*Math.pow(radius, 2)*height;System.out.printf("A cylinder of radius %.4f, and height %.4f has volume

%.4f.", radius, height, volume);}

}

Introductory Java Examples

1 of 165.

Page 2: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

Basic Java Statements #2import java.util.Scanner;public class InputExamples {

/** * InputExamples --- Example of different input types and data types. * Author: Don Spickler * Date: 2/2/2011 */

public static void main(String[] args) {Scanner keyboard = new Scanner(System.in);System.out.print("Input an integer: ");int num1 = keyboard.nextInt();System.out.println(num1);

System.out.print("Input a double: ");double num2 = keyboard.nextDouble();System.out.println(num2);

System.out.print("Input a byte: ");byte num3 = keyboard.nextByte();System.out.println(num3);

System.out.print("Input a long: ");long num4 = keyboard.nextLong();System.out.println(num4);

/*num1 = num4;num3 = num4;num2 = num4;num4 = num1;num4 = num3;num4 = num2;*/

}}

Run:

Input an integer: 2525Input a double: 236.35236.35Input a byte: 1212Input a long: 123456123456

Introductory Java Examples

2 of 165.

Page 3: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

import java.util.Scanner;public class StringExample {

/** * StringExample --- familiar to formal name. * Author: Don Spickler * Date: 2/2/2011 */

public static void main(String[] args) {Scanner keyboard = new Scanner(System.in);System.out.print("Input your name as, first last: ");String firstName = keyboard.next();String lastName = keyboard.next();System.out.println(lastName + ", " + firstName);

}}

Run:

Input your name as, first last: Don SpicklerSpickler, Don

Introductory Java Examples

3 of 165.

Page 4: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

public class MathExamples {/** * MathExamples --- just some calculations. * Author: Don Spickler * Date: 2/2/2011 */

public static void main(String[] args) {double num1 = Math.random();System.out.println("Random Number: " + num1);System.out.println("e = " + Math.E);System.out.println("pi = " + Math.PI);System.out.println("floor(27.8) = " + Math.floor(27.8));System.out.println("floor(17.0) = " + Math.floor(17.0));System.out.println("floor(-7.6) = " + Math.floor(-7.6));System.out.println("sqrt(2) = " + Math.sqrt(2));System.out.println("sqrt(16) = " + Math.sqrt(16));System.out.println("1/3 = " + (1/3));System.out.println("1.0/3.0 = " + (1.0/3.0));System.out.println("1.0/3.0*3.0 = " + (1.0/3.0)*3.0);System.out.println("max(23, 102) = " + Math.max(23, 102));System.out.println("min(23, 102) = " + Math.min(23, 102));

}}

Run:

Random Number: 0.19018278538416344e = 2.718281828459045pi = 3.141592653589793floor(27.8) = 27.0floor(17.0) = 17.0floor(-7.6) = -8.0sqrt(2) = 1.4142135623730951sqrt(16) = 4.01/3 = 01.0/3.0 = 0.33333333333333331.0/3.0*3.0 = 1.0max(23, 102) = 102min(23, 102) = 23

Introductory Java Examples

4 of 165.

Page 5: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

public class SpecialIntegerFunctions {/** * StringExample --- familiar to formal name. * Author: Don Spickler * Date: 2/2/2011 */

public static void main(String[] args) {int int1 = 7;long long1 = 700;System.out.println("int1 = " + int1);System.out.println("long1 = " + long1);

int1++;long1--;

System.out.println("int1 = " + int1);System.out.println("long1 = " + long1);

int1-=5;long1+=10;

System.out.println("int1 = " + int1);System.out.println("long1 = " + long1);

System.out.println("int1 = " + int1++);System.out.println("int1 = " + int1);

System.out.println("int1 = " + ++int1);System.out.println("int1 = " + int1);

System.out.println("int1 = " + --int1);System.out.println("int1 = " + int1);

System.out.println("4*int1++ = " + 4*int1++);System.out.println("4*int1 = " + 4*int1);

long1*=20;System.out.println("long1 = " + long1);

long1/=5;System.out.println("long1 = " + long1);

}}

Run:

int1 = 7long1 = 700int1 = 8long1 = 699int1 = 3long1 = 709int1 = 3int1 = 4int1 = 5int1 = 5int1 = 4int1 = 44*int1++ = 164*int1 = 20long1 = 14180long1 = 2836

Introductory Java Examples

5 of 165.

Page 6: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

Java Data Types and More Commandspublic class DataTypes001 {

public static void main(String[] args) {System.out.println("byte minimum: " + Byte.MIN_VALUE);System.out.println("byte maximum: " + Byte.MAX_VALUE);System.out.println("short minimum: " + Short.MIN_VALUE);System.out.println("short maximum: " + Short.MAX_VALUE);System.out.println("integer minimum: " + Integer.MIN_VALUE);System.out.println("integer maximum: " + Integer.MAX_VALUE);System.out.println("long minimum: " + Long.MIN_VALUE);System.out.println("long maximum: " + Long.MAX_VALUE);System.out.println("float minimum: " + Float.MIN_VALUE);System.out.println("float maximum: " + Float.MAX_VALUE);System.out.println("double minimum: " + Double.MIN_VALUE);System.out.println("double maximum: " + Double.MAX_VALUE);

System.out.println("byte bits: " + Byte.SIZE);System.out.println("short bits: " + Short.SIZE);System.out.println("integer bits: " + Integer.SIZE);System.out.println("long bits: " + Long.SIZE);System.out.println("float bits: " + Float.SIZE);System.out.println("double bits: " + Double.SIZE);

}}

byte minimum: -128byte maximum: 127short minimum: -32768short maximum: 32767integer minimum: -2147483648integer maximum: 2147483647long minimum: -9223372036854775808long maximum: 9223372036854775807float minimum: 1.4E-45float maximum: 3.4028235E38double minimum: 4.9E-324double maximum: 1.7976931348623157E308byte bits: 8short bits: 16integer bits: 32long bits: 64float bits: 32double bits: 64

Introductory Java Examples

6 of 165.

Page 7: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

public class DataTypes002 {public static void main(String[] args) {

// Overloading and underloading

int c = 299792458;System.out.println("c = " + c);System.out.println("c*c = " + c*c);

long lc = 299792458;System.out.println("lc = " + lc);System.out.println("lc*lc = " + lc*lc);System.out.println();

byte b = 120;for (int i = 0; i < 10; i++){

b++;System.out.println(b);

}

System.out.println();

float fl = 1000000000000000000000000000000f;for (int i = 0; i < 10; i++){

fl*=10;System.out.println(fl);

}

System.out.println();

double db = Math.pow(10, 300);for (int i = 0; i < 10; i++){

db*=10;System.out.println(db);

}

System.out.println();

db = Math.pow(10, -320);for (int i = 0; i < 5; i++){

db/=10;System.out.println(db);

}}

}

c = 299792458c*c = -1394772636lc = 299792458lc*lc = 89875517873681764

121122123124125126127-128-127-126

1.0E311.0E321.0000001E331.00000004E341.0E351.00000004E361.00000006E371.0000001E38InfinityInfinity

1.0E3011.0E3021.0E3031.0E3041.0E3059.999999999999999E3059.999999999999999E3069.999999999999998E307InfinityInfinity

1.0E-3211.0E-3221.0E-3230.00.0

Introductory Java Examples

7 of 165.

Page 8: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

public class DataTypes003 {public static void main(String[] args) {

// Characters

char c = 't';System.out.println(c);

for (int i = 0; i < 10; i++){

c++;System.out.println(c);

}

System.out.println();

System.out.println("ASCII Table");c = 0;for (int i = 1; i < 256; i++){

c++;System.out.print(c + " ");if (i % 10 == 0)

System.out.println();}

System.out.println();System.out.println();

c = '"';System.out.println(c);

c = '\"';System.out.println(c);

c = '\'';System.out.println(c);

System.out.println("ASCII Table Again");c = 0;for (int i = 1; i < 256; i++){

c++;System.out.print(c + "\t");if (i % 10 == 0)

System.out.print("\n");}

}}

Introductory Java Examples

8 of 165.

Page 9: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

tuvwxyz{|}~

ASCII Table ! " # $ % & ' ( ) * + , - . / 0 1 2 3 4 5 6 7 8 9 : ; < = > ? @ A B C D E F G H I J K L M N O P Q R S T U V W X Y Z [ \ ] ^ _ ` a b c d e f g h i j k l m n o p q r s t u v w x y z { | } ~ ? ? ? �? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ¡ ¢ £ ¤ ¥ ¦ § ¨ © ª « ¬ ® ¯ ° ± ² ³ ´ µ ¶ · ¸ ¹ º » ¼ ½ ¾ ¿ À Á Â Ã Ä Å Æ Ç È É Ê Ë Ì Í Î Ï Ð Ñ Ò Ó Ô Õ Ö × Ø Ù Ú Û Ü Ý Þ ß à á â ã ä å æ ç è é ê ë ì í î ï ð ñ ò ó ô õ ö ÷ ø ù ú û ü ý þ ÿ

""'ASCII Table Again

! " # $ % & ' () * + , - . / 0 1 23 4 5 6 7 8 9 : ; <= > ? @ A B C D E FG H I J K L M N O PQ R S T U V W X Y Z[ \ ] ^ _ ` a b c de f g h i j k l m no p q r s t u v w xy z { | } ~ � ? ? ?? ? ? ? ? ? ? ? ? ?? ? ? ? ? ? ? ? ? ?? ? ? ? ? ? ? ? ? ¡ ¢ £ ¤ ¥ ¦ § ¨ © ª« ¬ ® ¯ ° ± ² ³ ´µ ¶ · ¸ ¹ º » ¼ ½ ¾¿ À Á Â Ã Ä Å Æ Ç ÈÉ Ê Ë Ì Í Î Ï Ð Ñ ÒÓ Ô Õ Ö × Ø Ù Ú Û ÜÝ Þ ß à á â ã ä å æç è é ê ë ì í î ï ðñ ò ó ô õ ö ÷ ø ù úû ü ý þ ÿ

Introductory Java Examples

9 of 165.

Page 10: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

import java.util.Scanner;public class DataTypes004 {

public static void main(String[] args) {// Reference Types

Scanner keyboard = new Scanner(System.in);System.out.print("Input an integer: ");int t = keyboard.nextInt(); /*Scanner keyboard2 = null;System.out.print("Input an second integer: ");int t2 = keyboard2.nextInt();*/

}}

public class DataTypes005 {public static void main(String[] args) {

// String Examples

String str1 = "This is a test.";

char ch1 = str1.charAt(0);System.out.println(ch1);System.out.println(str1.charAt(0));System.out.println(str1.length());

System.out.println();for (int i = 0; i < str1.length(); i++) {

System.out.println(str1.charAt(i));}

System.out.println();String str2 = "this is a test.";System.out.println(str1.equals(str2));System.out.println(str1.equalsIgnoreCase(str2));

System.out.println();String str3 = String.valueOf(3.14159);System.out.println(str3);

System.out.println();System.out.println(str1.indexOf("i"));System.out.println(str1.indexOf("i", 3));System.out.println(str1.indexOf("i", 7));

System.out.println();System.out.println(str1.lastIndexOf("i"));System.out.println(str1.lastIndexOf("i", 3));System.out.println(str1.lastIndexOf("i", 7));System.out.println(str1.lastIndexOf("i", 1));

System.out.println();System.out.println(str1.indexOf("is"));System.out.println(str1.indexOf("is", 3));System.out.println(str1.indexOf("that"));

System.out.println();str1 = "cat"; str2 = "dog";

System.out.println(str1.compareTo(str2));System.out.println(str1.compareTo(str1));System.out.println(str2.compareTo(str1));

System.out.println();str1 = "cat"; str2 = "Dog";

TT15

This is a test.

falsetrue

3.14159

25-1

525-1

25-1

-101

Introductory Java Examples

10 of 165.

Page 11: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

System.out.println(str1.compareTo(str2));System.out.println(str1.compareTo(str1));System.out.println(str2.compareTo(str1));

System.out.println();System.out.println((int)('c') + " " + (int)('D'));System.out.println();System.out.println(str1.compareToIgnoreCase(str2));System.out.println(str1.compareToIgnoreCase(str1));System.out.println(str2.compareToIgnoreCase(str1));

System.out.println();str1 = str1.concat(str2);System.out.println(str1);

str1 = "cat"; str2 = "Dog";

str1 = str2 + str1;System.out.println(str1);System.out.println();

System.out.println(str1.endsWith("at"));System.out.println(str1.endsWith("ta"));

System.out.println();System.out.println(str1.startsWith("Dog"));System.out.println(str1.startsWith("dog"));

System.out.println();System.out.println(str1.isEmpty());System.out.println();System.out.println(str1);System.out.println(str1.toLowerCase());System.out.println(str1.toUpperCase());System.out.println(str1);

str1 = str1.toUpperCase();System.out.println(str1);

System.out.println();str1 = "This is a test string for testing the

replace command.";System.out.println(str1);str1.replaceAll("test", "short");System.out.println(str1.replaceAll("test",

"short"));System.out.println(str1);System.out.println(str1.replaceFirst("test",

"short"));System.out.println(str1);

System.out.println();System.out.println(str1.substring(5, 7));System.out.println(str1.substring(15, 20));System.out.println(str1.substring(15, 21));System.out.println(str1.substring(15));System.out.println(str1);

System.out.println();str1 = " This is a trim test ";System.out.println(str1.trim() + "*****");

}}

310-31

99 68

-101

catDogDogcat

truefalse

truefalse

false

DogcatdogcatDOGCATDogcatDOGCAT

This is a test string for testing the replace command.

This is a short string for shorting the replace command.

This is a test string for testing the replace command.

This is a short string for testing the replace command.

This is a test string for testing the replace command.

isstrinstringstring for testing the replace command.This is a test string for testing the replace command.

This is a trim test*****

Introductory Java Examples

11 of 165.

Page 12: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

public class DataTypes006 {public static void main(String[] args) {

// Converting numeric strings to numbers.

String str1 = "10.3";String str2 = "123";

System.out.println(str1+str2);

double d = Double.parseDouble(str1);int i = Integer.parseInt(str2);System.out.println(d+i);System.out.println();

}}

public class DataTypes007 {public static void main(String[] args) {

System.out.printf("This statement is %b \n", false);System.out.printf("The numbers are %d, %d, and %d \n", 17, 21, 100);

long c = 299792458;System.out.printf("The speed of light is %d m/sec \n", c);System.out.printf("The speed of light is %15d m/sec \n", c);System.out.printf("The speed of light is %f m/sec \n", 1.0*c);System.out.printf("The speed of light is %e m/sec \n", 1.0*c);

System.out.println();System.out.printf("Pi = %10.2f m/sec \n", Math.PI);System.out.printf("Pi = %10.4f m/sec \n", Math.PI);System.out.printf("Pi = %.2f m/sec \n", Math.PI);System.out.printf("Pi = %.7f m/sec \n", Math.PI);System.out.printf("Pi = %.20f m/sec \n", Math.PI);System.out.printf("Pi = %20f m/sec \n", Math.PI);

System.out.println();System.out.printf("Pi = %20e m/sec \n", Math.PI);System.out.printf("Pi = %20.10e m/sec \n", Math.PI);System.out.printf("Pi = %.20e m/sec \n", Math.PI);

char ch1 = 'W';System.out.println();System.out.printf("This is a character: %c \n", 'A');System.out.printf("This is a character: %c \n", ch1);System.out.printf("This is a character: %c \n", 125);

String str1 = "a string";System.out.println();System.out.printf("This is a string: %s \n", "Here we go.");System.out.printf("This is a string: %s \n", str1);

}}

10.3123133.3

This statement is false The numbers are 17, 21, and 100 The speed of light is 299792458 m/sec The speed of light is 299792458 m/sec The speed of light is 299792458.000000 m/sec The speed of light is 2.997925e+08 m/sec

Pi = 3.14 m/sec Pi = 3.1416 m/sec Pi = 3.14 m/sec Pi = 3.1415927 m/sec Pi = 3.14159265358979300000 m/sec Pi = 3.141593 m/sec

Pi = 3.141593e+00 m/sec Pi = 3.1415926536e+00 m/sec Pi = 3.14159265358979300000e+00 m/sec

This is a character: A This is a character: W This is a character: }

This is a string: Here we go. This is a string: a string

Introductory Java Examples

12 of 165.

Page 13: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

public class DataTypes008 {public static void main(String[] args) {

// More random numbers

for (int i = 0; i < 10; i++)System.out.println(Math.random());

for (int i = 0; i < 10; i++)System.out.println((int)(Math.random()*7) + 5);

}}

0.84595589537806060.7757215200926230.231723882218291880.023404930039023440.42062653306814480.048343248726027020.35078301575536750.8889714117221970.246858899723716660.10800846315586998691011698766

Introductory Java Examples

13 of 165.

Page 14: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

Boolean Expression Examples

public class BoolanExpressions {public static void main(String[] args) {

boolean b1 = true;boolean b2 = false;boolean b3 = true;int x = 2;int y = 3;int z = 4;

System.out.println(b1);System.out.println(b2);System.out.println();System.out.println(2 == 4);System.out.println(x == 4);System.out.println(z == 4);System.out.println(x == z);System.out.println(x != z);System.out.println();System.out.println(z < y);System.out.println(z > z);System.out.println(z >= z);System.out.println();System.out.println(!b1);System.out.println(!b2);System.out.println();System.out.println(b1 && b2);System.out.println(b1 && b3);System.out.println(b1 && !b2);System.out.println();System.out.println(b1 || b2);System.out.println(b1 || b3);System.out.println(!b1 || b2);System.out.println();System.out.println((x > 1) && (z < 7));System.out.println((x > 1) && (z < 4));System.out.println((x > 1) || (z < 4));System.out.println();System.out.println((x % 2 == 0) && (y % 2 == 0));System.out.println((x % 2 == 0) && (z % 2 == 0));System.out.println();System.out.println(((x % 2 == 0) && (z % 2 == 0)) || b2);System.out.println(((x % 2 == 0) && (z % 2 == 0)) && b2);System.out.println(((x % 2 == 0) && (z % 2 == 0)) && b3);System.out.println();System.out.println(b1 ^ b3);System.out.println(b1 ^ b2);System.out.println();System.out.println(true ^ true);System.out.println(true ^ false);System.out.println(false ^ true);System.out.println(false ^ false);System.out.println();System.out.println(2 ^ 5);System.out.println(23 ^ 15);System.out.println(42 ^ 49);

}}

truefalse

falsefalsetruefalsetrue

falsefalsetrue

falsetrue

falsetruetrue

truetruefalse

truefalsetrue

falsetrue

truefalsetrue

falsetrue

falsetruetruefalse

72427

Introductory Java Examples

14 of 165.

Page 15: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

Conditional Statement Examples

import java.util.Scanner;/** * Conditional Example #1 * Author: Don Spickler * Date: 2/6/2011 */

public class ConditionalExample {public static void main(String[] args) {

Scanner keyboard = new Scanner(System.in);System.out.print("How many eggs do you have? ");int numEggs = keyboard.nextInt();if (numEggs == 12){

System.out.println("You have a dozen eggs.");}

}}

import java.util.Scanner;/** * Conditional Example #2 * Author: Don Spickler * Date: 2/6/2011 */

public class ConditionalExample {public static void main(String[] args) {

Scanner keyboard = new Scanner(System.in);System.out.print("How many eggs do you have? ");int numEggs = keyboard.nextInt();if (numEggs == 12){

System.out.println("You have a dozen eggs.");}else{

System.out.println("You do not have a dozen eggs.");}

}}

Introductory Java Examples

15 of 165.

Page 16: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

import java.util.Scanner;/** * Conditional Example #3 * Author: Don Spickler * Date: 2/6/2011 */

public class ConditionalExample {public static void main(String[] args) {

Scanner keyboard = new Scanner(System.in);System.out.print("How many eggs do you have? ");int numEggs = keyboard.nextInt();if (numEggs == 12){

System.out.println("You have a dozen eggs.");}else if (numEggs < 12){

System.out.println("You have fewer than a dozen eggs.");}else{

System.out.println("You have more than a dozen eggs.");}

}}

import java.util.Scanner;/** * Conditional Example #4 * Author: Don Spickler * Date: 2/6/2011 */

public class ConditionalExample {public static void main(String[] args) {

Scanner keyboard = new Scanner(System.in);System.out.print("How many eggs do you have? ");int numEggs = keyboard.nextInt();if (numEggs == 12){

System.out.println("You have a dozen eggs.");}else if (numEggs == 2){

System.out.println("You have a couple eggs.");}else if (numEggs <= 7){

System.out.println("You have a few eggs.");}else if (numEggs < 12){

System.out.println("You have several eggs.");}else{

System.out.println("You have more than a dozen eggs.");}

}}

Introductory Java Examples

16 of 165.

Page 17: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

import java.util.Scanner;/** * Conditional Example #5 * Author: Don Spickler * Date: 2/6/2011 */

public class ConditionalExample {public static void main(String[] args) {

Scanner keyboard = new Scanner(System.in);System.out.println("Please select from the following menu:");System.out.println("1. Rectangle Properties");System.out.println("2. Circle Properties");System.out.println();System.out.print("Selection: ");int menuOption = keyboard.nextInt();if (menuOption == 1){

System.out.print("Input the width of the rectangle: ");double width = keyboard.nextDouble();System.out.print("Input the height of the rectangle: ");double height = keyboard.nextDouble();double area = height * width;double perimeter = 2*height + 2*width;System.out.println("The area of the rectangle is " + area);System.out.println("The perimeter of the rectangle is " + perimeter);

}else if (menuOption == 2){

System.out.print("Input the radius of the circle: ");double radius = keyboard.nextDouble();double area = Math.PI * Math.pow(radius, 2);double circumference = 2 * Math.PI * radius;System.out.println("The area of the circle is " + area);System.out.println("The circumference of the circle is " + circumference);

}else{

System.out.println("Invalid Menu Selection!");}

}}

Introductory Java Examples

17 of 165.

Page 18: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

import java.util.Scanner;/** * Conditional Example #6 * Author: Don Spickler * Date: 2/6/2011 */

public class ConditionalExample {public static void main(String[] args) {

Scanner keyboard = new Scanner(System.in);System.out.println("Please select from the following menu:");System.out.println("1. Rectangle Properties");System.out.println("2. Circle Properties");System.out.println("3. Eggs");System.out.println();System.out.print("Selection: ");int menuOption = keyboard.nextInt();if (menuOption == 1){

System.out.print("Input the width of the rectangle: ");double width = keyboard.nextDouble();System.out.print("Input the height of the rectangle: ");double height = keyboard.nextDouble();double area = height * width;double perimeter = 2*height + 2*width;System.out.println("The area of the rectangle is " + area);System.out.println("The perimeter of the rectangle is " + perimeter);

}else if (menuOption == 2){

System.out.print("Input the radius of the circle: ");double radius = keyboard.nextDouble();double area = Math.PI * Math.pow(radius, 2);double circumference = 2 * Math.PI * radius;System.out.println("The area of the circle is " + area);System.out.println("The circumference of the circle is " + circumference);

}else if (menuOption == 3){

System.out.print("How many eggs do you have? ");int numEggs = keyboard.nextInt();if (numEggs == 12){

System.out.println("You have a dozen eggs.");}else if (numEggs == 2){

System.out.println("You have a couple eggs.");}else if (numEggs <= 7){

System.out.println("You have a few eggs.");}else if (numEggs < 12){

System.out.println("You have several eggs.");}else{

System.out.println("You have more than a dozen eggs.");}

}else{

System.out.println("Invalid Menu Selection!");}

}}

Introductory Java Examples

18 of 165.

Page 19: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

While Loop Examples

import java.util.Scanner;/** * While Loop Example #1 * Author: Don Spickler * Date: 2/6/2011 */

public class WhileLoopExample {public static void main(String[] args) {

Scanner keyboard = new Scanner(System.in);System.out.print("Input the maximum number to square: ");int maxNum = keyboard.nextInt();int currentNum = 1;while (currentNum <= maxNum){

int square = currentNum * currentNum;System.out.print(square + " ");currentNum = currentNum + 1;

}System.out.println();

}}

/** * While Loop Example #2 * Author: Don Spickler * Date: 2/6/2011 */

public class WhileLoopExample {public static void main(String[] args) {

int currentNum = 1;int sum = 0;while (currentNum <= 100){

sum = sum + currentNum;currentNum = currentNum + 1;

}System.out.println("The sum of the numbers from 1 to 100 is " + sum + ".");

}}

Introductory Java Examples

19 of 165.

Page 20: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

import java.util.Scanner;/** * While Loop Example #3 * Author: Don Spickler * Date: 2/6/2011 */

public class WhileLoopExample {public static void main(String[] args) {

Scanner keyboard = new Scanner(System.in);System.out.print("Input n: ");int n = keyboard.nextInt();int currentNum = 1;int sum = 0;int sumSquare = 0;int sumCube = 0;while (currentNum <= n){

sum = sum + currentNum;sumSquare = sumSquare + currentNum*currentNum;sumCube = sumCube + currentNum*currentNum*currentNum;currentNum = currentNum + 1;

}System.out.println("The sum of the numbers from 1 to " + n + " is " + sum + ".");System.out.println("The sum of the squares of the numbers from 1 to " + n + " is " +

sumSquare + ".");System.out.println("The sum of the cubes of the numbers from 1 to " + n + " is " +

sumCube + ".");}

}

import java.util.Scanner;/** * While Loop Example #4 * Author: Don Spickler * Date: 2/6/2011 */

public class WhileLoopExample {public static void main(String[] args) {

Scanner keyboard = new Scanner(System.in);int currentNum = 0;int sum = 0;while (currentNum != -1){

sum = sum + currentNum;

System.out.print("Input the next positive number to add (-1 to quit): ");currentNum = keyboard.nextInt();

}System.out.println("The sum of the input numbers is " + sum + ".");

}}

Introductory Java Examples

20 of 165.

Page 21: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

import java.util.Scanner;/** * While Loop Example #5 * Author: Don Spickler * Date: 2/6/2011 */

public class WhileLoopExample {public static void main(String[] args) {

Scanner keyboard = new Scanner(System.in);int noMore = 0;while (noMore == 0){

System.out.println("Please select from the following menu:");System.out.println("1. Rectangle Properties");System.out.println("2. Circle Properties");System.out.println();System.out.print("Selection: ");int menuOption = keyboard.nextInt();System.out.println();

if (menuOption == 1){System.out.print("Input the width of the rectangle: ");double width = keyboard.nextDouble();System.out.print("Input the height of the rectangle: ");double height = keyboard.nextDouble();double area = height * width;double perimeter = 2*height + 2*width;System.out.println("The area of the rectangle is " + area);System.out.println("The perimeter of the rectangle is " + perimeter);noMore = 1;

}else if (menuOption == 2){

System.out.print("Input the radius of the circle: ");double radius = keyboard.nextDouble();double area = Math.PI * Math.pow(radius, 2);double circumference = 2 * Math.PI * radius;System.out.println("The area of the circle is " + area);System.out.println("The circumference of the circle is " + circumference);noMore = 1;

}else{

System.out.println("Invalid Menu Selection!");System.out.println("Please make another selection.");System.out.println();

}}

}}

Introductory Java Examples

21 of 165.

Page 22: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

Do-While Examplespublic class DoWhile001 {

public static void main(String[] args) {int i = 5;do{

System.out.println(i);i--;

}while (i > 0);System.out.println();

i = 5;while (i > 0){

System.out.println(i);i--;

}

System.out.println();

i = 0;do{

System.out.println(i);i--;

}while (i > 0);System.out.println();

i = 0;while (i > 0){

System.out.println(i);i--;

}}

}

Run:

54321

54321

0

1/2

Introductory Java Examples

22 of 165.

Page 23: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

import java.util.Scanner;public class DoWhile002 {

public static void main(String[] args) {Scanner keyboard = new Scanner(System.in);String YesNo;

do{System.out.print("Input the maximum number to square: ");int maxNum = keyboard.nextInt();int currentNum = 1;do{

int square = currentNum * currentNum;System.out.print(square + " ");currentNum = currentNum + 1;

}while (currentNum <= maxNum);System.out.println();

System.out.print("Do Another Sequence (Y/N): ");YesNo = keyboard.next();

}while(!YesNo.equalsIgnoreCase("N"));}

}

Run:

Input the maximum number to square: 51 4 9 16 25 Do Another Sequence (Y/N): yInput the maximum number to square: 31 4 9 Do Another Sequence (Y/N): yInput the maximum number to square: 01 Do Another Sequence (Y/N): yInput the maximum number to square: -51 Do Another Sequence (Y/N): n

2/2

Introductory Java Examples

23 of 165.

Page 24: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

For Loop Examplesimport java.util.Scanner;public class ForLoopExamples001 {

public static int DoSomething(int t) {return t*t/2;

}

public static void main(String[] args) {System.out.println("For Loop Example 1");

for (int i = 0; i < 10; i++){System.out.print(i + " ");

}

System.out.println();System.out.println();

System.out.println("For Loop Example 2");

for (int i = 0; i < 10; i+=3){System.out.print(i + " ");

}

System.out.println();System.out.println();

System.out.println("For Loop Example 3");

for (int i = 0; i < 10; i++){System.out.print(i + " ");i++;

}

System.out.println();System.out.println();

System.out.println("For Loop Example 4");int j = 4;for (int i = 0; i < 10; i++, j--){

System.out.println(i + " " + j);}

System.out.println();System.out.println();

System.out.println("For Loop Example 5");j = 2;for (int i = 0; i < 10; i = -j, j=j-3){

System.out.println(i + " " + j);}

System.out.println();

System.out.println("For Loop Example 6");j = 2;for (int i = 0; i < 10; i = DoSomething(j)){

System.out.println(i + " " + j);j++;

}

System.out.println();

System.out.println("For Loop Example 7");String str = "";for (int i = 0; i < 10; i++, str = str + "A"){

1/3

Introductory Java Examples

24 of 165.

Page 25: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

System.out.println(i + " " + str);}

System.out.println();

System.out.println("For Loop Example 8");Scanner keyboard = new Scanner(System.in);System.out.print("Input a number: ");int n = keyboard.nextInt();System.out.print("Sequrence: " + n + " ");int count = 1;for (;;){ // The same as while(true)

if (n == 1)break;

if (n % 2 == 0){n = n/2;

}else{

n = 3*n+1;}System.out.print(n + " ");count++;

}System.out.println();System.out.println("The number of numbers in the sequence is " + count);

}}

Run:

For Loop Example 10 1 2 3 4 5 6 7 8 9

For Loop Example 20 3 6 9

For Loop Example 30 2 4 6 8

For Loop Example 40 41 32 23 14 05 -16 -27 -38 -49 -5

For Loop Example 50 2-2 -11 -44 -77 -10

2/3

Introductory Java Examples

25 of 165.

Page 26: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

For Loop Example 60 24 38 4

For Loop Example 70 1 A2 AA3 AAA4 AAAA5 AAAAA6 AAAAAA7 AAAAAAA8 AAAAAAAA9 AAAAAAAAA

For Loop Example 8Input a number: 25Sequrence: 25 76 38 19 58 29 88 44 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1 The number of numbers in the sequence is 24

3/3

Introductory Java Examples

26 of 165.

Page 27: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

Switch Examplesimport java.util.Scanner;public class SwitchExample001 {

public static void main(String[] args) {Scanner keyboard = new Scanner(System.in);System.out.print("Input a number (1-5): ");int num = keyboard.nextInt();switch (num){case 1:

System.out.println("One");break;

case 2:System.out.println("Two");break;

case 3:System.out.println("One more than two");break;

case 4:System.out.println("One less than five");break;

case 5:System.out.println("half of ten");break;

}}

}

Run:

Input a number (1-5): 4One less than five

1/2

Introductory Java Examples

27 of 165.

Page 28: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

import java.util.Scanner;public class SwitchExample002 {

public static void main(String[] args) {Scanner keyboard = new Scanner(System.in);System.out.print("Input a single character: ");String str = keyboard.next();char c = str.charAt(0);switch(c){case 'a':

System.out.println("a was typed");break;

case 'b':case 'c':case 'd':case 'e':case 'f':

System.out.println("b-f was typed");break;

case 'g':System.out.println("gee");break;

default:System.out.println("something else was typed");break;

}}

}

Run:

Input a single character: db-f was typed

2/2

Introductory Java Examples

28 of 165.

Page 29: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

Break Examplepublic class BreakExample001 {

public static void main(String[] args) {System.out.println("Before the loop");

for (int i = 0; i < 10; i++){System.out.println(i);if (i == 6)

break;}

System.out.println("After the loop");}

}

Run:

Before the loop0123456After the loop

1/1

Introductory Java Examples

29 of 165.

Page 30: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

A Few Useful Loop Examples

Finding the minimum and maximum of a list in three ways.

import java.util.Scanner;

/* * This program finds the minimum and maximum of a list of positive numbers * input by the user. * Author: Don Spickler * Created: 9/17/2012 * Revised: 9/17/2012 */

public class FindMaximumAndMinimum {public static void main(String[] args) {

Scanner keyboard = new Scanner(System.in);

System.out.print("Input a positive number (<= 0 to quit): ");double num = keyboard.nextDouble();

if (num > 0){

double min = num;double max = num;while (num > 0){

if (num < min)min = num;

if (num > max)max = num;

System.out.print("Input a positive number (<= 0 to quit): ");num = keyboard.nextDouble();

}

System.out.println("The minimum was " + min);System.out.println("The maximum was " + max);

}else

System.out.println("No list of positive numbers was input.");

}}

Run 1:

Input a positive number (<= 0 to quit): 34Input a positive number (<= 0 to quit): 67Input a positive number (<= 0 to quit): 23Input a positive number (<= 0 to quit): 109Input a positive number (<= 0 to quit): 55Input a positive number (<= 0 to quit): 47Input a positive number (<= 0 to quit): 0The minimum was 23.0The maximum was 109.0

Run 2:

Input a positive number (<= 0 to quit): 0No list of positive numbers was input.

1

Introductory Java Examples

30 of 165.

Page 31: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

import java.util.Scanner;

/* * This program finds the minimum and maximum of a list of positive numbers * input by the user. * Author: Don Spickler * Created: 9/17/2012 * Revised: 9/17/2012 */

public class FindMaximumAndMinimum2 {public static void main(String[] args) {

Scanner keyboard = new Scanner(System.in);

double min = 0;double max = 0;double num = 1;boolean firstnumber = true;

while (num > 0){

System.out.print("Input a positive number (<= 0 to quit): ");num = keyboard.nextDouble();

if (num > 0)if (firstnumber){

min = num;max = num;firstnumber = false;

}else{

if (num < min)min = num;

if (num > max)max = num;

}}

if (max > 0) // Would be true if a positive number was entered.{

System.out.println("The minimum was " + min);System.out.println("The maximum was " + max);

}else

System.out.println("No list of positive numbers was input.");}

}

Run 1:

Input a positive number (<= 0 to quit): 34Input a positive number (<= 0 to quit): 67Input a positive number (<= 0 to quit): 23Input a positive number (<= 0 to quit): 109Input a positive number (<= 0 to quit): 55Input a positive number (<= 0 to quit): 47Input a positive number (<= 0 to quit): 0The minimum was 23.0The maximum was 109.0

Run 2:

Input a positive number (<= 0 to quit): 0No list of positive numbers was input.

2

Introductory Java Examples

31 of 165.

Page 32: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

import java.util.Scanner;

/* * This program finds the minimum and maximum of a list of positive numbers * input by the user. * Author: Don Spickler * Created: 9/17/2012 * Revised: 9/17/2012 */

public class FindMaximumAndMinimum2 {public static void main(String[] args) {

Scanner keyboard = new Scanner(System.in);

double min = 0;double max = 0;double num;boolean firstnumber = true;

do{

System.out.print("Input a positive number (<= 0 to quit): ");num = keyboard.nextDouble();

if (num > 0)if (firstnumber){

min = num;max = num;firstnumber = false;

}else{

if (num < min)min = num;

if (num > max)max = num;

}} while (num > 0);

if (max > 0) // Would be true if a positive number was entered.{

System.out.println("The minimum was " + min);System.out.println("The maximum was " + max);

}else

System.out.println("No list of positive numbers was input.");}

}

Run 1:

Input a positive number (<= 0 to quit): 34Input a positive number (<= 0 to quit): 67Input a positive number (<= 0 to quit): 23Input a positive number (<= 0 to quit): 109Input a positive number (<= 0 to quit): 55Input a positive number (<= 0 to quit): 47Input a positive number (<= 0 to quit): 0The minimum was 23.0The maximum was 109.0

Run 2:

Input a positive number (<= 0 to quit): 0No list of positive numbers was input.

3

Introductory Java Examples

32 of 165.

Page 33: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

Simulation to approximate π.

import java.util.Random;import java.util.Scanner;

public class PiApprox {public static void main(String[] args) {

Random generator = new Random();Scanner keyboard = new Scanner(System.in);

System.out.print("Input the number of darts: ");int numDarts = keyboard.nextInt();

int count = 0;for (int i = 0; i < numDarts; i++){

double x = 2*generator.nextDouble()-1;double y = 2*generator.nextDouble()-1;if (Math.sqrt(x*x+y*y) <= 1)

count++;}

double prob = 1.0*count/numDarts;System.out.println("Pi = " + prob*4);

}}

Runs:

Input the number of darts: 1000Pi = 3.1

Input the number of darts: 1000000Pi = 3.141564

Input the number of darts: 10000000Pi = 3.141526

Input the number of darts: 100000000Pi = 3.14182504

4

Introductory Java Examples

33 of 165.

Page 34: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

This is the 3n+1 sequence.

import java.util.Scanner;

/** * While Loop Example #5 * Author: Don Spickler * Date: 2/6/2011 */

public class NiftySequence {public static void main(String[] args) {

Scanner keyboard = new Scanner(System.in);System.out.print("Input a number: ");int n = keyboard.nextInt();System.out.print("Sequrence: " + n + " ");int count = 1;while (n != 1){

if (n % 2 == 0){n = n/2;

}else{

n = 3*n+1;}System.out.print(n + " ");count++;

}System.out.println();System.out.println("The number of numbers in the sequence is " + count);

}

}

Runs:

Input a number: 25Sequrence: 25 76 38 19 58 29 88 44 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1 The number of numbers in the sequence is 24

Input a number: 1024Sequrence: 1024 512 256 128 64 32 16 8 4 2 1 The number of numbers in the sequence is 11

Input a number: 15Sequrence: 15 46 23 70 35 106 53 160 80 40 20 10 5 16 8 4 2 1 The number of numbers in the sequence is 18

5

Introductory Java Examples

34 of 165.

Page 35: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

The game of Higher-Lower.

import java.util.Random;import java.util.Scanner;

public class GuessingGame {public static void main(String[] args) {

Random generator = new Random();Scanner keyboard = new Scanner(System.in);

String playAgain = "Y";int userWins = 0;int computerWins = 0;

while (playAgain.compareToIgnoreCase("Y") == 0){

int answer = generator.nextInt(100)+1;int numGuesses = 1;int guess = 0;

while ((numGuesses <= 7) && (guess != answer)){

System.out.print("Guess a number: ");guess = keyboard.nextInt();

if (numGuesses < 7){

if (guess < answer){

System.out.println("Higher...");}else if (guess > answer){

System.out.println("Lower...");}else{

System.out.println("You Win");userWins++;

}}else{

if (guess == answer){

System.out.println("You Win");userWins++;

}else{

System.out.println("I Win, the number was " + answer);computerWins++;

}}numGuesses++;

}

System.out.print("Would you like to play another game? (Y/N): ");playAgain = keyboard.next();

}

System.out.println("Final Score: You " + userWins + " Computer " + computerWins);}

}

6

Introductory Java Examples

35 of 165.

Page 36: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

Run:

Guess a number: 50Higher...Guess a number: 75Higher...Guess a number: 88Higher...Guess a number: 94Higher...Guess a number: 97Lower...Guess a number: 95Higher...Guess a number: 96You WinWould you like to play another game? (Y/N): YGuess a number: 50Lower...Guess a number: 25Higher...Guess a number: 38Lower...Guess a number: 31Lower...Guess a number: 28Lower...Guess a number: 27You WinWould you like to play another game? (Y/N): yGuess a number: 50Lower...Guess a number: 49Lower...Guess a number: 48Lower...Guess a number: 47Lower...Guess a number: 46Lower...Guess a number: 45Lower...Guess a number: 44I Win, the number was 21Would you like to play another game? (Y/N): nFinal Score: You 2 Computer 1

7

Introductory Java Examples

36 of 165.

Page 37: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

Exception Handling

import java.util.Scanner;

public class TryCatch001 {public static void main(String[] args) {

Scanner keyboard = new Scanner(System.in);

System.out.print("Numerator = ");int num = keyboard.nextInt();System.out.print("Denominator = ");int den = keyboard.nextInt();

System.out.println(num + "/" + den + " = " + num/den);}

}

Runs:

Numerator = 45Denominator = 945/9 = 5

Numerator = 34Denominator = 2334/23 = 1

Numerator = 23Denominator = 0Exception in thread "main" java.lang.ArithmeticException: / by zero

at TryCatch001.main(TryCatch001.java:12)

1

Introductory Java Examples

37 of 165.

Page 38: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

import java.util.Scanner;

public class TryCatch002 {public static void main(String[] args) {

Scanner keyboard = new Scanner(System.in);

System.out.print("Numerator = ");int num = keyboard.nextInt();System.out.print("Denominator = ");int den = keyboard.nextInt();

try{System.out.println(num + "/" + den + " = " + num/den);

} catch (ArithmeticException e) {System.out.println("Division by 0!");

}}

}

Runs:

Numerator = 45Denominator = 945/9 = 5

Numerator = 1Denominator = 0Division by 0!

2

Introductory Java Examples

38 of 165.

Page 39: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

import java.util.Scanner;

public class TryCatch003 {public static void main(String[] args) {

Scanner keyboard = new Scanner(System.in);

System.out.print("Numerator = ");int num = keyboard.nextInt();System.out.print("Denominator = ");int den = keyboard.nextInt();

try{System.out.println(num + "/" + den + " = " + num/den);

} catch (ArithmeticException e) {System.out.println(e.getMessage());

}}

}

Run:

Numerator = 1Denominator = 0/ by zero

3

Introductory Java Examples

39 of 165.

Page 40: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

import java.util.Scanner;

public class TryCatch004 {public static void main(String[] args) {

Scanner keyboard = new Scanner(System.in);

System.out.print("Numerator = ");int num = keyboard.nextInt();System.out.print("Denominator = ");int den = keyboard.nextInt();

try{System.out.println(num + "/" + den + " = " + num/den);

} catch (Exception e) {System.out.println(e.getMessage());

}}

}

Runs:

Numerator = 1Denominator = 0/ by zero

Numerator = 318371469327649173461Exception in thread "main" java.util.InputMismatchException: For input string: "318371469327649173461"

at java.util.Scanner.nextInt(Unknown Source)at java.util.Scanner.nextInt(Unknown Source)at TryCatch004.main(TryCatch004.java:8)

4

Introductory Java Examples

40 of 165.

Page 41: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

import java.util.Scanner;

public class TryCatch005 {public static void main(String[] args) {

Scanner keyboard = new Scanner(System.in);

try{System.out.print("Numerator = ");int num = keyboard.nextInt();System.out.print("Denominator = ");int den = keyboard.nextInt();

System.out.println(num + "/" + den + " = " + num/den);} catch (Exception e) {

System.out.println(e.getMessage());}

}}

Runs:

Numerator = 73614139654739143652375For input string: "73614139654739143652375"

5

Introductory Java Examples

41 of 165.

Page 42: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

Method Examples in Javapublic class MethodExample001 {

/** * MethodExample001 * Simple example of the use of methods in Java. * Author: Don Spickler * Date: 3/7/2011 */

public static void PrintLine() {System.out.println("This is a line of text.");

}

public static void main(String[] args) {System.out.println("Start Here");PrintLine();System.out.println("Back to the Main");PrintLine();System.out.println("End Here");

}}

Run:

Start HereThis is a line of text.Back to the MainThis is a line of text.End Here

public class MethodExample002 {/** * MethodExample002 * Simple example of the use of methods in Java. * Author: Don Spickler * Date: 3/7/2011 */

public static void PrintIntro() {System.out.println("This is the intro to the program.");

}

public static void PrintGoodbye() {System.out.println("Have a nice day :-)");

}

public static void main(String[] args) {PrintIntro();

for (int i = 0; i < 5; i++){

System.out.print(i + " ");}System.out.println();

PrintGoodbye();}

}

Run:

This is the intro to the program.0 1 2 3 4 Have a nice day :-)

1/14

Introductory Java Examples

42 of 165.

Page 43: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

import java.util.Scanner;public class MethodExample003 {

/** * MethodExample003 * Simple example of the use of methods in Java. * Author: Don Spickler * Date: 3/7/2011 */

public static void Welcome(String name) {System.out.println("Welcome to Java Methods " + name);

}

public static void main(String[] args) {Scanner keyboard = new Scanner(System.in);System.out.print("Input your name: ");String myName = keyboard.nextLine();Welcome(myName);

}}

Run:Input your name: Don SpicklerWelcome to Java Methods Don Spickler

import java.util.Scanner;public class MethodExample004 {

/** * MethodExample004 * Simple example of the use of methods in Java. * Author: Don Spickler * Date: 3/7/2011 */

public static void PrintFormalName(String firstName, String lastName) {System.out.println("Hello " + firstName + " " + lastName);System.out.println("Your formal name is " + lastName + ", " + firstName);

}

public static void main(String[] args) {Scanner keyboard = new Scanner(System.in);System.out.print("Input your name as, first last: ");String firstName = keyboard.next();String lastName = keyboard.next();PrintFormalName(firstName, lastName);

}}

Run:Input your name as, first last: Don SpicklerHello Don SpicklerYour formal name is Spickler, Don

2/14

Introductory Java Examples

43 of 165.

Page 44: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

import java.util.Scanner;public class MethodExample005 {

/** * MethodExample005 * Simple example of the use of methods in Java. * Author: Don Spickler * Date: 3/7/2011 */

public static void PrintCircleArea(double radius) {System.out.println("Circle Area = " + Math.PI*radius*radius);

}

public static void PrintRectangleArea(double length, double width) {System.out.println("Rectangle Area = " + length*width);

}

public static void main(String[] args) {Scanner keyboard = new Scanner(System.in);System.out.print("Input the radius of the circle: ");double rad = keyboard.nextDouble();System.out.print("Input the length of the rectangle: ");double len = keyboard.nextDouble();System.out.print("Input the width of the rectangle: ");double wid = keyboard.nextDouble();PrintCircleArea(rad);PrintRectangleArea(len, wid);

}}

Run:Input the radius of the circle: 5Input the length of the rectangle: 10Input the width of the rectangle: 15Circle Area = 78.53981633974483Rectangle Area = 150.0

3/14

Introductory Java Examples

44 of 165.

Page 45: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

import java.util.Scanner;public class MethodExample006 {

/** * MethodExample006 * Simple example of the use of methods in Java. * Author: Don Spickler * Date: 3/7/2011 */

public static double CircleArea(double radius) {return Math.PI*radius*radius;

}

public static double RectangleArea(double length, double width) {return length*width;

}

public static void main(String[] args) {Scanner keyboard = new Scanner(System.in);System.out.print("Input the radius of the circle: ");double rad = keyboard.nextDouble();System.out.print("Input the length of the rectangle: ");double len = keyboard.nextDouble();System.out.print("Input the width of the rectangle: ");double wid = keyboard.nextDouble();System.out.println("Circle Area = " + CircleArea(rad));System.out.println("Rectangle Area = " + RectangleArea(len, wid));

}}

Run:Input the radius of the circle: 5Input the length of the rectangle: 10Input the width of the rectangle: 15Circle Area = 78.53981633974483Rectangle Area = 150.0

4/14

Introductory Java Examples

45 of 165.

Page 46: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

import java.util.Scanner;public class MethodExample007 {

/** * MethodExample007 * Simple example of the use of methods in Java. * Author: Don Spickler * Date: 3/7/2011 */

public static double CircleArea(double radius) {return Math.PI*radius*radius;

}

public static double RectangleArea(double length, double width) {return length*width;

}

public static int menu() {Scanner keyboard = new Scanner(System.in);int menuOption = 0;while (menuOption < 1 || menuOption > 3){

System.out.println("Please select from the following menu:");System.out.println("1. Rectangle Properties");System.out.println("2. Circle Properties");System.out.println("3. Exit");System.out.println();System.out.print("Selection: ");menuOption = keyboard.nextInt();System.out.println();

if (menuOption < 1 || menuOption > 3){System.out.println("Invalid Menu Selection!");System.out.println("Please make another selection.");System.out.println();

}}return menuOption;

}

public static void main(String[] args) {Scanner keyboard = new Scanner(System.in);int menuOption = 0;while (menuOption != 3){

menuOption = menu();

if (menuOption == 1){System.out.print("Input the width of the rectangle: ");double width = keyboard.nextDouble();System.out.print("Input the height of the rectangle: ");double height = keyboard.nextDouble();System.out.println("The area of the rectangle is " + RectangleArea(width, height));

}else if (menuOption == 2){

System.out.print("Input the radius of the circle: ");double rad = keyboard.nextDouble();System.out.println("The area of the circle is " + CircleArea(rad));

}System.out.println();

}}

}

5/14

Introductory Java Examples

46 of 165.

Page 47: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

Run:

Please select from the following menu:1. Rectangle Properties2. Circle Properties3. Exit

Selection: 6

Invalid Menu Selection!Please make another selection.

Please select from the following menu:1. Rectangle Properties2. Circle Properties3. Exit

Selection: 1

Input the width of the rectangle: 2Input the height of the rectangle: 3The area of the rectangle is 6.0

Please select from the following menu:1. Rectangle Properties2. Circle Properties3. Exit

Selection: 2

Input the radius of the circle: 5The area of the circle is 78.53981633974483

Please select from the following menu:1. Rectangle Properties2. Circle Properties3. Exit

Selection: 3

6/14

Introductory Java Examples

47 of 165.

Page 48: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

import java.util.Scanner;public class MethodExample008 {

/** * MethodExample008 * Nifty Sequence Example * Author: Don Spickler * Date: 3/7/2011 */

public static int NiftySequence(int n) {if (n % 2 == 0){

n = n/2;}else{

n = 3*n+1;}return n;

}

public static void main(String[] args) {Scanner keyboard = new Scanner(System.in);System.out.print("Input a number: ");int n = keyboard.nextInt();System.out.print("Sequence: " + n + " ");int count = 1;while (n != 1){

n = NiftySequence(n);System.out.print(n + " ");count++;

}System.out.println();System.out.println("The number of numbers in the sequence is " + count);

}}

Run:Input a number: 104Sequence: 104 52 26 13 40 20 10 5 16 8 4 2 1 The number of numbers in the sequence is 13

7/14

Introductory Java Examples

48 of 165.

Page 49: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

import java.util.Scanner;public class MethodExample009 {

/** * MethodExample009 * Heron's Formula for the Area of a Triangle * Author: Don Spickler * Date: 3/7/2011 */

public static double distance(double x1, double y1, double x2, double y2) {return Math.sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1));

}

public static double heron(double a, double b, double c) {double p = (a+b+c)/2;return Math.sqrt(p*(p-a)*(p-b)*(p-c));

}

public static void main(String[] args) {Scanner keyboard = new Scanner(System.in);System.out.print("Input point 1 as x y: ");double x1 = keyboard.nextDouble();double y1 = keyboard.nextDouble();System.out.print("Input point 2 as x y: ");double x2 = keyboard.nextDouble();double y2 = keyboard.nextDouble();System.out.print("Input point 3 as x y: ");double x3 = keyboard.nextDouble();double y3 = keyboard.nextDouble();double a = distance(x1, y1, x2, y2);double b = distance(x1, y1, x3, y3);double c = distance(x3, y3, x2, y2);System.out.println("The area of the triangle is " + heron(a, b, c));

}}

Run:Input point 1 as x y: 2 1 Input point 2 as x y: 3 7Input point 3 as x y: 0 4The area of the triangle is 7.5

8/14

Introductory Java Examples

49 of 165.

Page 50: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

import java.util.Random;import java.util.Scanner;public class MethodExample010 {

/** * MethodExample010 * Guessing Game Example 1 * Author: Don Spickler * Date: 3/7/2011 */

// returns true if the user wins.public static boolean GuessingGame() {

Random generator = new Random();Scanner keyboard = new Scanner(System.in);int answer = generator.nextInt(100)+1;int numGuesses = 1;int guess = 0;while ((numGuesses <= 7) && (guess != answer)){

System.out.print("Guess a number: ");guess = keyboard.nextInt();

if (numGuesses < 7){

if (guess < answer){

System.out.println("Higher...");}else if (guess > answer){

System.out.println("Lower...");}else{

System.out.println("You Win");return true;

}}else{

if (guess == answer){

System.out.println("You Win");return true;

}else{

System.out.println("I Win, the number was " + answer);return false;

}}numGuesses++;

}return false; // Never happens but the compiler needs it.

}

public static void main(String[] args) {Scanner keyboard = new Scanner(System.in);String playAgain = "Y";int userWins = 0;int computerWins = 0;while (playAgain.compareToIgnoreCase("Y") == 0){

boolean youWin = GuessingGame();

9/14

Introductory Java Examples

50 of 165.

Page 51: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

if (youWin){userWins++;

}else{computerWins++;

}

System.out.print("Would you like to play another game? (Y/N): ");playAgain = keyboard.next();

}

System.out.println("Final Score: You " + userWins + " Computer " + computerWins);}

}

Run:Guess a number: 50Higher...Guess a number: 75Lower...Guess a number: 62Lower...Guess a number: 56Higher...Guess a number: 59Higher...Guess a number: 60You WinWould you like to play another game? (Y/N): yGuess a number: 25Higher...Guess a number: 26Higher...Guess a number: 27Higher...Guess a number: 28Higher...Guess a number: 29Higher...Guess a number: 30Higher...Guess a number: 31I Win, the number was 85Would you like to play another game? (Y/N): nFinal Score: You 1 Computer 1

10/14

Introductory Java Examples

51 of 165.

Page 52: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

import java.util.Random;import java.util.Scanner;public class MethodExample011

public static boolean GuessingGame() {Random generator = new Random();Scanner keyboard = new Scanner(System.in);int answer = generator.nextInt(100)+1;int numGuesses = 1;int guess = 0;while ((numGuesses <= 7) && (guess != answer)){

System.out.print("Guess a number: ");guess = keyboard.nextInt();

if (numGuesses < 7){

if (guess < answer)System.out.println("Higher...");

else if (guess > answer)System.out.println("Lower...");

else{

System.out.println("You Win");return true;

}}else{

if (guess == answer){

System.out.println("You Win");return true;

}else{

System.out.println("I Win, the number was " + answer);return false;

}}numGuesses++;

}return false; // Never happens but the compiler needs it.

}

public static void main(String[] args) {Scanner keyboard = new Scanner(System.in);String playAgain = "Y";int userWins = 0;int computerWins = 0;while (playAgain.compareToIgnoreCase("Y") == 0){

if (GuessingGame())userWins++;

elsecomputerWins++;

System.out.print("Would you like to play another game? (Y/N): ");playAgain = keyboard.next();

}System.out.println("Final Score: You " + userWins + " Computer " + computerWins);

}}

11/14

Introductory Java Examples

52 of 165.

Page 53: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

Rectangle.javapublic class Rectangle {

public static double Area(double length, double width) {return length*width;

}

public static double Perimeter(double length, double width) {return 2*length + 2*width;

}}

Circle.javapublic class Circle {

public static double Area(double radius) {return Math.PI*radius*radius;

}

public static double Circumference(double radius) {return 2*Math.PI*radius;

}

public static double Perimeter(double radius) {return Circumference(radius);

}}

MethodExample012.javaimport java.util.Scanner;public class MethodExample012 {

/** * MethodExample012 * External Class Methods Example * Author: Don Spickler * Date: 3/7/2011 */

public static int menu() {Scanner keyboard = new Scanner(System.in);int menuOption = 0;while (menuOption < 1 || menuOption > 3){

System.out.println("Please select from the following menu:");System.out.println("1. Rectangle Properties");System.out.println("2. Circle Properties");System.out.println("3. Exit");System.out.println();System.out.print("Selection: ");menuOption = keyboard.nextInt();System.out.println();

if (menuOption < 1 || menuOption > 3){System.out.println("Invalid Menu Selection!");System.out.println("Please make another selection.");System.out.println();

}}return menuOption;

}

12/14

Introductory Java Examples

53 of 165.

Page 54: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

public static void main(String[] args) {Scanner keyboard = new Scanner(System.in);int menuOption = 0;while (menuOption != 3){

menuOption = menu();

if (menuOption == 1){System.out.print("Input the width of the rectangle: ");double width = keyboard.nextDouble();System.out.print("Input the height of the rectangle: ");double height = keyboard.nextDouble();System.out.println("The area of the rectangle is " + Rectangle.Area(width, height));System.out.println("The perimeter of the rectangle is " + Rectangle.Perimeter(width,

height));}else if (menuOption == 2){

System.out.print("Input the radius of the circle: ");double rad = keyboard.nextDouble();System.out.println("The area of the circle is " + Circle.Area(rad));System.out.println("The circumference of the circle is " + Circle.Circumference(rad));

}System.out.println();

}}

}

Run:Please select from the following menu:1. Rectangle Properties2. Circle Properties3. Exit

Selection: 1

Input the width of the rectangle: 2Input the height of the rectangle: 3The area of the rectangle is 6.0The perimeter of the rectangle is 10.0

Please select from the following menu:1. Rectangle Properties2. Circle Properties3. Exit

Selection: 2

Input the radius of the circle: 2The area of the circle is 12.566370614359172The circumference of the circle is 12.566370614359172

Please select from the following menu:1. Rectangle Properties2. Circle Properties3. Exit

Selection: 2

Input the radius of the circle: 10The area of the circle is 314.1592653589793The circumference of the circle is 62.83185307179586

Please select from the following menu:1. Rectangle Properties2. Circle Properties3. Exit

Selection: 3

13/14

Introductory Java Examples

54 of 165.

Page 55: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

Triangle.javapublic class Triangle {

public static double Area(double a, double b, double c) {double p = (a+b+c)/2;return Math.sqrt(p*(p-a)*(p-b)*(p-c));

}

public static double Perimeter(double a, double b, double c) {return a + b + c;

}

public static boolean isRight(double a, double b, double c) {boolean righttri = false;if (a*a+b*b == c*c)

righttri = true;if (a*a+c*c == b*b)

righttri = true;if (c*c+b*b == a*a)

righttri = true;return righttri;

}

public static boolean isTriangle(double a, double b, double c) {boolean tri = true;// Find longest legdouble longleg = a;if (b > longleg) longleg = b;if (c > longleg) longleg = c;// Check if the two shorter legs do add up to the length of the // longest leg.if (a+b+c-longleg <= longleg)

tri = false;return tri;

}}

MethodExample013.javaimport java.util.Scanner;public class MethodExample013 {

public static void main(String[] args) {Scanner keyboard = new Scanner(System.in);System.out.print("Input the lengths of the sides of the triangle, a b c: ");double a = keyboard.nextDouble();double b = keyboard.nextDouble();double c = keyboard.nextDouble();if (Triangle.isTriangle(a,b,c)){

System.out.println("Area = " + Triangle.Area(a,b,c));System.out.println("Perimeter = " + Triangle.Perimeter(a, b, c));System.out.println("Right Triangle = " + Triangle.isRight(a, b, c));

}else

System.out.println("This is not a triangle.");}

}

14/14

Introductory Java Examples

55 of 165.

Page 56: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

Another Method Example

Main Program File:

public class Methods001 {

public static void main(String[] args) {System.out.println(MyMath.doubleit(5));System.out.println(MyMath.same(5));

}}

MyMath.java:

public class MyMath {

public static int doubleit(int a){return 2*a;

}

public static int same(int t){int x = doubleit(t);double y = MoreMath.half(x);return (int)y;

}

}

MoreMath.java:

public class MoreMath {public static double half(double x) {

return x / 2;}

}

Run:

105

Introductory Java Examples

56 of 165.

Page 57: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

User Input Testing

One feature available with the Scanner object in Java is its ability to tell you what the data type of the next thing to be read is. That is, we can ask the scanner if the next thing to be read is an integer or if the next thing to be read is a double, etc. So we can check the data type before the read and hence avoid the program crashing if the input is not the correct type. This is done with “has” methods in the Scanner object.

In this first example we do no data type checking. So if the user types in a double the program will crash when it tries to execute the statement kb.nextInt() since we cannot input a double into an integer.

import java.util.Scanner;

public class UserInputTesting000 {public static void main(String[] args) {

Scanner kb = new Scanner(System.in);

// Input from keyboard with no data type checking.System.out.print("Input an integer (no data checking): ");int num = kb.nextInt();

System.out.println("num = " + num);}

}

Run:

Input an integer (no data checking): 3.8Exception in thread "main" java.util.InputMismatchException

at java.util.Scanner.throwFor(Unknown Source)at java.util.Scanner.next(Unknown Source)at java.util.Scanner.nextInt(Unknown Source)at java.util.Scanner.nextInt(Unknown Source)at UserInputTesting000.main(UserInputTesting000.java:9)

1

Introductory Java Examples

57 of 165.

Page 58: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

import java.util.Scanner;

public class UserInputTesting001 {

public static void main(String[] args) {Scanner kb = new Scanner(System.in);

// Input from keyboard with data type checking.// Ask the scanner if the next thing to be read in is an integer.// If so, read it in and if not, print an error message and ask// for another input. Finally clear out the input buffer.

boolean inputNeeded = true;int value = 0;while (inputNeeded) {

System.out.print("Input an integer (data checking): ");if (kb.hasNextInt()) {

value = kb.nextInt();inputNeeded = false;

} else {System.out.println("Input is not an integer, try again.");

}String clearbuf = kb.nextLine();

}System.out.println("value = " + value);

}}

Run:

Input an integer (data checking): 3.8Input is not an integer, try again.Input an integer (data checking): 2.458Input is not an integer, try again.Input an integer (data checking): 5value = 5

2

Introductory Java Examples

58 of 165.

Page 59: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

This would be much more convenient if we modularize the code. That way we can simply do a function call to this input method and data checking is done for us. Now we can call it at any point without the need to copy and paste all of the code. Notice also that the Scanner is moved from the main to the method.

import java.util.Scanner;

public class UserInputTesting003 {

public static int getInteger() {Scanner kb = new Scanner(System.in);

boolean inputNeeded = true;int value = 0;while (inputNeeded) {

System.out.print("Input an integer: ");if (kb.hasNextInt()) {

value = kb.nextInt();inputNeeded = false;

} else {System.out.println("Input is not an integer, try again.");

}String clearbuf = kb.nextLine();

}return value;

}

public static void main(String[] args) {int num = getInteger();System.out.println("num = " + num);

System.out.println();

int num2 = getInteger();System.out.println("num2 = " + num2);

}}

Run:

Input an integer: 3.6Input is not an integer, try again.Input an integer: 15num = 15

Input an integer: 2.5Input is not an integer, try again.Input an integer: 1.8Input is not an integer, try again.Input an integer: 15num2 = 15

3

Introductory Java Examples

59 of 165.

Page 60: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

At this point we can do some simple additions to this to make the method more flexible. For example, you may want to change the messages for the prompt and the error, so bring them in as parameters. Another thing that is common to do with integer input is to check that an input is within a lower and upper bound, for example, make sure that the input is in the range from 4 to 17. This requires the addition of some parameters and a block of code to check if an input is in the given range, after we check if the input is valid. After this, we added some overloaded functions that give you some more options for calling the getInteger method.

import java.util.Scanner;

public class UserInputTesting004 {

// Made the getInteger method more general by letting the user input// the prompt message and the error message.public static int getInteger(String message, String errorMessage) {

Scanner kb = new Scanner(System.in);

boolean inputNeeded = true;int value = 0;while (inputNeeded) {

System.out.print(message);if (kb.hasNextInt()) {

value = kb.nextInt();inputNeeded = false;

} else {System.out.println(errorMessage);

}String clearbuf = kb.nextLine();

}return value;

}

// Added the functionality to check that an input is within a range// of numbers [low, high].public static int getInteger(int low, int high, String message,

String errorMessage, String rangeErrorMessage) {Scanner kb = new Scanner(System.in);boolean inputNeeded = true;int value = 0;while (inputNeeded) {

System.out.print(message);if (kb.hasNextInt()) {

value = kb.nextInt();if (value < low || value > high)

System.out.println(rangeErrorMessage);else

inputNeeded = false;} else {

System.out.println(errorMessage);}String clearbuf = kb.nextLine();

}return value;

}

4

Introductory Java Examples

60 of 165.

Page 61: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

// The following are overloads of the getInteger method that allow// the user to use some default messages. public static int getInteger() {

return getInteger("Input an integer: ","Input is not an integer, try again.");

}

public static int getInteger(String message) {return getInteger(message, "Input is not an integer, try again.");

}

public static int getInteger(int low, int high) {return getInteger(low, high, "Input an integer between " + low + " to "

+ high + ": ", "Input is not an integer, try again.", "Input is not in the correct range, try again.");

}

public static int getInteger(int low, int high, String message) {return getInteger(low, high, message,

"Input is not an integer, try again.", "Input is not in the correct range, try again.");

}

public static void main(String[] args) {int num = getInteger();System.out.println("num1 = " + num);System.out.println();

num = getInteger("Input num: ");System.out.println("num2 = " + num);System.out.println();

num = getInteger("Input an integer called num: ","Not an integer, moron.");

System.out.println("num3 = " + num);System.out.println();

num = getInteger(2, 10);System.out.println("num4 = " + num);System.out.println();

num = getInteger(2, 10, "Input an integer between 2 and 10: ");System.out.println("num5 = " + num);System.out.println();

num = getInteger(5, 15, "Input an integer between 5 and 15: ","This was not an integer, moron.","I said between 5 and 15, what word don't you understand?");

System.out.println("num6 = " + num);System.out.println();

}}

5

Introductory Java Examples

61 of 165.

Page 62: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

Run:

Input an integer: 3.5Input is not an integer, try again.Input an integer: 5.7Input is not an integer, try again.Input an integer: 5num1 = 5

Input num: 3.1Input is not an integer, try again.Input num: 4.8Input is not an integer, try again.Input num: 57num2 = 57

Input an integer called num: 2.5Not an integer, moron.Input an integer called num: 25num3 = 25

Input an integer between 2 to 10: 5.9Input is not an integer, try again.Input an integer between 2 to 10: 15Input is not in the correct range, try again.Input an integer between 2 to 10: 6.5Input is not an integer, try again.Input an integer between 2 to 10: 20Input is not in the correct range, try again.Input an integer between 2 to 10: 21Input is not in the correct range, try again.Input an integer between 2 to 10: 6num4 = 6

Input an integer between 2 and 10: 9.4Input is not an integer, try again.Input an integer between 2 and 10: 25Input is not in the correct range, try again.Input an integer between 2 and 10: 32Input is not in the correct range, try again.Input an integer between 2 and 10: 2.4Input is not an integer, try again.Input an integer between 2 and 10: 8num5 = 8

Input an integer between 5 and 15: 0I said between 5 and 15, what word don't you understand?Input an integer between 5 and 15: 3.5This was not an integer, moron.Input an integer between 5 and 15: 47I said between 5 and 15, what word don't you understand?Input an integer between 5 and 15: 7num6 = 7

6

Introductory Java Examples

62 of 165.

Page 63: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

User Input Checking Examples

Objective: Create a segment of code that will check user input for an integer that is between 4 and 10. If the user types in something other than an integer the program should print an error message and ask for the input again. If the user types in an integer outside that range the program should print out another error message and ask for the input again. The program should ask for input until the user types in an integer between 4 and 10.

Solution: Solve the problem one step at a time, first get the integer input checking working and then deal with the range checking.

Step 1: Get the computer to not crash on a non integer input.

import java.util.Scanner;

public class UserInputChecking {

public static void main(String[] args) {Scanner keyboard = new Scanner(System.in);int num = 0;

try {System.out.print("Input an integer between 4 and 10: ");num = keyboard.nextInt();

} catch (Exception e) {System.out.println("Input is not an integer, try again.");

}

System.out.println(num);}

}

Runs:

Input an integer between 4 and 10: 6.3Input is not an integer, try again.0

Input an integer between 4 and 10: 55

Input an integer between 4 and 10: 6868

1

Introductory Java Examples

63 of 165.

Page 64: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

Step 2: Put this in a loop so that the input is asked for until the user types in an integer.

import java.util.Scanner;

public class UserInputChecking {

public static void main(String[] args) {Scanner keyboard = new Scanner(System.in);boolean goodinput = false;int num = 0;

do {try {

goodinput = true;System.out.print("Input an integer between 4 and 10: ");num = keyboard.nextInt();

} catch (Exception e) {System.out.println("Input is not an integer, try again.");goodinput = false;String clear = keyboard.nextLine();

}} while (!goodinput);

System.out.println(num);}

}

Run:

Input an integer between 4 and 10: 3.6Input is not an integer, try again.Input an integer between 4 and 10: 2.3Input is not an integer, try again.Input an integer between 4 and 10: 2525

2

Introductory Java Examples

64 of 165.

Page 65: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

Step 3: Add in range checking, easy to do since the framework has already been set up.

import java.util.Scanner;

public class UserInputChecking {

public static void main(String[] args) {Scanner keyboard = new Scanner(System.in);boolean goodinput = false;int num = 0;

do {try {

goodinput = true;System.out.print("Input an integer between 4 and 10: ");num = keyboard.nextInt();

if ((num < 4) || (num > 10)) {System.out.println("Input is not between 4 and 10, try again.");goodinput = false;

}

} catch (Exception e) {System.out.println("Input is not an integer, try again.");goodinput = false;String clear = keyboard.nextLine();

}} while (!goodinput);

System.out.println(num);}

}

Run:

Input an integer between 4 and 10: 6.3Input is not an integer, try again.Input an integer between 4 and 10: 2Input is not between 4 and 10, try again.Input an integer between 4 and 10: 66

3

Introductory Java Examples

65 of 165.

Page 66: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

Step 4: Although the problem has been solved, we can make it better. Place it in a function so that it can be used multiple times for different variable inputs.

import java.util.Scanner;

public class UserInputChecking {

public static int getIntreger4to10() {Scanner keyboard = new Scanner(System.in);boolean goodinput = false;int num = 0;

do {try {

goodinput = true;System.out.print("Input an integer between 4 and 10: ");num = keyboard.nextInt();

if ((num < 4) || (num > 10)) {System.out.println("Input is not between 4 and 10, try again.");goodinput = false;

}

} catch (Exception e) {System.out.println("Input is not an integer, try again.");goodinput = false;String clear = keyboard.nextLine();

}} while (!goodinput);

return num;}

public static void main(String[] args) {int num1 = getIntreger4to10();int num2 = getIntreger4to10();int num3 = getIntreger4to10();

System.out.println(num1 + " " + num2 + " " + num3);}

}

Run:

Input an integer between 4 and 10: 6.3Input is not an integer, try again.Input an integer between 4 and 10: 5Input an integer between 4 and 10: 56Input is not between 4 and 10, try again.Input an integer between 4 and 10: 2Input is not between 4 and 10, try again.Input an integer between 4 and 10: 4Input an integer between 4 and 10: 95 4 9

4

Introductory Java Examples

66 of 165.

Page 67: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

Step 5: Do a better job with the user interface. Add a parameter to change the input message so the user knows which number they are inputting.

import java.util.Scanner;

public class UserInputChecking {

public static int getIntreger4to10(String message) {Scanner keyboard = new Scanner(System.in);boolean goodinput = false;int num = 0;

do {try {

goodinput = true;System.out.print("Input the integer " + message + " between 4 and 10: ");num = keyboard.nextInt();

if ((num < 4) || (num > 10)) {System.out.println("Input is not between 4 and 10, try again.");goodinput = false;

}

} catch (Exception e) {System.out.println("Input is not an integer, try again.");goodinput = false;String clear = keyboard.nextLine();

}} while (!goodinput);

return num;}

public static void main(String[] args) {int num1 = getIntreger4to10("Number 1");int num2 = getIntreger4to10("Number 2");int num3 = getIntreger4to10("Number 3");

System.out.println(num1 + " " + num2 + " " + num3);}

}

Run:

Input the integer Number 1 between 4 and 10: 3Input is not between 4 and 10, try again.Input the integer Number 1 between 4 and 10: 6.5Input is not an integer, try again.Input the integer Number 1 between 4 and 10: 5Input the integer Number 2 between 4 and 10: 12Input is not between 4 and 10, try again.Input the integer Number 2 between 4 and 10: 15Input is not between 4 and 10, try again.Input the integer Number 2 between 4 and 10: 5.5Input is not an integer, try again.Input the integer Number 2 between 4 and 10: 9Input the integer Number 3 between 4 and 10: 45 9 4

5

Introductory Java Examples

67 of 165.

Page 68: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

Step 6: Generalize so that the function can be used for different range restrictions. Add two more parameters that allow the programmer to set the lower and upper bounds on the range of possible values.

import java.util.Scanner;

public class UserInputChecking {

public static int getIntregerAtoB(String message, int a, int b) {Scanner keyboard = new Scanner(System.in);boolean goodinput = false;int num = 0;

do {try {

goodinput = true;System.out.print("Input the integer " + message + " between " + a + " and "+ b + ": ");num = keyboard.nextInt();

if ((num < a) || (num > b)) {System.out.println("Input is not between "+ a + " and " + b + ", try again.");goodinput = false;

}

} catch (Exception e) {System.out.println("Input is not an integer, try again.");goodinput = false;String clear = keyboard.nextLine();

}} while (!goodinput);

return num;}

public static void main(String[] args) {int num1 = getIntregerAtoB("Number 1", 2, 10);int num2 = getIntregerAtoB("Number 2", 30, 40);int num3 = getIntregerAtoB("Number 3", 1, 5);

System.out.println(num1 + " " + num2 + " " + num3);}

}

Run:

Input the integer Number 1 between 2 and 10: 3.6Input is not an integer, try again.Input the integer Number 1 between 2 and 10: 1Input is not between 2 and 10, try again.Input the integer Number 1 between 2 and 10: 5Input the integer Number 2 between 30 and 40: 21Input is not between 30 and 40, try again.Input the integer Number 2 between 30 and 40: 35.9Input is not an integer, try again.Input the integer Number 2 between 30 and 40: 35Input the integer Number 3 between 1 and 5: -5Input is not between 1 and 5, try again.Input the integer Number 3 between 1 and 5: 3.6Input is not an integer, try again.Input the integer Number 3 between 1 and 5: 35 35 3

6

Introductory Java Examples

68 of 165.

Page 69: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

Step 7: Although the above examples are good exercise in the use of boolean variables you may notice that for this problem one does not need to use the boolean. It can be removed by altering the while statement as follows.

import java.util.Scanner;

public class UserInputCheckSave2 {

public static int getIntregerAtoB(String message, int a, int b) {Scanner keyboard = new Scanner(System.in);int num = 0;

do {try {

System.out.print("Input the integer " + message + " between " + a + " and "+ b + ": ");num = keyboard.nextInt();

if ((num < a) || (num > b)) {System.out.println("Input is not between "+ a + " and " + b + ", try again.");

}

} catch (Exception e) {System.out.println("Input is not an integer, try again.");String clear = keyboard.nextLine();

}} while ((num < a) || (num > b));

return num;}

public static void main(String[] args) {int num1 = getIntregerAtoB("Number 1", 2, 10);int num2 = getIntregerAtoB("Number 2", 30, 40);int num3 = getIntregerAtoB("Number 3", 1, 5);

System.out.println(num1 + " " + num2 + " " + num3);}

}

Run:

Input the integer Number 1 between 2 and 10: 5.3Input is not an integer, try again.Input the integer Number 1 between 2 and 10: 6.2Input is not an integer, try again.Input the integer Number 1 between 2 and 10: 89Input is not between 2 and 10, try again.Input the integer Number 1 between 2 and 10: 5Input the integer Number 2 between 30 and 40: 20Input is not between 30 and 40, try again.Input the integer Number 2 between 30 and 40: 35Input the integer Number 3 between 1 and 5: -2.3Input is not an integer, try again.Input the integer Number 3 between 1 and 5: 25 35 2

7

Introductory Java Examples

69 of 165.

Page 70: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

User Input Checking Using Exceptions

This example is the same as the last example from the User Input Checking handout except that it uses exceptions to determine if the input is invalid. So instead of asking the system what is waiting to come in as input it simply takes whatever input is there and if the input is not the right type the program will crash, but instead of terminating it will catch the crash (exception) and ask the user for another input.

import java.util.Scanner;public class UserInputTesting005 {

// Made the getInteger method more general by letting the user input// the prompt message and the error message.public static int getInteger(String message, String errorMessage) {

Scanner kb = new Scanner(System.in);

boolean inputNeeded = true;int value = 0;while (inputNeeded) {

System.out.print(message);try {

value = kb.nextInt();inputNeeded = false;

} catch (Exception e) {System.out.println(errorMessage);

}String clearbuf = kb.nextLine();

}return value;

}

// Added the functionality to check that an input is within a range// of numbers [low, high].public static int getInteger(int low, int high, String message,

String errorMessage, String rangeErrorMessage) {Scanner kb = new Scanner(System.in);

boolean inputNeeded = true;int value = 0;while (inputNeeded) {

System.out.print(message);try {

value = kb.nextInt();if (value < low || value > high)

System.out.println(rangeErrorMessage);else

inputNeeded = false;} catch (Exception e) {

System.out.println(errorMessage);}String clearbuf = kb.nextLine();

}return value;

}

1

Introductory Java Examples

70 of 165.

Page 71: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

// The following are overloads of the getInteger method that allow// the user to use some default messages.public static int getInteger() {

return getInteger("Input an integer: ","Input is not an integer, try again.");

}

public static int getInteger(String message) {return getInteger(message, "Input is not an integer, try again.");

}

public static int getInteger(int low, int high) {return getInteger(low, high, "Input an integer between " + low + " to "

+ high + ": ", "Input is not an integer, try again.","Input is not in the correct range, try again.");

}

public static int getInteger(int low, int high, String message) {return getInteger(low, high, message,

"Input is not an integer, try again.","Input is not in the correct range, try again.");

}

public static void main(String[] args) {int num = getInteger();System.out.println("num1 = " + num);System.out.println();

num = getInteger("Input num: ");System.out.println("num2 = " + num);System.out.println();

num = getInteger("Input an integer called num: ","Not an integer, moron.");

System.out.println("num3 = " + num);System.out.println();

num = getInteger(2, 10);System.out.println("num4 = " + num);System.out.println();

num = getInteger(2, 10, "Input an integer between 2 and 10: ");System.out.println("num5 = " + num);System.out.println();

num = getInteger(5, 15, "Input an integer between 5 and 15: ","This was not an integer, moron.","I said between 5 and 15, what word don't you understand?");

System.out.println("num6 = " + num);System.out.println();

}}

2

Introductory Java Examples

71 of 165.

Page 72: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

Run:

Input an integer: 3.6Input is not an integer, try again.Input an integer: 26num1 = 26

Input num: 2.8Input is not an integer, try again.Input num: 12num2 = 12

Input an integer called num: 6.265Not an integer, moron.Input an integer called num: 25num3 = 25

Input an integer between 2 to 10: 5.89Input is not an integer, try again.Input an integer between 2 to 10: 15Input is not in the correct range, try again.Input an integer between 2 to 10: 6num4 = 6

Input an integer between 2 and 10: 15Input is not in the correct range, try again.Input an integer between 2 and 10: 5.9Input is not an integer, try again.Input an integer between 2 and 10: 7num5 = 7

Input an integer between 5 and 15: 23.6This was not an integer, moron.Input an integer between 5 and 15: 10num6 = 10

3

Introductory Java Examples

72 of 165.

Page 73: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

Throwing Exceptions: Crashing Your Own Program

import java.util.Scanner;

public class ThrowingExceptions {

static void printSquares(int startingValue, int endingValue) {if ((startingValue <= 0) || (endingValue <= 0))

throw new IllegalArgumentException("Starting value and ending value must be positive.");

if (endingValue < startingValue)throw new IllegalArgumentException(

"Starting value must be less than or equal to ending value.");

for (int i = startingValue; i <= endingValue; i++) {System.out.print(i * i + " ");

}System.out.println();

}

public static void main(String[] args) {Scanner keyboard = new Scanner(System.in);

System.out.print("Input start: ");int start = keyboard.nextInt();System.out.print("Input end: ");int end = keyboard.nextInt();

printSquares(start, end);

}}

Runs:

Input start: 3Input end: 99 16 25 36 49 64 81

Input start: 7Input end: 3Exception in thread "main" java.lang.IllegalArgumentException: Starting value must be less than or equal to ending value.

at ThrowingExceptions.printSquares(ThrowingExceptions.java:11)at ThrowingExceptions.main(ThrowingExceptions.java:28)

Introductory Java Examples

73 of 165.

Page 74: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

import java.util.Scanner;

public class ThrowingExceptions2 {

static void printSquares(int startingValue, int endingValue) {if ((startingValue <= 0) || (endingValue <= 0))

throw new IllegalArgumentException("Starting value and ending value must be positive.");

if (endingValue < startingValue)throw new IllegalArgumentException(

"Starting value must be less than or equal to ending value.");

for (int i = startingValue; i <= endingValue; i++) {System.out.print(i * i + " ");

}System.out.println();

}

public static void main(String[] args) {Scanner keyboard = new Scanner(System.in);boolean expThrown = true;

while (expThrown) {expThrown = false;System.out.print("Input start: ");int start = keyboard.nextInt();System.out.print("Input end: ");int end = keyboard.nextInt();

try {printSquares(start, end);

} catch (IllegalArgumentException e) {expThrown = true;System.out.println(e.getMessage());

}}

}}

Run:

Input start: -3Input end: 2Starting value and ending value must be positive.Input start: 7Input end: 3Starting value must be less than or equal to ending value.Input start: 2Input end: 84 9 16 25 36 49 64

Introductory Java Examples

74 of 165.

Page 75: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

import java.util.Scanner;

public class ThrowingExceptions3 {

static void printSquares(int startingValue, int endingValue) {if ((startingValue <= 0) || (endingValue <= 0))

throw new IllegalArgumentException("Starting value and ending value must be positive.");

if (endingValue < startingValue)throw new IllegalArgumentException(

"Starting value must be less than or equal to ending value.");

for (int i = startingValue; i <= endingValue; i++) {System.out.print(i * i + " ");

}System.out.println();

}

public static void main(String[] args) {Scanner keyboard = new Scanner(System.in);boolean expThrown = true;

while (expThrown) {expThrown = false;System.out.print("Input start: ");int start = keyboard.nextInt();System.out.print("Input end: ");int end = keyboard.nextInt();

try {printSquares(start, end);

} catch (Exception e) {expThrown = true;System.out.println(e.getMessage());

}}

}}

Run:

Input start: 3Input end: -5Starting value and ending value must be positive.Input start: 9Input end: 3Starting value must be less than or equal to ending value.Input start: 3Input end: 99 16 25 36 49 64 81

Introductory Java Examples

75 of 165.

Page 76: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

import java.util.InputMismatchException;import java.util.Scanner;

public class ThrowingExceptions4 {

static void printSquares(int startingValue, int endingValue) {if ((startingValue <= 0) || (endingValue <= 0))

throw new IllegalArgumentException("Starting value and ending value must be positive.");

if (endingValue < startingValue)throw new IllegalArgumentException(

"Starting value must be less than or equal to ending value.");

for (int i = startingValue; i <= endingValue; i++) {System.out.print(i * i + " ");

}System.out.println();

}

public static void main(String[] args) {Scanner keyboard = new Scanner(System.in);boolean expThrown = true;

while (expThrown) {expThrown = false;int start;int end;

try {System.out.print("Input start: ");start = keyboard.nextInt();System.out.print("Input end: ");end = keyboard.nextInt();

printSquares(start, end);} catch (IllegalArgumentException e) {

expThrown = true;System.out.println(e.getMessage());

} catch (InputMismatchException e) {expThrown = true;System.out.println(e.getMessage());String str = keyboard.nextLine();

}}

}}

Run:

Input start: 3.6nullInput start: 3.6nullInput start: 6Input end: 56.5nullInput start: 26Input end: 25Starting value must be less than or equal to ending value.Input start: 23Input end: 52529 576 625 676 729 784 841 900 961 1024 1089 1156 1225 1296 1369 1444 1521 1600 1681 1764 1849 1936 2025 2116 2209 2304 2401 2500 2601 2704

Introductory Java Examples

76 of 165.

Page 77: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

Object Examples #1File: Triangle.javapublic class Triangle {

// Data Members

private double a;private double b;private double c;// Methods// Constructorpublic Triangle(double s1, double s2, double s3){

a = s1;b = s2;c = s3;

}

// Accessor Methodspublic double getSide1() {

return a;}

public double getSide2() {return b;

}

public double getSide3() {return c;

}

// Other Methodspublic double Area() {

double p = (a+b+c)/2;return Math.sqrt(p*(p-a)*(p-b)*(p-c));

}

public double Perimeter() {return a + b + c;

}

public boolean isRight() {boolean righttri = false;if (a*a+b*b == c*c)

righttri = true;if (a*a+c*c == b*b)

righttri = true;if (c*c+b*b == a*a)

righttri = true;return righttri;

}

public boolean isTriangle() {boolean tri = true;// Find longest legdouble longleg = a;if (b > longleg) longleg = b;if (c > longleg) longleg = c;// Check if the two shorter legs do add up to the length of the // longest leg.if (a+b+c-longleg <= longleg)

tri = false;return tri;

}}

Introductory Java Examples

77 of 165.

Page 78: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

File: ObjectExample001.javaimport java.util.Scanner;public class ObjectExample001 {

public static void main(String[] args) {Scanner keyboard = new Scanner(System.in);System.out.print("Input the lengths of the sides of the triangle, a b c: ");double a = keyboard.nextDouble();double b = keyboard.nextDouble();double c = keyboard.nextDouble();Triangle tri = new Triangle(a, b, c);if (tri.isTriangle()){

System.out.println("Area = " + tri.Area());System.out.println("Perimeter = " + tri.Perimeter());System.out.println("Right Triangle = " + tri.isRight());

}else

System.out.println("This is not a triangle.");}

}

Runs:

Input the lengths of the sides of the triangle, a b c: 3 4 5Area = 6.0Perimeter = 12.0Right Triangle = true

Input the lengths of the sides of the triangle, a b c: 5 6 9Area = 14.142135623730951Perimeter = 20.0Right Triangle = false

Input the lengths of the sides of the triangle, a b c: 2 3 7This is not a triangle.

Introductory Java Examples

78 of 165.

Page 79: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

File: NiftySequence.javapublic class NiftySequence {

// Data Membersprivate int startNum;private int len;private String seqstr;// Constructorpublic NiftySequence(int num){

startNum = num;createSequence();

}

// Accessor Methodspublic int start(){

return startNum;}

public int length(){return len;

}

public String toString(){return seqstr;

}

// private methodsprivate void createSequence(){

int n = startNum;len = 1;seqstr = "" + n + " ";while (n > 1){

if (n % 2 == 0){n = n/2;

}else{

n = 3*n+1;}len++;seqstr = seqstr + n + " ";

}}

}

File: ObjectExample002.javaimport java.util.Scanner;public class ObjectExample002 {

public static void main(String[] args) {Scanner keyboard = new Scanner(System.in);System.out.print("Input a number: ");int n = keyboard.nextInt();if (n > 0){

NiftySequence seq = new NiftySequence(n); System.out.println("Start: " + seq.start());System.out.println("Sequence: " + seq.toString());System.out.println("Length: " + seq.length());

}}

}

Run:Input a number: 25Start: 25Sequence: 25 76 38 19 58 29 88 44 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1 Length: 24

Introductory Java Examples

79 of 165.

Page 80: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

Object Examples #2File: Employee.java

public class Employee {private String name;private double wage;private double hours_worked;public Employee(String n, double w, double hw){

name = n;if (w > 0)

wage = w;else

wage = 0;

if (hw > 0) hours_worked = hw;

elsehours_worked = 0;

}

public String getName(){return name;

}

public double getWage(){return wage;

}

public double getHoursWorked(){return hours_worked;

}

public void setName(String n){name = n;

}

public void setWage(double w){if (w > 0)

wage = w;else

wage = 0;}

public void getHoursWorked(double hw){if (hw > 0)

hours_worked = hw;else

hours_worked = 0;}

public double pay(){double payment = 0;if (hours_worked > 40)

payment = wage*40 + (hours_worked-40)*wage*1.5;else

payment = wage*hours_worked;

return payment;}

}

Introductory Java Examples

80 of 165.

Page 81: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

File: ObjectExample003.java

import java.util.Scanner;public class ObjectExample003 {

public static void main(String[] args) {Scanner keyboard = new Scanner(System.in);System.out.print("Input employee name: ");String name = keyboard.nextLine();System.out.print("Input employee wage: ");double wage = keyboard.nextDouble();System.out.print("Input hours worked: ");double hours = keyboard.nextDouble();Employee emp = new Employee(name, wage, hours);System.out.println();System.out.println("Employee Record");System.out.println("Name: " + emp.getName());System.out.println("Wage: " + emp.getWage());System.out.println("Hours Worked: " + emp.getHoursWorked());System.out.println("Pay: " + emp.pay());

}}

Run:

Input employee name: Don SpicklerInput employee wage: 12.5Input hours worked: 45

Employee RecordName: Don SpicklerWage: 12.5Hours Worked: 45.0Pay: 593.75

Introductory Java Examples

81 of 165.

Page 82: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

File: ObjectExample004.java

public class ObjectExample004 {public static void PrintRecord(Employee employee) {

System.out.println("Name: " + employee.getName());System.out.println("Wage: " + employee.getWage());System.out.println("Hours Worked: " + employee.getHoursWorked());System.out.printf("Pay: %.2f \n", employee.pay());System.out.println();

}

public static void main(String[] args) {Employee emp1 = new Employee("Don Spickler", 12.5, 52);Employee emp2 = new Employee("John Doe", 23.54, 37);Employee emp3 = new Employee("Jane Q. Public", 15.47, 48);Employee emp4 = new Employee("Sue Me", 30, 25);System.out.println("Payment List");PrintRecord(emp1);PrintRecord(emp2);PrintRecord(emp3);PrintRecord(emp4);

double payout = emp1.pay() + emp2.pay() + emp3.pay() + emp4.pay();System.out.println("Company Payout: " + payout);

}}

Run:

Payment ListName: Don SpicklerWage: 12.5Hours Worked: 52.0Pay: 725.00

Name: John DoeWage: 23.54Hours Worked: 37.0Pay: 870.98

Name: Jane Q. PublicWage: 15.47Hours Worked: 48.0Pay: 804.44

Name: Sue MeWage: 30.0Hours Worked: 25.0Pay: 750.00

Company Payout: 3150.42

Introductory Java Examples

82 of 165.

Page 83: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

Object Example 3Card Class:

public class Card {private String value;private String suit;

public Card(String v, String s) {value = v;suit = s;

}

public String getValue() {return value;

}

public String getSuit() {return suit;

}

public int getWorth() {if (value.equals("A"))

return 1;else if (value.equals("2"))

return 2;else if (value.equals("3"))

return 3;else if (value.equals("4"))

return 4;else if (value.equals("5"))

return 5;else if (value.equals("6"))

return 6;else if (value.equals("7"))

return 7;else if (value.equals("8"))

return 8;else if (value.equals("9"))

return 9;else

return 10;}

public int getWorth(int ace) {if (value.equals("A"))

return ace;else if (value.equals("2"))

return 2;else if (value.equals("3"))

return 3;else if (value.equals("4"))

return 4;else if (value.equals("5"))

return 5;else if (value.equals("6"))

return 6;else if (value.equals("7"))

return 7;else if (value.equals("8"))

return 8;else if (value.equals("9"))

return 9;else

return 10;}

1

Introductory Java Examples

83 of 165.

Page 84: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

public boolean isAce() {return value.equals("A");

}

public boolean equals(Card card2) {return value.equals(card2.getValue()) && suit.equals(card2.getSuit());

}

public String toString() {return value + " " + suit;

}

public String toString(boolean space) {String retstr = value;if (space)

retstr += " ";retstr += suit;return retstr;

}

}

2

Introductory Java Examples

84 of 165.

Page 85: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

Deck Class:

import java.util.Random;

public class Deck {private Card deck[] = new Card[52];private int top = 0;

public Deck() {int pos = 0;for (int i = 0; i < 4; i++)

for (int j = 0; j < 13; j++) {String suit = "";String value = "";

if (i == 0)suit = "H";

else if (i == 1)suit = "D";

else if (i == 2)suit = "C";

else if (i == 3)suit = "S";

if (j == 0)value = "A";

else if (j == 10)value = "J";

else if (j == 11)value = "Q";

else if (j == 12)value = "K";

elsevalue = "" + (j + 1);

deck[pos] = new Card(value, suit);pos++;

}}

public void PrintDeck() {for (int i = 0; i < deck.length; i++) {

System.out.print(deck[i].toString(false) + " ");}System.out.println();

}

public Deck copyDeck(){Deck tempdeck = new Deck();

for (int i = 0; i < 52; i++){tempdeck.deck[i] = new Card(deck[i].getValue(), deck[i].getSuit());

}

return tempdeck;}

public void RiffleShuffleDeck() {Random generator = new Random();Card tempdeck[] = new Card[deck.length];

for (int i = 0; i < 7; i++) {int tempdeckpos = 0;int mid = deck.length / 2;int start = 0;

3

Introductory Java Examples

85 of 165.

Page 86: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

while (tempdeckpos < deck.length) {int side = generator.nextInt(2);

if (side == 0) {int skip1 = generator.nextInt(3) + 1;if (start < deck.length / 2) {

if (start + skip1 > deck.length / 2)skip1 = deck.length / 2 - start;

for (int j = start; j < start + skip1; j++) {tempdeck[tempdeckpos] = deck[j];tempdeckpos++;

}}start += skip1;

} else {int skip2 = generator.nextInt(3) + 1;if (mid < deck.length) {

if (mid + skip2 > deck.length)skip2 = deck.length - mid;

for (int j = mid; j < mid + skip2; j++) {tempdeck[tempdeckpos] = deck[j];tempdeckpos++;

}}mid += skip2;

}}

for (int j = 0; j < deck.length; j++)deck[j] = tempdeck[j];

}top = 0;

}

public void InterchangeShuffleDeck() {Random generator = new Random();

for (int i = 0; i < 100; i++) {int card1 = generator.nextInt(52);int card2 = generator.nextInt(52);Card tempcard = deck[card1];deck[card1] = deck[card2];deck[card2] = tempcard;

}top = 0;

}

public void ShuffleDeck(Card[] deck) {InterchangeShuffleDeck();

}

public Card dealCard() {return deck[top++];

}

public void resetTop(){top = 0;

}

}

4

Introductory Java Examples

86 of 165.

Page 87: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

PokerHand Class:

public class PokerHand {private Card hand[] = new Card[5];int cardsInHand = 0;

public PokerHand() {cardsInHand = 0;

}

public void clearHand() {cardsInHand = 0;

}

public void addToHand(Card card) {if (cardsInHand < 5)

hand[cardsInHand++] = new Card(card.getValue(), card.getSuit());}

public void PrintHand() {for (int i = 0; i < cardsInHand; i++) {

System.out.print(hand[i].toString(false) + " ");}System.out.println();

}

}

5

Introductory Java Examples

87 of 165.

Page 88: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

Main:

public class ObjectExample005 {

public static void main(String[] args) {Deck cards = new Deck();Deck cards2 = new Deck();

System.out.print("Cards: ");cards.PrintDeck();cards.InterchangeShuffleDeck();System.out.print("Cards: ");cards.PrintDeck();

System.out.println();

Deck cards3 = cards.copyDeck();System.out.print("Cards: ");cards.PrintDeck();System.out.print("Cards3: ");cards3.PrintDeck();

System.out.println();

cards.InterchangeShuffleDeck();System.out.print("Cards: ");cards.PrintDeck();System.out.print("Cards3: ");cards3.PrintDeck();

System.out.println();

PokerHand hand1 = new PokerHand();PokerHand hand2 = new PokerHand();cards.RiffleShuffleDeck();System.out.print("Cards: ");cards.PrintDeck();

for (int i = 0; i < 5; i++) {hand1.addToHand(cards.dealCard());hand2.addToHand(cards.dealCard());

}

System.out.println();hand1.PrintHand();hand2.PrintHand();

hand1.addToHand(cards.dealCard());hand2.addToHand(cards.dealCard());System.out.println();

hand1.PrintHand();hand2.PrintHand();

System.out.println();

hand1.clearHand();hand2.clearHand();cards.RiffleShuffleDeck();System.out.print("Cards: ");cards.PrintDeck();

System.out.println();hand1.addToHand(cards.dealCard());hand2.addToHand(cards.dealCard());hand1.PrintHand();hand2.PrintHand();

6

Introductory Java Examples

88 of 165.

Page 89: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

hand1.addToHand(cards.dealCard());hand2.addToHand(cards.dealCard());hand1.PrintHand();hand2.PrintHand();

hand1.addToHand(cards.dealCard());hand2.addToHand(cards.dealCard());hand1.PrintHand();hand2.PrintHand();

}

}

7

Introductory Java Examples

89 of 165.

Page 90: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

Run:

Cards: AH 2H 3H 4H 5H 6H 7H 8H 9H 10H JH QH KH AD 2D 3D 4D 5D 6D 7D 8D 9D 10D JD QD KD AC 2C 3C 4C 5C 6C 7C 8C 9C 10C JC QC KC AS 2S 3S 4S 5S 6S 7S 8S 9S 10S JS QS KS Cards: 7D JC 10H 2H 5S JS 9H 3D 5D KD 3H 7S KH 4S AS AH QH 10C 5H 7C 6D JD AC QC 6H KS QS 3C 8C KC 6S 2C JH 8S 10S 7H 9D 9S AD 2D 9C QD 6C 4H 5C 2S 8H 4C 10D 4D 8D 3S

Cards: 7D JC 10H 2H 5S JS 9H 3D 5D KD 3H 7S KH 4S AS AH QH 10C 5H 7C 6D JD AC QC 6H KS QS 3C 8C KC 6S 2C JH 8S 10S 7H 9D 9S AD 2D 9C QD 6C 4H 5C 2S 8H 4C 10D 4D 8D 3S Cards3: 7D JC 10H 2H 5S JS 9H 3D 5D KD 3H 7S KH 4S AS AH QH 10C 5H 7C 6D JD AC QC 6H KS QS 3C 8C KC 6S 2C JH 8S 10S 7H 9D 9S AD 2D 9C QD 6C 4H 5C 2S 8H 4C 10D 4D 8D 3S

Cards: JC 5D QC AS 7S 2D 10D QH 8S 8D AH 4H 6D 9S 8C KS 6H 10S 8H 5S 9H 3H 10H QD 5H 7H QS 3D 4S 9D 4D 7D KH 2H 9C 4C AD 2C AC 5C JS 6C JD 3C 10C 2S 6S JH 3S KD KC 7C Cards3: 7D JC 10H 2H 5S JS 9H 3D 5D KD 3H 7S KH 4S AS AH QH 10C 5H 7C 6D JD AC QC 6H KS QS 3C 8C KC 6S 2C JH 8S 10S 7H 9D 9S AD 2D 9C QD 6C 4H 5C 2S 8H 4C 10D 4D 8D 3S

Cards: 9S 6C JH QH 10D 4H 6D 3S 3D 4C 8S KS AH 7H 6S JD 8C 8D JS 5S 2H 7S QS 9D 2S 3C KH JC 5D 7D 10C 10H 6H 10S KD 4D QD 9C AD 5C 9H 3H QC AS 2C 5H 2D 8H 4S AC KC 7C

9S JH 10D 6D 3D 6C QH 4H 3S 4C

9S JH 10D 6D 3D 6C QH 4H 3S 4C

Cards: 8S 8H 10H 4S AC KC KH JC AD 8C JS 8D QS JH QH 3C 4H 9S 7D 7C AS 7S 2S 5H 2C QD 9C 2D JD 6D 3S 3D 6H 10S KD 3H 9D 5C 9H 4D 5D 6S 5S 10D KS 2H AH 10C 7H 6C QC 4C

8S 8H 8S 10H 8H 4S 8S 10H AC 8H 4S KC

8

Introductory Java Examples

90 of 165.

Page 91: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

Array Examples #1public class ArrayExample001 {

public static void main(String[] args) {int intArray[] = new int[5];int [] intArray2 = new int[10];for (int i = 0; i < 5; i++){

intArray[i] = i*i;}

for (int i = 0; i < 5; i++){System.out.print(intArray[i] + " ");

}

System.out.println();

for (int i = 0; i < 10; i++){intArray2[i] = i*i*i;

}

for (int i = 0; i < 10; i++){System.out.print(intArray2[i] + " ");

}}

}

Run:

0 1 4 9 16 0 1 8 27 64 125 216 343 512 729

Introductory Java Examples

91 of 165.

Page 92: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

import java.util.Scanner;public class ArrayExample002 {

public static void main(String[] args) {Scanner keyboard = new Scanner(System.in);System.out.print("Input the array size: ");int arraySize = keyboard.nextInt();int intArray[] = new int[arraySize];for (int i = 0; i < intArray.length; i++){

intArray[i] = i*i;}

for (int i = 0; i < intArray.length; i++){System.out.print(intArray[i] + " ");

}}

}

Runs:

Input the array size: 50 1 4 9 16

Input the array size: 120 1 4 9 16 25 36 49 64 81 100 121

Input the array size: 1000 1 4 9 16 25 36 49 64 81 100 121 144 169 196 225 256 289 324 361 400 441 484 529 576 625 676 729 784 841 900 961 1024 1089 1156 1225 1296 1369 1444 1521 1600 1681 1764 1849 1936 2025 2116 2209 2304 2401 2500 2601 2704 2809 2916 3025 3136 3249 3364 3481 3600 3721 3844 3969 4096 4225 4356 4489 4624 4761 4900 5041 5184 5329 5476 5625 5776 5929 6084 6241 6400 6561 6724 6889 7056 7225 7396 7569 7744 7921 8100 8281 8464 8649 8836 9025 9216 9409 9604 9801

Introductory Java Examples

92 of 165.

Page 93: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

import java.util.Scanner;public class ArrayExample003 {

public static void PopulateArray(int [] A) {Scanner keyboard = new Scanner(System.in);for (int i = 0; i < A.length; i++){

System.out.print("Input entry " + (i+1) + ": ");A[i] = keyboard.nextInt();

}}

public static void PrintArray(int [] Arr) {for (int i = 0; i < Arr.length; i++){

System.out.println(Arr[i] + " ");}

}

public static int SumArray(int [] Arr) {int sum = 0;for (int i = 0; i < Arr.length; i++){

sum += Arr[i];}return sum;

}

public static void main(String[] args) {Scanner keyboard = new Scanner(System.in);System.out.print("Input the array size: ");int arraySize = keyboard.nextInt();int intArray[] = new int[arraySize];PopulateArray(intArray);PrintArray(intArray);System.out.println("The sum of the array is = " + SumArray(intArray));

}}

Run:

Input the array size: 7Input entry 1: 1Input entry 2: 6Input entry 3: 4Input entry 4: 8Input entry 5: 9Input entry 6: 2Input entry 7: 121 6 4 8 9 2 12 The sum of the array is = 42

Introductory Java Examples

93 of 165.

Page 94: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

public class Employee {private String name;private double wage;private double hours_worked;public Employee(String n, double w, double hw){

name = n;if (w > 0)

wage = w;else

wage = 0;

if (hw > 0) hours_worked = hw;

elsehours_worked = 0;

}

public String getName(){return name;

}

public double getWage(){return wage;

}

public double getHoursWorked(){return hours_worked;

}

public void setName(String n){name = n;

}

public void setWage(double w){if (w > 0)

wage = w;else

wage = 0;}

public void getHoursWorked(double hw){if (hw > 0)

hours_worked = hw;else

hours_worked = 0;}

public double pay(){double payment = 0;if (hours_worked > 40)

payment = wage*40 + (hours_worked-40)*wage*1.5;else

payment = wage*hours_worked;

return payment;}

}

Introductory Java Examples

94 of 165.

Page 95: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

import java.util.Scanner;public class ArrayExample004 {

public static void InputEmployees(Employee [] A) {Scanner keyboard = new Scanner(System.in);for (int i = 0; i < A.length; i++){

System.out.print("Employee " + (i+1) + " name: ");String name = keyboard.nextLine();System.out.print("Employee " + (i+1) + " wage: ");double wage = keyboard.nextDouble();System.out.print("Employee " + (i+1) + " hours worked: ");double hours = keyboard.nextDouble();Employee emp = new Employee(name, wage, hours);A[i] = emp;

System.out.println(); // Put space between inputs.String clear = keyboard.nextLine(); // clear the end of line.

}}

public static void PrintPayReport(Employee [] A) {for (int i = 0; i < A.length; i++){

PrintRecord(A[i]);}

}

public static double CalculateTotalPay(Employee [] A) {double totalpay = 0;for (int i = 0; i < A.length; i++){

totalpay += A[i].pay();}return totalpay;

}

public static void PrintRecord(Employee employee) {System.out.println("Name: " + employee.getName());System.out.println("Wage: " + employee.getWage());System.out.println("Hours Worked: " + employee.getHoursWorked());System.out.printf("Pay: %.2f \n", employee.pay());System.out.println();

}

public static void main(String[] args) {Scanner keyboard = new Scanner(System.in);System.out.print("Input the number of employees: ");int arraySize = keyboard.nextInt();Employee company[] = new Employee[arraySize];InputEmployees(company);PrintPayReport(company);double totpay = CalculateTotalPay(company);System.out.printf("Company payout = %.2f \n", totpay);

}}

Introductory Java Examples

95 of 165.

Page 96: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

Input the number of employees: 3Employee 1 name: Don SpicklerEmployee 1 wage: 12.56Employee 1 hours worked: 84

Employee 2 name: John DoeEmployee 2 wage: 15.8Employee 2 hours worked: 40

Employee 3 name: Sue MeEmployee 3 wage: 27.96Employee 3 hours worked: 45

Name: Don SpicklerWage: 12.56Hours Worked: 84.0Pay: 1331.36

Name: John DoeWage: 15.8Hours Worked: 40.0Pay: 632.00

Name: Sue MeWage: 27.96Hours Worked: 45.0Pay: 1328.10

Company payout = 3291.46

Introductory Java Examples

96 of 165.

Page 97: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

Array Examples #2: Multi-Dimensional Arrayspublic class ArrayExample005 {

public static void main(String[] args) {int TwoDimArray [][] = new int[5][7];TwoDimArray[3][4] = 2;TwoDimArray[1][6] = 12;TwoDimArray[2][1] = -4;

for (int i = 0; i < 5; i++){for (int j = 0; j < 7; j++){

System.out.printf("%4d", TwoDimArray[i][j]);}System.out.println();

}

System.out.println();System.out.println();

int dim1 = TwoDimArray.length; // Gets the number of rowsint dim2 = TwoDimArray[0].length; // Gets the number of columnsSystem.out.println(dim1 + " " + dim2);System.out.println();System.out.println();

for (int i = 0; i < dim1; i++){for (int j = 0; j < dim2; j++){

System.out.printf("%4d", TwoDimArray[i][j]);}System.out.println();

}

for (int i = 0; i < dim1; i++){for (int j = 0; j < dim2; j++){

TwoDimArray[i][j] = 2*i+j;}

}

System.out.println();System.out.println();

for (int i = 0; i < dim1; i++){for (int j = 0; j < dim2; j++){

System.out.printf("%4d", TwoDimArray[i][j]);}System.out.println();

}

}}

Introductory Java Examples

97 of 165.

Page 98: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

Runs:

0 0 0 0 0 0 0 0 0 0 0 0 0 12 0 -4 0 0 0 0 0 0 0 0 0 2 0 0 0 0 0 0 0 0 0

5 7

0 0 0 0 0 0 0 0 0 0 0 0 0 12 0 -4 0 0 0 0 0 0 0 0 0 2 0 0 0 0 0 0 0 0 0

0 1 2 3 4 5 6 2 3 4 5 6 7 8 4 5 6 7 8 9 10 6 7 8 9 10 11 12 8 9 10 11 12 13 14

Introductory Java Examples

98 of 165.

Page 99: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

public class ArrayExample006 {public static void Print2DintArray(int A[][]) {

int dim1 = A.length; // Gets the number of rowsint dim2 = A[0].length; // Gets the number of columnsfor (int i = 0; i < dim1; i++){

for (int j = 0; j < dim2; j++){System.out.printf("%4d", A[i][j]);

}System.out.println();

}}

public static void doubleArray(int [][] A) {int dim1 = A.length; // Gets the number of rowsint dim2 = A[0].length; // Gets the number of columnsfor (int i = 0; i < dim1; i++){

for (int j = 0; j < dim2; j++){A[i][j] = A[i][j]*2;

}}

}

public static void main(String[] args) {int arr1 [][] = new int[5][7];int [][] arr2 = new int[12][5];for (int i = 0; i < 5; i++){

for (int j = 0; j < 7; j++){arr1[i][j] = 2*i+j;

}}

for (int i = 0; i < 12; i++){for (int j = 0; j < 5; j++){

arr2[i][j] = i-j;}

}

Print2DintArray(arr1);System.out.println();Print2DintArray(arr2);

doubleArray(arr1);System.out.println();Print2DintArray(arr1);

}}

Introductory Java Examples

99 of 165.

Page 100: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

Run:

0 1 2 3 4 5 6 2 3 4 5 6 7 8 4 5 6 7 8 9 10 6 7 8 9 10 11 12 8 9 10 11 12 13 14

0 -1 -2 -3 -4 1 0 -1 -2 -3 2 1 0 -1 -2 3 2 1 0 -1 4 3 2 1 0 5 4 3 2 1 6 5 4 3 2 7 6 5 4 3 8 7 6 5 4 9 8 7 6 5 10 9 8 7 6 11 10 9 8 7

0 2 4 6 8 10 12 4 6 8 10 12 14 16 8 10 12 14 16 18 20 12 14 16 18 20 22 24 16 18 20 22 24 26 28

Introductory Java Examples

100 of 165.

Page 101: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

import java.util.Scanner;public class ArrayExample007 {

public static void Print2DintArray(int A[][]) {int dim1 = A.length; // Gets the number of rowsint dim2 = A[0].length; // Gets the number of columnsfor (int i = 0; i < dim1; i++){

for (int j = 0; j < dim2; j++){System.out.printf("%4d", A[i][j]);

}System.out.println();

}}

public static void main(String[] args) {Scanner keyboard = new Scanner(System.in);System.out.print("Input the number of rows: ");int rows = keyboard.nextInt();System.out.print("Input the number of columns: ");int cols = keyboard.nextInt();int arr1 [][] = new int[rows][cols];for (int i = 0; i < rows; i++){

for (int j = 0; j < cols; j++){arr1[i][j] = i+j;

}}

Print2DintArray(arr1);}

}

Run:

Input the number of rows: 5Input the number of columns: 7 0 1 2 3 4 5 6 1 2 3 4 5 6 7 2 3 4 5 6 7 8 3 4 5 6 7 8 9 4 5 6 7 8 9 10

Introductory Java Examples

101 of 165.

Page 102: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

import java.util.Random;import java.util.Scanner;public class ArrayExample008 {

public static void PrintSales(int A[][]) {int dim1 = A.length; // Gets the number of rowsint dim2 = A[0].length; // Gets the number of columnsSystem.out.printf("%8s", "");for (int j = 0; j < dim2-1; j++){

System.out.printf("%4s", "P"+(j+1));}System.out.printf("%4s", "Tot");System.out.println();

for (int i = 0; i < dim1; i++){if (i < dim1-1)

System.out.printf("%8s", "Week " + (i+1));else

System.out.printf("%8s", "Total");for (int j = 0; j < dim2; j++){

System.out.printf("%4d", A[i][j]);}System.out.println();

}}

public static void main(String[] args) {Random generator = new Random();Scanner keyboard = new Scanner(System.in);System.out.print("Input the number of weeks: ");int weeks = keyboard.nextInt();System.out.print("Input the number of sales people: ");int sales = keyboard.nextInt();int salesChart [][] = new int[weeks+1][sales+1];for (int i = 0; i < weeks; i++){

for (int j = 0; j < sales; j++){salesChart[i][j] = generator.nextInt(21);

}}

for (int i = 0; i < weeks; i++){int weekTotal = 0;for (int j = 0; j < sales; j++){

weekTotal += salesChart[i][j]; }salesChart[i][sales] = weekTotal;

}

for (int i = 0; i < sales; i++){int personTotal = 0;for (int j = 0; j < weeks; j++){

personTotal += salesChart[j][i]; }salesChart[weeks][i] = personTotal;

}

int total = 0;for (int j = 0; j < weeks; j++){

total += salesChart[j][sales]; }salesChart[weeks][sales] = total;

PrintSales(salesChart);}

}

Introductory Java Examples

102 of 165.

Page 103: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

Runs:

Input the number of weeks: 5Input the number of sales people: 10 P1 P2 P3 P4 P5 P6 P7 P8 P9 P10 Tot Week 1 13 18 0 5 10 7 4 3 3 8 71 Week 2 8 20 6 18 12 18 5 16 16 0 119 Week 3 2 15 4 0 15 9 20 10 18 8 101 Week 4 7 13 5 13 8 6 10 0 4 19 85 Week 5 1 8 3 4 19 4 3 20 8 8 78 Total 31 74 18 40 64 44 42 49 49 43 454

Input the number of weeks: 15Input the number of sales people: 3 P1 P2 P3 Tot Week 1 18 19 8 45 Week 2 15 4 0 19 Week 3 13 18 14 45 Week 4 9 7 19 35 Week 5 14 0 9 23 Week 6 4 15 6 25 Week 7 5 13 6 24 Week 8 2 6 5 13 Week 9 12 11 5 28 Week 10 0 5 1 6 Week 11 2 4 7 13 Week 12 14 12 0 26 Week 13 11 18 12 41 Week 14 9 10 10 29 Week 15 5 10 6 21 Total 133 152 108 393

Input the number of weeks: 3Input the number of sales people: 15 P1 P2 P3 P4 P5 P6 P7 P8 P9 P10 P11 P12 P13 P14 P15 Tot Week 1 7 4 15 16 2 0 6 10 1 10 13 20 10 5 0 119 Week 2 16 8 19 16 20 14 10 6 10 6 4 2 5 3 0 139 Week 3 0 9 1 9 9 5 14 20 17 7 11 18 7 5 20 152 Total 23 21 35 41 31 19 30 36 28 23 28 40 22 13 20 410

Introductory Java Examples

103 of 165.

Page 104: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

import java.util.Scanner;public class ArrayExample009 {

public static void PrintBoard(char A[][]) {for (int i = 0; i < 3; i++){

for (int j = 0; j < 3; j++){if (j == 0)

System.out.print(" ");

if (j < 2)System.out.print(A[i][j] + " | ");

elseSystem.out.print(A[i][j]);

}System.out.println();if (i < 2)

System.out.println("-----------");}

}

public static int RowCount(char A[][], int row, char c) {int count = 0;for (int i = 0; i < 3; i++)

if (A[row][i] == c) count++;return count;

}

public static int RowSpacePos(char A[][], int row) {int pos = -1;for (int i = 0; i < 3; i++)

if (A[row][i] == ' ') pos = i;

return pos;}

public static int ColCount(char A[][], int col, char c) {int count = 0;for (int i = 0; i < 3; i++)

if (A[i][col] == c) count++;return count;

}

public static int ColSpacePos(char A[][], int col) {int pos = -1;for (int i = 0; i < 3; i++)

if (A[i][col] == ' ') pos = i;

return pos;}

public static int DiagCount(char A[][], int diag, char c) {int count = 0;if (diag == 1){

for (int i = 0; i < 3; i++)if (A[i][i] == c) count++;

}else{for (int i = 0; i < 3; i++)

if (A[2-i][i] == c) count++;}

return count;}

public static int DiagSpacePos(char A[][], int diag) {int pos = -1;if (diag == 1){

for (int i = 0; i < 3; i++)if (A[i][i] == ' ') pos = i;

Introductory Java Examples

104 of 165.

Page 105: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

}else{for (int i = 0; i < 3; i++)

if (A[2-i][i] == ' ') pos = i;}

return pos;}

public static void PlaceO(char A[][]) {// Finish game if possible.for (int i = 0; i < 3; i++){

if ((RowCount(A, i, 'O') == 2) && (RowSpacePos(A, i) >= 0)){A[i][RowSpacePos(A,i)] = 'O';return;

}}

for (int i = 0; i < 3; i++){if ((ColCount(A, i, 'O') == 2) && (ColSpacePos(A,i) >= 0)){

A[ColSpacePos(A,i)][i] = 'O';return;

}}

for (int i = 0; i < 2; i++){if ((DiagCount(A, i, 'O') == 2) && (DiagSpacePos(A,i) >= 0)){

A[DiagSpacePos(A,i)][DiagSpacePos(A,i)] = 'O';return;

}}

// Block a win.for (int i = 0; i < 3; i++){

if ((RowCount(A, i, 'X') == 2) && (RowSpacePos(A, i) >= 0)) {A[i][RowSpacePos(A,i)] = 'O';return;

}}

for (int i = 0; i < 3; i++){if ((ColCount(A, i, 'X') == 2) && (ColSpacePos(A,i) >= 0)){

A[ColSpacePos(A,i)][i] = 'O';return;

}}

for (int i = 0; i < 2; i++){if ((DiagCount(A, i, 'X') == 2) && (DiagSpacePos(A, i) >= 0)){

A[2-DiagSpacePos(A,i)][DiagSpacePos(A,i)] = 'O';return;

}}

// Progress to a win.for (int i = 0; i < 3; i++){

if ((RowCount(A, i, 'X') == 0) && (RowCount(A, i, 'O') > 0) && (RowSpacePos(A, i) >= 0)) {A[i][RowSpacePos(A,i)] = 'O';return;

}}

for (int i = 0; i < 3; i++){if ((ColCount(A, i, 'X') == 0) && (ColCount(A, i, 'O') > 0) && (ColSpacePos(A,i) >= 0)){

A[ColSpacePos(A,i)][i] = 'O';return;

}}

for (int i = 0; i < 2; i++){if ((DiagCount(A, i, 'X') == 0) && (DiagCount(A, i, 'O') > 0) && (DiagSpacePos(A, i) >= 0)){

A[2-DiagSpacePos(A,i)][DiagSpacePos(A,i)] = 'O';return;

}}

Introductory Java Examples

105 of 165.

Page 106: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

// Go for a corner.if (A[0][0] == ' '){

A[0][0] = 'O';return;

}

if (A[0][2] == ' '){A[0][2] = 'O';return;

}

if (A[2][0] == ' '){A[2][0] = 'O';return;

}

if (A[2][2] == ' '){A[2][2] = 'O';return;

}

// Go for the center

if (A[1][1] == ' '){A[1][1] = 'O';return;

}

// Go to one of the middle row positions.

if (A[0][1] == ' '){A[0][1] = 'O';return;

}

if (A[1][0] == ' '){A[1][0] = 'O';return;

}

if (A[1][2] == ' '){A[1][2] = 'O';return;

}

if (A[2][1] == ' '){A[2][1] = 'O';return;

}}

public static boolean CheckWin(char A[][]) {for (int i = 0; i < 3; i++){

if (RowCount(A, i, 'X') == 3){System.out.println("X wins.");return true;

}}

for (int i = 0; i < 3; i++){if (ColCount(A, i, 'X') == 3){

System.out.println("X wins.");return true;

}}

for (int i = 0; i < 2; i++){if (DiagCount(A, i, 'X') == 3){

System.out.println("X wins.");return true;

}}

Introductory Java Examples

106 of 165.

Page 107: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

for (int i = 0; i < 3; i++){if (RowCount(A, i, 'O') == 3){

System.out.println("O wins.");return true;

}}

for (int i = 0; i < 3; i++){if (ColCount(A, i, 'O') == 3){

System.out.println("O wins.");return true;

}}

for (int i = 0; i < 2; i++){if (DiagCount(A, i, 'O') == 3){

System.out.println("O wins.");return true;

}}

int spacecount = 0;for (int i = 0; i < 3; i++)

for (int j = 0; j < 3; j++)if (A[i][j] == ' ')

spacecount++;

if (spacecount == 0){System.out.println("No Winner");return true;

}

return false;}

public static void main(String[] args) {char TTT[][] = new char [3][3];boolean gameover = false;Scanner keyboard = new Scanner(System.in);// Clear the board.for (int i = 0; i < 3; i++)

for (int j = 0; j < 3; j++)TTT[i][j] = ' ';

while (!gameover){boolean badSelection = true;int row = 1;int col = 1;while (badSelection){

System.out.print("Input the row of next move (1-3): ");row = keyboard.nextInt();System.out.print("Input the column of next move (1-3): ");col = keyboard.nextInt();badSelection = false;if ((row < 1) || (row > 3) || (col < 1) || (col > 3))

badSelection = true;if (badSelection)

System.out.println("Invalid selection, please try again.");}

// array indexes start at 0 so adjust values.row--;col--;

if (TTT[row][col] == ' '){TTT[row][col] = 'X';gameover = CheckWin(TTT);if (!gameover){

PlaceO(TTT);gameover = CheckWin(TTT);

}

Introductory Java Examples

107 of 165.

Page 108: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

}else

System.out.println("Invalid selection, please try again.");

PrintBoard(TTT);}

}}

Run:

Input the row of next move (1-3): 1Input the column of next move (1-3): 1 X | | O----------- | | ----------- | | Input the row of next move (1-3): 3Input the column of next move (1-3): 3 X | | O----------- | O | ----------- | | XInput the row of next move (1-3): 3Input the column of next move (1-3): 1 X | | O----------- | O | ----------- X | O | XInput the row of next move (1-3): 2Input the column of next move (1-3): 1X wins. X | | O----------- X | O | ----------- X | O | X

Introductory Java Examples

108 of 165.

Page 109: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

Array Example #3

import java.util.Random;import java.util.Scanner;public class ArrayExample010 {

public static void PrintIntArray(int A[]) {for (int i = 0; i < A.length; i++) {

System.out.print(A[i] + " ");}System.out.println();

}

public static void BubbleSort(int A[]) {for (int i = A.length-1; i > 0; i--) {

for (int j = 0; j < i; j++){if (A[j] > A[j+1]){

int temp = A[j];A[j] = A[j+1];A[j+1] = temp;

}}

}}

public static void main(String[] args) {Scanner keyboard = new Scanner(System.in);Random generator = new Random();System.out.print("Input the array size: ");int arraySize = keyboard.nextInt();int arr[] = new int[arraySize];for (int i = 0; i < arr.length; i++)

arr[i] = generator.nextInt(1000);

PrintIntArray(arr);BubbleSort(arr);PrintIntArray(arr);

}}

Runs:

Input the array size: 5881 709 206 158 544 158 206 544 709 881

Input the array size: 15163 179 103 91 404 531 745 405 686 858 898 926 266 867 865 91 103 163 179 266 404 405 531 686 745 858 865 867 898 926

Introductory Java Examples

109 of 165.

Page 110: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

ArrayExample011.javaimport java.util.Random;public class ArrayExample011 {

public static void PrintDeck(Card[] deck) {for (int i = 0; i < deck.length; i++) {

System.out.print(deck[i].getValue() + deck[i].getSuit() + " ");}System.out.println();

}

public static void ShuffleDeck(Card[] deck) {Random generator = new Random();Card tempdeck[] = new Card[deck.length];for (int i = 0; i < 7; i++) {

int tempdeckpos = 0;int mid = deck.length / 2;int start = 0;while (tempdeckpos < deck.length){

int side = generator.nextInt(2);if (side == 0){

int skip1 = generator.nextInt(3) + 1;if (start < deck.length / 2) {

if (start + skip1 > deck.length / 2)skip1 = deck.length / 2 - start;

for (int j = start; j < start + skip1; j++) {tempdeck[tempdeckpos] = deck[j];tempdeckpos++;

}}start += skip1;

}else{

int skip2 = generator.nextInt(3) + 1;if (mid < deck.length) {

if (mid + skip2 > deck.length)skip2 = deck.length - mid;

for (int j = mid; j < mid + skip2; j++) {tempdeck[tempdeckpos] = deck[j];tempdeckpos++;

}}mid += skip2;

}}

for (int j = 0; j < deck.length; j++)deck[j] = tempdeck[j];

}}

public static void main(String[] args) {Card deck[] = new Card[52];int pos = 0;for (int i = 0; i < 4; i++)

for (int j = 0; j < 13; j++) {String suit = "";String value = "";

if (i == 0)suit = "H";

else if (i == 1)suit = "D";

else if (i == 2)suit = "C";

Introductory Java Examples

110 of 165.

Page 111: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

else if (i == 3)suit = "S";

if (j == 0)value = "A";

else if (j == 10)value = "J";

else if (j == 11)value = "Q";

else if (j == 12)value = "K";

elsevalue = "" + (j + 1);

deck[pos] = new Card(value, suit);pos++;

}PrintDeck(deck);ShuffleDeck(deck);PrintDeck(deck);

}}

Card.java

public class Card {private String value;private String suit;public Card(String v, String s){

value = v;suit = s;

}

public String getValue(){return value;

}

public String getSuit(){return suit;

}

public int getWorth(){if (value.equals("A"))

return 1;else if (value.equals("2"))

return 2;else if (value.equals("3"))

return 3;else if (value.equals("4"))

return 4;else if (value.equals("5"))

return 5;else if (value.equals("6"))

return 6;else if (value.equals("7"))

return 7;else if (value.equals("8"))

return 8;else if (value.equals("9"))

return 9;else

return 10;}

public boolean isAce(){return value.equals("A");

}}

Run:AH 2H 3H 4H 5H 6H 7H 8H 9H 10H JH QH KH AD 2D 3D 4D 5D 6D 7D 8D 9D 10D JD QD KD AC 2C 3C 4C 5C 6C 7C 8C 9C 10C JC QC KC AS 2S 3S 4S 5S 6S 7S 8S 9S 10S JS QS KS

3D 6D AS 3C 4D AH 2H AC QS KS 4S 5S 9D 9H 10H 3H JC QC 5C 10C KC 7D QD 5H JH QH 8D 4H 2S 10D 9C JD 6S 3S KH 8C 7S 6H 7H 10S AD 2C 6C JS 8H KD 8S 9S 5D 4C 2D 7C

Introductory Java Examples

111 of 165.

Page 112: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

Array Examples 4

public class ArrayExample012 {

public static void PrintintArray(int A[], int width) {String format = "%" + width + "d";for (int i = 0; i < A.length; i++)

System.out.printf(format, A[i]);

System.out.println();}

public static int[] CopyintArray(int A[]) {int[] B = new int[A.length];

for (int i = 0; i < A.length; i++)B[i] = A[i];

return B;}

public static void main(String[] args) {int[] Arr1 = new int[15];int[] Arr2 = new int[15];

for (int i = 0; i < Arr1.length; i++)Arr1[i] = (int)(Math.random()*100) + 1;

PrintintArray(Arr1, 4);System.out.println();

Arr2 = CopyintArray(Arr1);PrintintArray(Arr1, 4);PrintintArray(Arr2, 4);System.out.println("Array 1 Position: " + Arr1);System.out.println("Array 2 Position: " + Arr2);System.out.println();

Arr2[2] = -3;Arr2[7] = -9;

PrintintArray(Arr1, 4);PrintintArray(Arr2, 4);System.out.println("Array 1 Position: " + Arr1);System.out.println("Array 2 Position: " + Arr2);System.out.println();

Arr2 = Arr1;

PrintintArray(Arr1, 4);PrintintArray(Arr2, 4);System.out.println("Array 1 Position: " + Arr1);System.out.println("Array 2 Position: " + Arr2);System.out.println();

Arr2[2] = -3;Arr2[7] = -9;

PrintintArray(Arr1, 4);PrintintArray(Arr2, 4);System.out.println("Array 1 Position: " + Arr1);System.out.println("Array 2 Position: " + Arr2);System.out.println();

Arr2 = CopyintArray(Arr1);Arr2[3] = -12;Arr2[10] = -3;

1

Introductory Java Examples

112 of 165.

Page 113: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

PrintintArray(Arr1, 4);PrintintArray(Arr2, 4);System.out.println("Array 1 Position: " + Arr1);System.out.println("Array 2 Position: " + Arr2);System.out.println();

Arr2 = CopyintArray(Arr1);PrintintArray(Arr1, 4);PrintintArray(Arr2, 4);System.out.println("Array 1 Position: " + Arr1);System.out.println("Array 2 Position: " + Arr2);System.out.println(Arr1 == Arr2);System.out.println();

Arr2 = Arr1;System.out.println("Array 1 Position: " + Arr1);System.out.println("Array 2 Position: " + Arr2);System.out.println(Arr1 == Arr2);

}}

Run: 15 22 70 37 24 8 35 42 46 48 92 3 55 89 55

15 22 70 37 24 8 35 42 46 48 92 3 55 89 55 15 22 70 37 24 8 35 42 46 48 92 3 55 89 55Array 1 Position: [I@70d76d51Array 2 Position: [I@4f4a1ab7

15 22 70 37 24 8 35 42 46 48 92 3 55 89 55 15 22 -3 37 24 8 35 -9 46 48 92 3 55 89 55Array 1 Position: [I@70d76d51Array 2 Position: [I@4f4a1ab7

15 22 70 37 24 8 35 42 46 48 92 3 55 89 55 15 22 70 37 24 8 35 42 46 48 92 3 55 89 55Array 1 Position: [I@70d76d51Array 2 Position: [I@70d76d51

15 22 -3 37 24 8 35 -9 46 48 92 3 55 89 55 15 22 -3 37 24 8 35 -9 46 48 92 3 55 89 55Array 1 Position: [I@70d76d51Array 2 Position: [I@70d76d51

15 22 -3 37 24 8 35 -9 46 48 92 3 55 89 55 15 22 -3 -12 24 8 35 -9 46 48 -3 3 55 89 55Array 1 Position: [I@70d76d51Array 2 Position: [I@a200d0c

15 22 -3 37 24 8 35 -9 46 48 92 3 55 89 55 15 22 -3 37 24 8 35 -9 46 48 92 3 55 89 55Array 1 Position: [I@70d76d51Array 2 Position: [I@3e389405false

Array 1 Position: [I@70d76d51Array 2 Position: [I@70d76d51true

2

Introductory Java Examples

113 of 165.

Page 114: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

import java.util.Random;import java.util.Scanner;

public class ArrayExample013 {public static void PrintIntArray(int A[]) {

for (int i = 0; i < A.length; i++) {System.out.print(A[i] + " ");

}System.out.println();

}

public static void PrintDoubleArray(double A[]) {for (int i = 0; i < A.length; i++) {

System.out.print(A[i] + " ");}System.out.println();

}

public static void PrintStringArray(String A[]) {for (int i = 0; i < A.length; i++) {

System.out.print(A[i] + " ");}System.out.println();

}

public static void main(String[] args) {Scanner keyboard = new Scanner(System.in);Random generator = new Random();System.out.print("Input the array size: ");int arraySize = keyboard.nextInt();

int arr1[] = new int[arraySize];PrintIntArray(arr1);

for (int i = 0; i < arr1.length; i++)arr1[i] = generator.nextInt(1000);

PrintIntArray(arr1);System.out.println();

int arr2[] = {2, 4, 3, 6, 5, 8};System.out.println(arr2.length);PrintIntArray(arr2);System.out.println();

int arr3[] = new int [] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};System.out.println(arr3.length);PrintIntArray(arr3);System.out.println();

double arr4[] = new double[15];for (int i = 0; i < arr4.length; i++)

arr4[i] = generator.nextDouble();

PrintDoubleArray(arr4);System.out.println();

double arr5[] = {2.3, 5.6, 4, -10.3, Math.PI, 1/2, 1.0/3.0};System.out.println(arr5.length);PrintDoubleArray(arr5);System.out.println();

String strArr1[] = {"cat", "dog", "mouse", "rabbit"};System.out.println(strArr1.length);PrintStringArray(strArr1);System.out.println();

}}

3

Introductory Java Examples

114 of 165.

Page 115: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

Run:

Input the array size: 100 0 0 0 0 0 0 0 0 0 302 619 8 37 262 497 383 797 143 988

62 4 3 6 5 8

121 2 3 4 5 6 7 8 9 10 11 12

0.22447903784936019 0.43763247778004233 0.1987588824535872 0.5383156056753986 0.04949182360721671 0.12794488544307692 0.6946079439564165 0.11186724441018847 0.030058217324341108 0.397384484159263 0.3343190457657873 0.6460478828182871 0.678256822090923 0.7796383020699095 0.12604802327450715

72.3 5.6 4.0 -10.3 3.141592653589793 0.0 0.3333333333333333

4cat dog mouse rabbit

4

Introductory Java Examples

115 of 165.

Page 116: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

public class ArrayExample014 {

public static void PrintStringArray(String A[]) {for (int i = 0; i < A.length; i++) {

System.out.print(A[i] + " ");}System.out.println();

}

public static void main(String[] args) {System.out.println(args.length);PrintStringArray(args);

}}

Run:

5

Introductory Java Examples

116 of 165.

Page 117: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

import java.util.Random;import java.util.Scanner;

public class ArrayExample015 {

public static void PrintArray(int A[]) {for (int i = 0; i < A.length; i++) {

System.out.print(A[i] + " ");}System.out.println();

}

public static void PrintArray(double A[]) {for (int i = 0; i < A.length; i++) {

System.out.print(A[i] + " ");}System.out.println();

}

public static void PrintArray(String A[]) {for (int i = 0; i < A.length; i++) {

System.out.print(A[i] + " ");}System.out.println();

}

public static void main(String[] args) {Scanner keyboard = new Scanner(System.in);Random generator = new Random();System.out.print("Input the array size: ");int arraySize = keyboard.nextInt();int arr1[] = new int[arraySize];PrintArray(arr1);

for (int i = 0; i < arr1.length; i++)arr1[i] = generator.nextInt(1000);

PrintArray(arr1);System.out.println();

int arr2[] = {2, 4, 3, 6, 5, 8};System.out.println(arr2.length);PrintArray(arr2);System.out.println();

int arr3[] = new int [] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};System.out.println(arr3.length);PrintArray(arr3);System.out.println();

double arr4[] = new double[15];for (int i = 0; i < arr4.length; i++)

arr4[i] = generator.nextDouble();

PrintArray(arr4);System.out.println();

double arr5[] = {2.3, 5.6, 4, -10.3, Math.PI, 1/2, 1.0/3.0};System.out.println(arr5.length);PrintArray(arr5);System.out.println();

String strArr1[] = {"cat", "dog", "mouse", "rabbit"};System.out.println(strArr1.length);PrintArray(strArr1);System.out.println();

}}

6

Introductory Java Examples

117 of 165.

Page 118: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

Searching Arrays

Linear Search Algorithm:

Look at each item in the array in turn, and check whether that item is the one you are looking for. If so, the search is finished. If you look at every item without finding the one you want, then you can be sure that the item is not in the array.

I. For each entry in the array check its equality with the target value. A. If the target item matches return the array position the target item was in. B. If the target item does not match move onto the next array entry.

II. If the end of the array is reached without a match then return -1 to indicate a failed search.

Binary Search Algorithm: This only works for an array that is sorted from smallest to largest.

The basic operation is to look at the item in the middle of the range. If this item is greater than the target value N, then the second half of the range can be eliminated. If it is less than N, then the first half of the range can be eliminated. If the number in the middle just happens to be N exactly, then the search is finished. If the size of the range decreases to zero, then the number N does not occur in the array.

I. Set the lowest value to 0 and the highest value to the last position of the array (length – 1). So we are always searching for the target N between the lowest and highest positions.

II. Calculate the location between the lowest and highest position (i.e. the middle of the list). III. If N is equal to the entry in the middle position then we have found the target and return the

middle position. The function will end at this point. IV. If N is less than the value in the middle position then if N is in the list it is in the first half of

the list, so we discard the second the half of the list by setting highest to middle – 1. V. If N is greater than the value in the middle position then if N is in the list it is in the second

half of the list, so we discard the first the half of the list by setting lowest to middle + 1. VI. If N is not in the list then at some point the lowest value will exceed the highest value, in

this case return -1 to indicate a failed search.

Revision:

I. Set the lowest value to 0 and the highest value to the last position of the array (length – 1). II. While the lowest value is smaller than the highest value do the following.

A. Calculate the middle location. B. If N is equal to the entry in the middle position then return the middle position. C. If N is less than the value in the middle position then set highest to middle – 1. D. If N is greater than the value in the middle position then set lowest to middle + 1.

III. Return -1.

1

Introductory Java Examples

118 of 165.

Page 119: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

public class ArraySearching {

public static void PrintIntArray(int A[]) {for (int i = 0; i < A.length; i++) {

System.out.print(A[i] + " ");}System.out.println();

}

static int linearSearch(int[] A, int N) {for (int index = 0; index < A.length; index++) {

if (A[index] == N)return index; // N has been found at this index!

}// At this point N is known to be not in the array. Return -1return -1;

}

static int binarySearch(int[] A, int N) {int lowestPossibleLoc = 0;int highestPossibleLoc = A.length - 1;while (highestPossibleLoc >= lowestPossibleLoc) {

int middle = (lowestPossibleLoc + highestPossibleLoc) / 2;if (A[middle] == N) {

// N has been found at this index!return middle;

} else if (A[middle] > N) {// eliminate locations >= middlehighestPossibleLoc = middle - 1;

} else {// eliminate locations <= middlelowestPossibleLoc = middle + 1;

}}// At this point N is known to be not in the array. Return -1return -1;

}

public static void main(String[] args) {int arr1[] = {3, 5, -2, 7, 10, 1, 5, 7, 3};PrintIntArray(arr1);

int pos = linearSearch(arr1, 1);System.out.println(pos + " " + arr1[pos]);pos = linearSearch(arr1, 7);System.out.println(pos + " " + arr1[pos]);pos = linearSearch(arr1, 9);System.out.println(pos);System.out.println();

int arr2[] = {2, 4, 4, 4, 5, 6, 15, 18, 23, 42, 45, 57, 101};PrintIntArray(arr2);

pos = binarySearch(arr2, 15);System.out.println(pos + " " + arr2[pos]);pos = binarySearch(arr2, 4);System.out.println(pos + " " + arr2[pos]);pos = binarySearch(arr2, 100);System.out.println(pos);System.out.println();

// Doing a binary search on a non-sorted array will not// work in general. pos = binarySearch(arr1, 1);System.out.println(pos);System.out.println();

}}

2

Run:

3 5 -2 7 10 1 5 7 3 5 13 7-1

2 4 4 4 5 6 15 18 23 42 45 57 101 6 152 4-1

-1

Introductory Java Examples

119 of 165.

Page 120: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

Sorting Arrays

All sorting algorithms will be using integer arrays, although the same algorithm works for other data types, and the arrays will be sorted from smallest to largest.

Bubble Sort Algorithm:

The idea behind the bubble sort is to move through the list and compare each two consecutive entries in the array. That is, entries 0 and 1 then 1 and 2 then 2 and 3 and so on until the last two entries have been compared. At each comparison if the numbers are out of order then we interchange them. The result is that after one pass through the array the largest number in the array is in the last position of the array. In other words, the largest number in the array is now in its correct place in the sorted array. We now do the same process but we stop at the next to last position of the array (since the last position is already sorted). The second pass will put the second largest number in the next to last position and hence it is in its correct position. Make another pass up to the second to last position and so on. Once the last position sorted is the second position in the array we do the final comparison, and possible interchange, and we are done. In all we do the length of the array minus 1 passes.

I. From the first entry to the next to last entry compare the entry with the one following it. A. If the entry is larger than the one following it, interchange the two values.

II. Repeat the process up to the second to last entry, then the third to last ans so on.

Revision:

I. For each entry index, i, from the next to last up to the second entry do the following II. For each entry index, j, from the first up to i – 1 do the following

A. Compare the entry in the jth position with the entry in the j+1st position. If the two entries are out of order, interchange them.

Modified Bubble Sort Algorithm:

If you examine the bubble sort you probably notice that there are times when you are doing a process when you do not need to. If you have not noticed this, trace through the algorithm with an array that is already sorted. We can modify the bubble sort a little by tracking the last interchange we make. Notice that during each pass the array is sorted from the last interchange to the end. So instead of doing a pass for each entry we can do each pass up to the last interchange of the previous pass. This could conceivably save many passes through the array.

I. While a change in the order of any entries was done on the last pass do the following A. For each entry index, j, from the first up to the last changed position minus 1 do the

following i. Compare the entry in the jth position with the entry in the j+1st position. If the two

entries are out of order, interchange them. Also, note that a change has been made and track the position of the last interchange for the next pass.

1

Introductory Java Examples

120 of 165.

Page 121: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

Insertion Sort Algorithm:

The insertion sort works under the following principle, say we have an already sorted list and we want to insert another number into the list. One way to do this and retain a sorted list is to find the place the new umber needs to go, move all of the larger numbers down one entry and put the new number in the empty spot. We can extend this idea to sorting an array as follows. Start with a single entry, entry index 0. An array with a single number in it is clearly sorted. Now take the second number in the array and insert it into the single entry array by moving the larger numbers down and inserting the new entry in order. Now we have a sorted array with two elements. Now take the third entry of the array and insert it by moving the larger entries down and inserting the new entry. Do the same with the next entry and so on until we process the entire array.

I. For each entry index, itemsSorted, from one to the length of the array minus 1 do the following A. Store the entry at the itemsSorted position of the array. Also store the location loc where

we will store this number. Start the loc at the position of itemsSorted minus 1. B. While the entry in the array at position loc is larger than the one in the itemsSorted

position move the loc position entry down one and decrement loc. C. Place the new entry in location loc + 1.

Selection Sort Algorithm:

The idea behind the selection sort is to find the largest element in the array and interchange it with the entry in the last position. Then find the largest entry in the array up to the next to last position and interchange it with the entry in the next to last position. Repeat the process up to position length – 2, and so on.

I. For each entry index, lastPlace, from the length minus one to index 1 do the following A. Find the largest value in the array from position 0 up to position lastPlace. B. Interchange the maximum with the entry in lastPlace.

2

Introductory Java Examples

121 of 165.

Page 122: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

import java.util.Random;import java.util.Scanner;

public class ArraySorting {

public static int[] CopyintArray(int A[]) {int[] B = new int[A.length];

for (int i = 0; i < A.length; i++)B[i] = A[i];

return B;}

public static void PrintIntArray(int A[]) {for (int i = 0; i < A.length; i++) {

System.out.print(A[i] + " ");}System.out.println();

}

public static void BubbleSort(int A[]) {for (int i = A.length - 1; i > 0; i--) {

for (int j = 0; j < i; j++) {if (A[j] > A[j + 1]) {

int temp = A[j];A[j] = A[j + 1];A[j + 1] = temp;

}}

}}

public static void ModifiedBubbleSort(int A[]) {int lastchange = A.length - 1;boolean changemade = true;int pass = 1;

while (changemade) {changemade = false;int changed = 0;int j = 0;while (j < lastchange) {

if (A[j] > A[j + 1]) {int temp = A[j];A[j] = A[j + 1];A[j + 1] = temp;changed = j;changemade = true;

}j++;

}lastchange = changed;

}}

public static void insertionSort(int[] A) {for (int itemsSorted = 1; itemsSorted < A.length; itemsSorted++) {

int temp = A[itemsSorted];int loc = itemsSorted - 1;while (loc >= 0 && A[loc] > temp) {

A[loc + 1] = A[loc];loc = loc - 1;

}A[loc + 1] = temp;

}}

3

Introductory Java Examples

122 of 165.

Page 123: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

public static void selectionSort(int[] A) {for (int lastPlace = A.length - 1; lastPlace > 0; lastPlace--) {

int maxLoc = 0;for (int j = 1; j <= lastPlace; j++)

if (A[j] > A[maxLoc])maxLoc = j;

int temp = A[maxLoc];A[maxLoc] = A[lastPlace];A[lastPlace] = temp;

}}

public static void main(String[] args) {Scanner keyboard = new Scanner(System.in);Random generator = new Random();System.out.print("Input the array size: ");int arraySize = keyboard.nextInt();System.out.print("Input the maximum random integer: ");int intSize = keyboard.nextInt();System.out.println();

int arr[] = new int[arraySize];int arr2[];int arr3[];

for (int i = 0; i < arr.length; i++)arr[i] = generator.nextInt(intSize) + 1;

arr2 = CopyintArray(arr);PrintIntArray(arr2);BubbleSort(arr2);PrintIntArray(arr2);System.out.println();

arr2 = CopyintArray(arr);PrintIntArray(arr2);ModifiedBubbleSort(arr2);PrintIntArray(arr2);System.out.println();

arr2 = CopyintArray(arr);PrintIntArray(arr2);insertionSort(arr2);PrintIntArray(arr2);System.out.println();

arr2 = CopyintArray(arr);PrintIntArray(arr2);selectionSort(arr2);PrintIntArray(arr2);System.out.println();

}}

4

Run:

Input the array size: 10Input the maximum random integer: 100

12 96 71 9 74 89 50 29 80 51 9 12 29 50 51 71 74 80 89 96

12 96 71 9 74 89 50 29 80 51 9 12 29 50 51 71 74 80 89 96

12 96 71 9 74 89 50 29 80 51 9 12 29 50 51 71 74 80 89 96

12 96 71 9 74 89 50 29 80 51 9 12 29 50 51 71 74 80 89 96

Introductory Java Examples

123 of 165.

Page 124: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

Applet Examples #1

import javax.swing.JApplet;import java.awt.*;public class Applets001 extends JApplet{

public void paint(Graphics g){super.paint(g);g.setColor(Color.black);g.fillOval(60, 40, 220, 220);g.setColor(Color.red);g.fillOval(80, 60, 180, 180);

}}

<HTML><HEAD><META http-equiv="Content-Type" content="text/html; charset=windows-1252"><TITLE>This is my first Applet</TITLE></HEAD>

<BODY>

<APPLET code="Applets001.class" codebase="." width=400 height=300></APPLET>

</BODY></HTML>

Introductory Java Examples

124 of 165.

Page 125: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

import java.awt.*;import javax.swing.JApplet;public class Applets003 extends JApplet {

public void paint(Graphics g){super.paint(g);g.setColor(Color.red);g.fillOval(70, 50, 200, 50);g.setColor(Color.green);g.drawOval(10, 20, 100, 200);g.drawRect(100, 200, 50, 50);g.setColor(Color.blue);g.fillRect(170, 200, 50, 50);

g.setColor(Color.red);g.fillRect(170, 130, 50, 50);g.setColor(Color.black);g.drawRect(170, 130, 50, 50);

}}

Introductory Java Examples

125 of 165.

Page 126: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

import java.awt.*;import javax.swing.JApplet;public class Applets004 extends JApplet {

public void paint(Graphics g){super.paint(g);g.setColor(Color.red);g.fillRect(50, 70, 250, 350);

g.clearRect(100, 100, 100, 100);}

}

Introductory Java Examples

126 of 165.

Page 127: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

import java.awt.*;import javax.swing.JApplet;public class Applets005 extends JApplet {

public void paint(Graphics g){super.paint(g);int [] xvalues = new int [5];int [] yvalues = new int [5];xvalues[0] = 20;xvalues[1] = 120;xvalues[2] = 290;xvalues[3] = 20;xvalues[4] = 80;

yvalues[0] = 100; yvalues[1] = 200;yvalues[2] = 20;yvalues[3] = 50;yvalues[4] = 210;

g.setColor(Color.red);g.drawPolygon(xvalues, yvalues, 5);

}}

Introductory Java Examples

127 of 165.

Page 128: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

import java.awt.*;import javax.swing.JApplet;public class Applets006 extends JApplet {

public void paint(Graphics g){super.paint(g);int [] xvalues = new int [5];int [] yvalues = new int [5];xvalues[0] = 20;xvalues[1] = 120;xvalues[2] = 290;xvalues[3] = 20;xvalues[4] = 80;

yvalues[0] = 100; yvalues[1] = 200;yvalues[2] = 20;yvalues[3] = 50;yvalues[4] = 210;

g.setColor(Color.red);g.fillPolygon(xvalues, yvalues, 5);

}}

Introductory Java Examples

128 of 165.

Page 129: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

import java.awt.*;import javax.swing.JApplet;public class Applets007 extends JApplet {

public void paint(Graphics g){super.paint(g);g.setColor(Color.red);g.drawString("Hi there", 100, 200);

g.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 50));g.drawString("Big Font", 50, 70);g.setFont(new Font(Font.SANS_SERIF, Font.BOLD | Font.ITALIC, 70));g.drawString("Big Slant Font", 50, 170);

}}

Introductory Java Examples

129 of 165.

Page 130: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

import java.awt.*;import javax.swing.JApplet;public class Applets008 extends JApplet {

public void paint(Graphics g){super.paint(g);g.setColor(Color.black);g.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 30));g.drawString("Green Triangle", 50, 70);

int [] trixvalues = new int [3];int [] triyvalues = new int [3];trixvalues[0] = 20;trixvalues[1] = 120;trixvalues[2] = 290;

triyvalues[0] = 100; triyvalues[1] = 200;triyvalues[2] = 110;

g.setColor(Color.green);g.fillPolygon(trixvalues, triyvalues, 3);

g.setColor(Color.black);g.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 30));g.drawString("Red Square", 350, 70);g.setColor(Color.red);g.fillRect(360, 100, 150, 150);

}}

Introductory Java Examples

130 of 165.

Page 131: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

import java.awt.*;import javax.swing.JApplet;public class Applets009 extends JApplet {

public void paint(Graphics g){super.paint(g);g.setColor(Color.black);for (int i = 0; i < 120; i+= 10)

g.drawLine(i, 0, i, 300);

g.setColor(Color.red);g.fillRect(0, 0, 50, 50);g.setColor(Color.green);g.fillRect(60, 0, 50, 50);

g.setColor(Color.blue);g.fillRect(0, 60, 50, 50);g.setColor(Color.magenta);g.fillRect(60, 60, 50, 50);

g.setColor(new Color(0, 255, 0));g.fillRect(0, 120, 50, 50);g.setColor(new Color(0, 255, 255));g.fillRect(60, 120, 50, 50);

g.setColor(new Color(1f, 0f, 0f));g.fillRect(0, 180, 50, 50);g.setColor(new Color(1f, 0.5f, 0f));g.fillRect(60, 180, 50, 50);

g.setColor(new Color(1f, 0f, 0f, 0.5f));g.fillRect(0, 240, 50, 50);g.setColor(new Color(255, 100, 0, 130));g.fillRect(60, 240, 50, 50);

for (int i = 0; i < 120; i+= 10){g.setColor(new Color(1f, 0f, 0f, i/120f));g.fillRect(i, 300, 50, 50);

}

for (int i = 0; i < 120; i++){g.setColor(new Color(1f, 0f, 0f, i/120f));g.drawLine(i, 360, i, 400);

}}

}

Introductory Java Examples

131 of 165.

Page 132: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

import javax.swing.JApplet;import java.awt.*;import java.util.Random;public class Appltes002 extends JApplet {

Random gen = new Random();public void paint(Graphics g){

super.paint(g);for (int i = 0; i < 300; i++){

g.setColor(new Color(gen.nextInt(255), gen.nextInt(255), gen.nextInt(255)));

g.drawLine(gen.nextInt(300), gen.nextInt(300), gen.nextInt(300), gen.nextInt(300));

}}

}

Introductory Java Examples

132 of 165.

Page 133: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

import java.awt.*;import javax.swing.JApplet;public class Applets010 extends JApplet {

public void paint(Graphics g){super.paint(g);g.translate(200, 200);g.drawLine(0, 200, 0, -200);g.drawLine(-200, 0, 200, 0);

}}

Introductory Java Examples

133 of 165.

Page 134: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

import java.awt.*;import javax.swing.JApplet;public class Applets011 extends JApplet {

public void paint(Graphics g){super.paint(g);g.setColor(Color.black);g.translate(200, 200);g.drawLine(0, 200, 0, -200);g.drawLine(-200, 0, 200, 0);

g.setColor(Color.red);

double lastx = -100;double lasty = -100;for (double x = -10; x <= 10; x+=0.1){

double y = Math.sin(x);if (lastx > -90){

g.drawLine((int)(20*lastx), (int)(20*lasty), (int)(20*x), (int)(20*y));

}lastx = x;lasty = y;

}}

}

Introductory Java Examples

134 of 165.

Page 135: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

import java.awt.*;import javax.swing.JApplet;public class Applets012 extends JApplet {

public void paint(Graphics g){super.paint(g);g.setColor(Color.black);g.translate(200, 200);g.drawLine(0, 200, 0, -200);g.drawLine(-200, 0, 200, 0);

g.setColor(Color.red);

for (int i = 0; i <= 6; i++){double x = Math.cos(2*Math.PI*((double)i/6));double y = Math.sin(2*Math.PI*((double)i/6));double nextx = Math.cos(2*Math.PI*((double)(i+1)/6));double nexty = Math.sin(2*Math.PI*((double)(i+1)/6));g.drawLine((int)(100*x), (int)(100*y), (int)(100*nextx), (int)

(100*nexty));}

}}

Introductory Java Examples

135 of 165.

Page 136: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

Applet Examples #2: Adding Event-Driven Code

The nifty thing about Graphical User Interface programming is that you can get the program to respond to user actions, like clicking the mouse or typing an arrow key. You can also get the program to respond to other actions like database updating, internet communications, etc. We will not get into these advanced features but we will look at implementing the mouse into our program. To get the program to respond to mouse events we need to add in two listeners, MouseListener and MouseMotionListener. A listener is a built-in facility for Java that listens for events. In our case we will be listening for two types of mouse events a Mouse event like clicking and a Mouse Motion even like moving the moue around the screen. Listeners are listed after an implements command in the class header. When you use a listener you must override the functions associated with the listener even if the functions do nothing. In the code below we override the mousePressed function that is run every time any mouse button is pressed, note that a press of a mouse button is not the same as a click of a button. A mouse click is both pressing and releasing the mouse button. We also overload the mouseDragged function which runs every time the mouse is moved while a button is down. In our programming before this point when we wanted to run a function we always called the function from some point in the code. Here a function is being called as a result of the user doing something. It may be helpful to think of event-driven programming as the user calling these functions as a result of what they do with the mouse, keyboard or whatever input device they are using.

import java.awt.*;import javax.swing.JApplet;import java.awt.event.*;import javax.swing.*;

public class Applets013 extends JApplet implements MouseListener,MouseMotionListener {

private int prevX, prevY; // The previous location of the mouse.private int drawWidth = 500;private int drawHeight = 400;

public void init() {addMouseListener(this);addMouseMotionListener(this);

}

public void paint(Graphics g) {super.paint(g);

g.setColor(Color.WHITE);g.fillRect(0, 0, drawWidth, drawHeight);g.setColor(Color.BLACK);g.drawRect(0, 0, drawWidth, drawHeight);

}

1

Introductory Java Examples

136 of 165.

Page 137: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

public void mousePressed(MouseEvent evt) {prevX = evt.getX(); // x-coordinate where the user clicked.prevY = evt.getY(); // y-coordinate where the user clicked.

}

public void mouseDragged(MouseEvent evt) {int x = evt.getX(); // x-coordinate of mouse.int y = evt.getY(); // y=coordinate of mouse.

Graphics g = getGraphics();

// Make sure that we are in the drawing region and then draw the line.if ((x > 0) && (x < drawWidth) && (y > 0) && (y < drawHeight)

&& (prevX > 0) && (prevX < drawWidth) && (prevY > 0)&& (prevY < drawHeight))

g.drawLine(prevX, prevY, x, y);

// Get ready for the next line segment in the curve.prevX = x;prevY = y;

}

// Some empty routines. These are required by the MouseListener// and MouseMotionListener interfaces.public void mouseEntered(MouseEvent evt) {}

public void mouseExited(MouseEvent evt) {}

public void mouseClicked(MouseEvent evt) {}

public void mouseMoved(MouseEvent evt) {}

public void mouseReleased(MouseEvent evt) {}

}

2

Introductory Java Examples

137 of 165.

Page 138: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

This is a minor update of the last program. In the above program we were able to draw on the screen with both the left and right mouse buttons. In this one we will draw with the left button and use a click with the right button to clear the screen. Note the addition of the boolean variable dragging which tracks if the left button is down to allow drawing. We also added a mouseClicked function to do the clearing of the screen on a right click.

import java.awt.*;import javax.swing.JApplet;import java.awt.event.*;import javax.swing.*;

public class Applets014 extends JApplet implements MouseListener,MouseMotionListener {

private int prevX, prevY; // The previous location of the mouse.private int drawWidth = 500;private int drawHeight = 400;private boolean dragging = false;

public void init() {addMouseListener(this);addMouseMotionListener(this);

}

public void paint(Graphics g) {super.paint(g);

g.setColor(Color.WHITE);g.fillRect(0, 0, drawWidth, drawHeight);g.setColor(Color.BLACK);g.drawRect(0, 0, drawWidth, drawHeight);

}

public void mousePressed(MouseEvent evt) {// Only draw if the left mouse button was depressed. if (evt.getButton() == MouseEvent.BUTTON1)

dragging = true;

prevX = evt.getX(); // x-coordinate where the user clicked.prevY = evt.getY(); // y-coordinate where the user clicked.

}

public void mouseDragged(MouseEvent evt) {if (!dragging)

return;

int x = evt.getX(); // x-coordinate of mouse.int y = evt.getY(); // y=coordinate of mouse.

Graphics g = getGraphics();

// Make sure that we are in the drawing region and then draw the line.if ((x > 0) && (x < drawWidth) && (y > 0) && (y < drawHeight)

3

Introductory Java Examples

138 of 165.

Page 139: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

&& (prevX > 0) && (prevX < drawWidth) && (prevY > 0)&& (prevY < drawHeight))

g.drawLine(prevX, prevY, x, y);

// Get ready for the next line segment in the curve.prevX = x;prevY = y;

}

public void mouseReleased(MouseEvent evt) {dragging = false;

}

public void mouseClicked(MouseEvent evt) {// if right mouse button clicked, clear the screenif (evt.getButton() == MouseEvent.BUTTON3) {

Graphics g = getGraphics();

g.setColor(Color.WHITE);g.fillRect(0, 0, drawWidth, drawHeight);g.setColor(Color.BLACK);g.drawRect(0, 0, drawWidth, drawHeight);

}}

// Some empty routines. These are required by the MouseListener// and MouseMotionListener interfaces.public void mouseEntered(MouseEvent evt) {}

public void mouseExited(MouseEvent evt) {}

public void mouseMoved(MouseEvent evt) {}

}

4

Introductory Java Examples

139 of 165.

Page 140: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

Next we get a little fancier and add in the ability to change the drawing color as well as a “button” to clear the screen. I put “button” in quotes because this is not really a button, it will be an area where if the user clicks in the area the screen will clear.

import java.awt.*;import javax.swing.JApplet;import java.awt.event.*;import javax.swing.*;

public class Applets015 extends JApplet implements MouseListener,MouseMotionListener {

private int prevX, prevY; // The previous location of the mouse.private int drawWidth = 500;private int drawHeight = 400;private boolean dragging = false;private Color drawColor;

public void init() {addMouseListener(this);addMouseMotionListener(this);

}

public void paint(Graphics g) {super.paint(g);

g.setColor(Color.WHITE);g.fillRect(0, 0, drawWidth, drawHeight);g.setColor(Color.BLACK);g.drawRect(0, 0, drawWidth, drawHeight);

g.setColor(Color.BLACK);g.drawRect(0, 0, drawWidth - 50, drawHeight);

g.setColor(Color.BLACK);g.fillRect(drawWidth - 50, 0, 50, 50);g.setColor(Color.BLACK);g.drawRect(drawWidth - 50, 0, 50, 50);

g.setColor(Color.RED);g.fillRect(drawWidth - 50, 50, 50, 50);g.setColor(Color.BLACK);g.drawRect(drawWidth - 50, 50, 50, 50);

g.setColor(Color.GREEN);g.fillRect(drawWidth - 50, 100, 50, 50);g.setColor(Color.BLACK);g.drawRect(drawWidth - 50, 100, 50, 50);

g.setColor(Color.BLUE);g.fillRect(drawWidth - 50, 150, 50, 50);g.setColor(Color.BLACK);g.drawRect(drawWidth - 50, 150, 50, 50);

5

Introductory Java Examples

140 of 165.

Page 141: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

g.setColor(Color.YELLOW);g.fillRect(drawWidth - 50, 200, 50, 50);g.setColor(Color.BLACK);g.drawRect(drawWidth - 50, 200, 50, 50);

g.setColor(Color.GRAY);g.fillRect(drawWidth - 50, 250, 50, 50);g.setColor(Color.BLACK);g.drawRect(drawWidth - 50, 250, 50, 50);

g.drawRect(drawWidth - 50, 300, 50, 50);g.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 20));g.drawString("Clear", drawWidth - 49, 335);

drawColor = Color.BLACK;}

public void mousePressed(MouseEvent evt) {// Only draw if the left mouse button was depressed.if (evt.getButton() == MouseEvent.BUTTON1)

dragging = true;

prevX = evt.getX(); // x-coordinate where the user clicked.prevY = evt.getY(); // y-coordinate where the user clicked.

}

public void mouseDragged(MouseEvent evt) {if (!dragging)

return;

int x = evt.getX(); // x-coordinate of mouse.int y = evt.getY(); // y=coordinate of mouse.

Graphics g = getGraphics();g.setColor(drawColor);

// Make sure that we are in the drawing region and then draw the line.if ((x > 0) && (x < drawWidth - 50) && (y > 0) && (y < drawHeight)

&& (prevX > 0) && (prevX < drawWidth - 50) && (prevY > 0)&& (prevY < drawHeight))

g.drawLine(prevX, prevY, x, y);

// Get ready for the next line segment in the curve.prevX = x;prevY = y;

}

public void mouseReleased(MouseEvent evt) {dragging = false;

}

public void mouseClicked(MouseEvent evt) {// if right mouse button clicked, clear the screen.if (evt.getButton() == MouseEvent.BUTTON3) {

6

Introductory Java Examples

141 of 165.

Page 142: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

Graphics g = getGraphics();

g.setColor(Color.WHITE);g.fillRect(0, 0, drawWidth - 50, drawHeight);g.setColor(Color.BLACK);g.drawRect(0, 0, drawWidth - 50, drawHeight);

}

// if left mouse button clicked, change the color.if (evt.getButton() == MouseEvent.BUTTON1) {

int x = evt.getX(); // x-coordinate of mouse.int y = evt.getY(); // y-coordinate of mouse.

if (x > drawWidth - 50 && x < drawWidth) {if (y > 0 && y < 50)

drawColor = Color.BLACK;else if (y > 50 && y < 100)

drawColor = Color.RED;else if (y > 100 && y < 150)

drawColor = Color.GREEN;else if (y > 150 && y < 200)

drawColor = Color.BLUE;else if (y > 200 && y < 250)

drawColor = Color.YELLOW;else if (y > 250 && y < 300)

drawColor = Color.GRAY;else if (y > 300 && y < 350) {

Graphics g = getGraphics();

g.setColor(Color.WHITE);g.fillRect(0, 0, drawWidth - 50, drawHeight);g.setColor(Color.BLACK);g.drawRect(0, 0, drawWidth - 50, drawHeight);

}}

}}

// Some empty routines. These are required by the MouseListener// and MouseMotionListener interfaces.public void mouseEntered(MouseEvent evt) {}

public void mouseExited(MouseEvent evt) {}

public void mouseMoved(MouseEvent evt) {}

}

7

Introductory Java Examples

142 of 165.

Page 143: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

8

Introductory Java Examples

143 of 165.

Page 144: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

This is really an application and not an applet. What this does is runs the above code in a window and not through a browser. We took the drawing code from the last program and out it in a separate file (class) called PrintJPanel. The only change was taking the init function and making it a constructor.

Main:

import java.awt.*;import javax.swing.*;

public class Applets016 {

public static void main(String[] args) {JFrame window = new JFrame("GUI Test");PaintJPanel content = new PaintJPanel();window.setContentPane(content);window.setSize(507, 429);window.setLocation(100, 100);window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);window.setVisible(true);window.setResizable(false);

}}

PrintJPanel Class (PrintJPanel.java):

import java.awt.*;import java.awt.event.*;import javax.swing.*;

public class PaintJPanel extends JPanel implements MouseListener,MouseMotionListener {

private int prevX, prevY; // The previous location of the mouse.private int drawWidth = 500;private int drawHeight = 400;private boolean dragging = false;private Color drawColor;

public PaintJPanel() {addMouseListener(this);addMouseMotionListener(this);

}

public void paint(Graphics g) {super.paint(g);

g.setColor(Color.WHITE);g.fillRect(0, 0, drawWidth, drawHeight);g.setColor(Color.BLACK);g.drawRect(0, 0, drawWidth, drawHeight);

9

Introductory Java Examples

144 of 165.

Page 145: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

g.setColor(Color.BLACK);g.drawRect(0, 0, drawWidth - 50, drawHeight);

g.setColor(Color.BLACK);g.fillRect(drawWidth - 50, 0, 50, 50);g.setColor(Color.BLACK);g.drawRect(drawWidth - 50, 0, 50, 50);

g.setColor(Color.RED);g.fillRect(drawWidth - 50, 50, 50, 50);g.setColor(Color.BLACK);g.drawRect(drawWidth - 50, 50, 50, 50);

g.setColor(Color.GREEN);g.fillRect(drawWidth - 50, 100, 50, 50);g.setColor(Color.BLACK);g.drawRect(drawWidth - 50, 100, 50, 50);

g.setColor(Color.BLUE);g.fillRect(drawWidth - 50, 150, 50, 50);g.setColor(Color.BLACK);g.drawRect(drawWidth - 50, 150, 50, 50);

g.setColor(Color.YELLOW);g.fillRect(drawWidth - 50, 200, 50, 50);g.setColor(Color.BLACK);g.drawRect(drawWidth - 50, 200, 50, 50);

g.setColor(Color.GRAY);g.fillRect(drawWidth - 50, 250, 50, 50);g.setColor(Color.BLACK);g.drawRect(drawWidth - 50, 250, 50, 50);

g.drawRect(drawWidth - 50, 300, 50, 50);g.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 20));g.drawString("Clear", drawWidth - 49, 335);

drawColor = Color.BLACK;}

public void mousePressed(MouseEvent evt) {// Only draw if the left mouse button was depressed.if (evt.getButton() == MouseEvent.BUTTON1)

dragging = true;

prevX = evt.getX(); // x-coordinate where the user clicked.prevY = evt.getY(); // y-coordinate where the user clicked.

}

public void mouseDragged(MouseEvent evt) {if (!dragging)

return;

int x = evt.getX(); // x-coordinate of mouse.int y = evt.getY(); // y=coordinate of mouse.

10

Introductory Java Examples

145 of 165.

Page 146: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

Graphics g = getGraphics();g.setColor(drawColor);

// Make sure that we are in the drawing region and then draw the line.if ((x > 0) && (x < drawWidth - 50) && (y > 0) && (y < drawHeight)

&& (prevX > 0) && (prevX < drawWidth - 50) && (prevY > 0)&& (prevY < drawHeight))

g.drawLine(prevX, prevY, x, y);

// Get ready for the next line segment in the curve.prevX = x;prevY = y;

}

public void mouseReleased(MouseEvent evt) {dragging = false;

}

public void mouseClicked(MouseEvent evt) {// if right mouse button clicked, clear the screen.if (evt.getButton() == MouseEvent.BUTTON3) {

Graphics g = getGraphics();

g.setColor(Color.WHITE);g.fillRect(0, 0, drawWidth - 50, drawHeight);g.setColor(Color.BLACK);g.drawRect(0, 0, drawWidth - 50, drawHeight);

}

// if left mouse button clicked, change the color.if (evt.getButton() == MouseEvent.BUTTON1) {

int x = evt.getX(); // x-coordinate of mouse.int y = evt.getY(); // y-coordinate of mouse.

if (x > drawWidth - 50 && x < drawWidth) {if (y > 0 && y < 50)

drawColor = Color.BLACK;else if (y > 50 && y < 100)

drawColor = Color.RED;else if (y > 100 && y < 150)

drawColor = Color.GREEN;else if (y > 150 && y < 200)

drawColor = Color.BLUE;else if (y > 200 && y < 250)

drawColor = Color.YELLOW;else if (y > 250 && y < 300)

drawColor = Color.GRAY;else if (y > 300 && y < 350) {

Graphics g = getGraphics();

g.setColor(Color.WHITE);g.fillRect(0, 0, drawWidth - 50, drawHeight);g.setColor(Color.BLACK);g.drawRect(0, 0, drawWidth - 50, drawHeight);

11

Introductory Java Examples

146 of 165.

Page 147: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

}}

}}

// Some empty routines. These are required by the MouseListener// and MouseMotionListener interfaces.public void mouseEntered(MouseEvent evt) {}

public void mouseExited(MouseEvent evt) {}

public void mouseMoved(MouseEvent evt) {}

}

12

Introductory Java Examples

147 of 165.

Page 148: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

The following uses the PrintJPanel, without any modifications, turns it into an applet. The main is essentially two lines.

Main:

import java.awt.*;import javax.swing.JApplet;import java.awt.event.*;import javax.swing.*;

public class Applets017 extends JApplet {public void init() {

PaintJPanel content = new PaintJPanel();setContentPane(content);

}}

PrintJPanel Class (PrintJPanel.java):

import java.awt.*;import java.awt.event.*;import javax.swing.*;

public class PaintJPanel extends JPanel implements MouseListener,MouseMotionListener {

private int prevX, prevY; // The previous location of the mouse.private int drawWidth = 500;private int drawHeight = 400;private boolean dragging = false;private Color drawColor;

public PaintJPanel() {addMouseListener(this);addMouseMotionListener(this);

}

public void paint(Graphics g) {super.paint(g);

g.setColor(Color.WHITE);g.fillRect(0, 0, drawWidth, drawHeight);g.setColor(Color.BLACK);g.drawRect(0, 0, drawWidth, drawHeight);

g.setColor(Color.BLACK);g.drawRect(0, 0, drawWidth - 50, drawHeight);

g.setColor(Color.BLACK);g.fillRect(drawWidth - 50, 0, 50, 50);g.setColor(Color.BLACK);

13

Introductory Java Examples

148 of 165.

Page 149: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

g.drawRect(drawWidth - 50, 0, 50, 50);

g.setColor(Color.RED);g.fillRect(drawWidth - 50, 50, 50, 50);g.setColor(Color.BLACK);g.drawRect(drawWidth - 50, 50, 50, 50);

g.setColor(Color.GREEN);g.fillRect(drawWidth - 50, 100, 50, 50);g.setColor(Color.BLACK);g.drawRect(drawWidth - 50, 100, 50, 50);

g.setColor(Color.BLUE);g.fillRect(drawWidth - 50, 150, 50, 50);g.setColor(Color.BLACK);g.drawRect(drawWidth - 50, 150, 50, 50);

g.setColor(Color.YELLOW);g.fillRect(drawWidth - 50, 200, 50, 50);g.setColor(Color.BLACK);g.drawRect(drawWidth - 50, 200, 50, 50);

g.setColor(Color.GRAY);g.fillRect(drawWidth - 50, 250, 50, 50);g.setColor(Color.BLACK);g.drawRect(drawWidth - 50, 250, 50, 50);

g.drawRect(drawWidth - 50, 300, 50, 50);g.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 20));g.drawString("Clear", drawWidth - 49, 335);

drawColor = Color.BLACK;}

public void mousePressed(MouseEvent evt) {// Only draw if the left mouse button was depressed.if (evt.getButton() == MouseEvent.BUTTON1)

dragging = true;

prevX = evt.getX(); // x-coordinate where the user clicked.prevY = evt.getY(); // y-coordinate where the user clicked.

}

public void mouseDragged(MouseEvent evt) {if (!dragging)

return;

int x = evt.getX(); // x-coordinate of mouse.int y = evt.getY(); // y=coordinate of mouse.

Graphics g = getGraphics();g.setColor(drawColor);

// Make sure that we are in the drawing region and then draw the line.if ((x > 0) && (x < drawWidth - 50) && (y > 0) && (y < drawHeight)

14

Introductory Java Examples

149 of 165.

Page 150: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

&& (prevX > 0) && (prevX < drawWidth - 50) && (prevY > 0)&& (prevY < drawHeight))

g.drawLine(prevX, prevY, x, y);

// Get ready for the next line segment in the curve.prevX = x;prevY = y;

}

public void mouseReleased(MouseEvent evt) {dragging = false;

}

public void mouseClicked(MouseEvent evt) {// if right mouse button clicked, clear the screen.if (evt.getButton() == MouseEvent.BUTTON3) {

Graphics g = getGraphics();

g.setColor(Color.WHITE);g.fillRect(0, 0, drawWidth - 50, drawHeight);g.setColor(Color.BLACK);g.drawRect(0, 0, drawWidth - 50, drawHeight);

}

// if left mouse button clicked, change the color.if (evt.getButton() == MouseEvent.BUTTON1) {

int x = evt.getX(); // x-coordinate of mouse.int y = evt.getY(); // y-coordinate of mouse.

if (x > drawWidth - 50 && x < drawWidth) {if (y > 0 && y < 50)

drawColor = Color.BLACK;else if (y > 50 && y < 100)

drawColor = Color.RED;else if (y > 100 && y < 150)

drawColor = Color.GREEN;else if (y > 150 && y < 200)

drawColor = Color.BLUE;else if (y > 200 && y < 250)

drawColor = Color.YELLOW;else if (y > 250 && y < 300)

drawColor = Color.GRAY;else if (y > 300 && y < 350) {

Graphics g = getGraphics();

g.setColor(Color.WHITE);g.fillRect(0, 0, drawWidth - 50, drawHeight);g.setColor(Color.BLACK);g.drawRect(0, 0, drawWidth - 50, drawHeight);

}}

}}

// Some empty routines. These are required by the MouseListener

15

Introductory Java Examples

150 of 165.

Page 151: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

// and MouseMotionListener interfaces.public void mouseEntered(MouseEvent evt) {}

public void mouseExited(MouseEvent evt) {}

public void mouseMoved(MouseEvent evt) {}

}

16

Introductory Java Examples

151 of 165.

Page 152: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

Our final example shows that we can write one program that will run as either an application or as an applet. So if this is included in an HTML page it will run as an applet and if run through Eclipse (in application mode) or from a java command line it will run as an application. The only change is in the main where we have both a main and a init. If the program is run as an application the main will be run and if the program is run as an applet it will run the init.

Main:

import java.awt.*;import javax.swing.JApplet;import javax.swing.JFrame;import java.awt.event.*;import javax.swing.*;

public class Applets018 extends JApplet {

public static void main(String[] args) {JFrame window = new JFrame("GUI Test");PaintJPanel content = new PaintJPanel();window.setContentPane(content);window.setSize(507, 429);window.setLocation(100, 100);window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);window.setVisible(true);window.setResizable(false);

}

public void init() {PaintJPanel content = new PaintJPanel();setContentPane(content);

}}

PrintJPanel Class (PrintJPanel.java):

import java.awt.*;import java.awt.event.*;import javax.swing.*;

public class PaintJPanel extends JPanel implements MouseListener,MouseMotionListener {

private int prevX, prevY; // The previous location of the mouse.private int drawWidth = 500;private int drawHeight = 400;private boolean dragging = false;private Color drawColor;

public PaintJPanel() {addMouseListener(this);addMouseMotionListener(this);

}

17

Introductory Java Examples

152 of 165.

Page 153: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

public void paint(Graphics g) {super.paint(g);

g.setColor(Color.WHITE);g.fillRect(0, 0, drawWidth, drawHeight);g.setColor(Color.BLACK);g.drawRect(0, 0, drawWidth, drawHeight);

g.setColor(Color.BLACK);g.drawRect(0, 0, drawWidth - 50, drawHeight);

g.setColor(Color.BLACK);g.fillRect(drawWidth - 50, 0, 50, 50);g.setColor(Color.BLACK);g.drawRect(drawWidth - 50, 0, 50, 50);

g.setColor(Color.RED);g.fillRect(drawWidth - 50, 50, 50, 50);g.setColor(Color.BLACK);g.drawRect(drawWidth - 50, 50, 50, 50);

g.setColor(Color.GREEN);g.fillRect(drawWidth - 50, 100, 50, 50);g.setColor(Color.BLACK);g.drawRect(drawWidth - 50, 100, 50, 50);

g.setColor(Color.BLUE);g.fillRect(drawWidth - 50, 150, 50, 50);g.setColor(Color.BLACK);g.drawRect(drawWidth - 50, 150, 50, 50);

g.setColor(Color.YELLOW);g.fillRect(drawWidth - 50, 200, 50, 50);g.setColor(Color.BLACK);g.drawRect(drawWidth - 50, 200, 50, 50);

g.setColor(Color.GRAY);g.fillRect(drawWidth - 50, 250, 50, 50);g.setColor(Color.BLACK);g.drawRect(drawWidth - 50, 250, 50, 50);

g.drawRect(drawWidth - 50, 300, 50, 50);g.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 20));g.drawString("Clear", drawWidth - 49, 335);

drawColor = Color.BLACK;}

public void mousePressed(MouseEvent evt) {// Only draw if the left mouse button was depressed.if (evt.getButton() == MouseEvent.BUTTON1)

dragging = true;

18

Introductory Java Examples

153 of 165.

Page 154: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

prevX = evt.getX(); // x-coordinate where the user clicked.prevY = evt.getY(); // y-coordinate where the user clicked.

}

public void mouseDragged(MouseEvent evt) {if (!dragging)

return;

int x = evt.getX(); // x-coordinate of mouse.int y = evt.getY(); // y=coordinate of mouse.

Graphics g = getGraphics();g.setColor(drawColor);

// Make sure that we are in the drawing region and then draw the line.if ((x > 0) && (x < drawWidth - 50) && (y > 0) && (y < drawHeight)

&& (prevX > 0) && (prevX < drawWidth - 50) && (prevY > 0)&& (prevY < drawHeight))

g.drawLine(prevX, prevY, x, y);

// Get ready for the next line segment in the curve.prevX = x;prevY = y;

}

public void mouseReleased(MouseEvent evt) {dragging = false;

}

public void mouseClicked(MouseEvent evt) {// if right mouse button clicked, clear the screen.if (evt.getButton() == MouseEvent.BUTTON3) {

Graphics g = getGraphics();

g.setColor(Color.WHITE);g.fillRect(0, 0, drawWidth - 50, drawHeight);g.setColor(Color.BLACK);g.drawRect(0, 0, drawWidth - 50, drawHeight);

}

// if left mouse button clicked, change the color.if (evt.getButton() == MouseEvent.BUTTON1) {

int x = evt.getX(); // x-coordinate of mouse.int y = evt.getY(); // y-coordinate of mouse.

if (x > drawWidth - 50 && x < drawWidth) {if (y > 0 && y < 50)

drawColor = Color.BLACK;else if (y > 50 && y < 100)

drawColor = Color.RED;else if (y > 100 && y < 150)

drawColor = Color.GREEN;else if (y > 150 && y < 200)

drawColor = Color.BLUE;else if (y > 200 && y < 250)

19

Introductory Java Examples

154 of 165.

Page 155: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

drawColor = Color.YELLOW;else if (y > 250 && y < 300)

drawColor = Color.GRAY;else if (y > 300 && y < 350) {

Graphics g = getGraphics();

g.setColor(Color.WHITE);g.fillRect(0, 0, drawWidth - 50, drawHeight);g.setColor(Color.BLACK);g.drawRect(0, 0, drawWidth - 50, drawHeight);

}}

}}

// Some empty routines. These are required by the MouseListener// and MouseMotionListener interfaces.public void mouseEntered(MouseEvent evt) {}

public void mouseExited(MouseEvent evt) {}

public void mouseMoved(MouseEvent evt) {}

}

20

Introductory Java Examples

155 of 165.

Page 156: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

Applet Examples #3: A Little GUI Programming

In the last handout we saw how to link the actions of the mouse to our program and get it to respond depending on how the mouse was used. In modern programming facilities like menus, tool bars, text boxes, buttons, check boxes, drop-down selections, lists, trees, etc. have become standard interface tools that most users now expect in a good piece of software. Most programming environments that are built for graphical user interface programming (GUI) have these controls and several others that may not be as common. In Java, there are two systems that allow you to create these types of tools and incorporate them into your program. The older one is AWT (Abstract Windowing Toolkit). The AWT still has some facilities that we use but for the most part the controls themselves are not AWT they are the newer toolkit called Swing. So in Swing, there are ways to incorporate standard interface tools such as buttons, menus, etc. To do justice with GUI programming you really need to take an entire course in GUI design and implementation. Here we will look at how to make Java respond to one easy control, the button. When you click on a button you expect the program to respond in some manner. In the program code you simply set up the framework for this to take place and then write the response code.

The program we will write is similar to the paint program from the last handout. It will not have the ability to change colors but we will place buttons at the bottom to clear the screen and to display 300 random lines in random colors.

The first example is really an application that sets up all the buttons and links their functionality to the PrintJPanel. The PrintJPanel is similar to the one developed in the last handout but we have just implemented the free drawing in one color. Note in the PrintJPanel class we have added a method to create the random lines and one to clesr the screen. In the main we sinply call these functions on the click of the button.

Main:

import java.awt.*;import java.awt.event.*;import javax.swing.*;import javax.swing.border.*;

public class Applets019 extends JFrame {

public static void main(String[] args) {

JPanel content = new JPanel();content.setLayout(new BorderLayout());final PaintJPanel paintArea = new PaintJPanel();

JButton OK_Button = new JButton("OK");OK_Button.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent evt) {System.exit(0);

}});

1

Introductory Java Examples

156 of 165.

Page 157: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

JButton Cancel_Button = new JButton("Clear");Cancel_Button.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent evt) {paintArea.clearScreen();

}});

JButton Random_Button = new JButton("Random");Random_Button.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent evt) {paintArea.randomLines();

}});

JPanel buttons = new JPanel();buttons.add(OK_Button);buttons.add(Cancel_Button);buttons.add(Random_Button);

content.add(buttons, BorderLayout.SOUTH);content.add(paintArea, BorderLayout.CENTER);paintArea.setBorder(new LineBorder(Color.BLACK));buttons.setBorder(new LineBorder(Color.BLACK));

JFrame window = new JFrame("GUI Test 2");window.setContentPane(content);window.setSize(507, 429);window.setLocation(100, 100);window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);window.setVisible(true);

}}

PrintJPanel:

import java.awt.*;import java.awt.event.*;import java.util.Random;import javax.swing.*;

public class PaintJPanel extends JPanel implements MouseListener,MouseMotionListener {

private int prevX, prevY; // The previous location of the mouse.private Color drawColor;

public PaintJPanel(){addMouseListener(this);addMouseMotionListener(this);

}

2

Introductory Java Examples

157 of 165.

Page 158: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

public void clearScreen() {Graphics g = getGraphics();

int drawWidth = getWidth();int drawHeight = getHeight();

g.setColor(Color.WHITE);g.fillRect(0, 0, drawWidth, drawHeight);g.setColor(Color.BLACK);g.drawRect(0, 0, drawWidth, drawHeight);

}

public void randomLines() {Graphics g = getGraphics();Random gen = new Random();

int drawWidth = getWidth();int drawHeight = getHeight();

for (int i = 0; i < 300; i++) {g.setColor(new Color(gen.nextInt(255), gen.nextInt(255), gen

.nextInt(255)));g.drawLine(gen.nextInt(drawWidth), gen.nextInt(drawHeight),

gen.nextInt(drawWidth), gen.nextInt(drawHeight));}

}

public void paint(Graphics g) {super.paint(g);

int drawWidth = getWidth();int drawHeight = getHeight();

g.setColor(Color.WHITE);g.fillRect(0, 0, drawWidth, drawHeight);g.setColor(Color.BLACK);g.drawRect(0, 0, drawWidth, drawHeight);

}

public void mousePressed(MouseEvent evt) {prevX = evt.getX(); // x-coordinate where the user clicked.prevY = evt.getY(); // y-coordinate where the user clicked.

}

public void mouseDragged(MouseEvent evt) {int x = evt.getX(); // x-coordinate of mouse.int y = evt.getY(); // y=coordinate of mouse.int drawWidth = getWidth();int drawHeight = getHeight();

Graphics g = getGraphics();

// Make sure that we are in the drawing region and then draw the line.if ((x > 0) && (x < drawWidth) && (y > 0) && (y < drawHeight)

&& (prevX > 0) && (prevX < drawWidth) && (prevY > 0)

3

Introductory Java Examples

158 of 165.

Page 159: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

&& (prevY < drawHeight))g.drawLine(prevX, prevY, x, y);

// Get ready for the next line segment in the curve.prevX = x;prevY = y;

}

// Some empty routines. These are required by the MouseListener// and MouseMotionListener interfaces.

public void mouseReleased(MouseEvent evt) {}

public void mouseClicked(MouseEvent evt) {}

public void mouseEntered(MouseEvent evt) {}

public void mouseExited(MouseEvent evt) {}

public void mouseMoved(MouseEvent evt) {}

}

4

Introductory Java Examples

159 of 165.

Page 160: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

The following simply converts the application above to an applet. Note that We do not need the OK button since we will not be shutting down the program, it is the browser's job to do that. The result is the same as above but it is run as an applet. Note that the PrintJPanel class is unaltered.

import java.awt.BorderLayout;import java.awt.Color;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import javax.swing.JApplet;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JPanel;import javax.swing.border.LineBorder;

public class Applets020 extends JApplet {

public void init() {JPanel content = new JPanel();content.setLayout(new BorderLayout());final PaintJPanel paintArea = new PaintJPanel();

JButton Cancel_Button = new JButton("Clear");Cancel_Button.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent evt) {paintArea.clearScreen();

}});

JButton Random_Button = new JButton("Random");Random_Button.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent evt) {paintArea.randomLines();

}});

JPanel buttons = new JPanel();buttons.add(Cancel_Button);buttons.add(Random_Button);

content.add(buttons, BorderLayout.SOUTH);content.add(paintArea, BorderLayout.CENTER);paintArea.setBorder(new LineBorder(Color.BLACK));buttons.setBorder(new LineBorder(Color.BLACK));

setContentPane(content);}

}

5

Introductory Java Examples

160 of 165.

Page 161: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

As you saw in the last handout, you can combine the programs into one so that the program can run either as an application or as an applet. Again, the PrintJPanel class was not changed.

import java.awt.BorderLayout;import java.awt.Color;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import javax.swing.JApplet;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JPanel;import javax.swing.border.LineBorder;

public class Applets021 extends JApplet {

public static void main(String[] args) {JPanel content = new JPanel();content.setLayout(new BorderLayout());final PaintJPanel paintArea = new PaintJPanel();

JButton OK_Button = new JButton("OK");OK_Button.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent evt) {System.exit(0);

}});

JButton Cancel_Button = new JButton("Clear");Cancel_Button.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent evt) {paintArea.clearScreen();

}});

JButton Random_Button = new JButton("Random");Random_Button.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent evt) {paintArea.randomLines();

}});

JPanel buttons = new JPanel();buttons.add(OK_Button);buttons.add(Cancel_Button);buttons.add(Random_Button);

content.add(buttons, BorderLayout.SOUTH);content.add(paintArea, BorderLayout.CENTER);paintArea.setBorder(new LineBorder(Color.BLACK));buttons.setBorder(new LineBorder(Color.BLACK));

JFrame window = new JFrame("GUI Test 2");window.setContentPane(content);window.setSize(507, 429);window.setLocation(100, 100);

6

Introductory Java Examples

161 of 165.

Page 162: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);window.setVisible(true);

}

public void init() {JPanel content = new JPanel();content.setLayout(new BorderLayout());final PaintJPanel paintArea = new PaintJPanel();

JButton Cancel_Button = new JButton("Clear");Cancel_Button.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent evt) {paintArea.clearScreen();

}});

JButton Random_Button = new JButton("Random");Random_Button.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent evt) {paintArea.randomLines();

}});

JPanel buttons = new JPanel();buttons.add(Cancel_Button);buttons.add(Random_Button);

content.add(buttons, BorderLayout.SOUTH);content.add(paintArea, BorderLayout.CENTER);paintArea.setBorder(new LineBorder(Color.BLACK));buttons.setBorder(new LineBorder(Color.BLACK));

setContentPane(content);}

}

7

Introductory Java Examples

162 of 165.

Page 163: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

Recursion Examples

public class Recursion001 {

// Factorial: Recursive implementation n! = n*(n-1)!public static long factorialRecursive(long n) {

if (n == 0)return 1;

return n * factorialRecursive(n - 1);}

// Factorial: Iterative implementation n! = 1*2*3*...*npublic static long factorialIterative(long n) {

long num = 1;for (int i = 1; i <= n; i++)

num = num * i;

return num;}

// Fibonacci Numbers: Recursive implementation Fn = Fn-1 + Fn-2public static int FibonacciRecursive(int n) {

if ((n == 1) || (n == 2))return 1;

return FibonacciRecursive(n - 1) + FibonacciRecursive(n - 2);}

// Fibonacci Numbers: Iterative implementation Fn = Fn-1 + Fn-2public static long FibonacciIterative(long n) {

long backOne = 1;long backTwo = 1;long num = 1;for (int i = 3; i <= n; i++) {

num = backOne + backTwo;backTwo = backOne;backOne = num;

}return num;

}

public static int add_digits(int n) {int sum = 0;while (n > 0) {

sum += (n % 10);n = n / 10;

}return sum;

}

1

Introductory Java Examples

163 of 165.

Page 164: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

// Divisibility by 9 recursivepublic static boolean isDiv9(int num) {

if (num == 9)return true;

else if (num > 9)return isDiv9(add_digits(num));

return false;}

// Divisibility by 3 recursivepublic static boolean isDiv3(int num) {

if (num == 3 || num == 6 || num == 9)return true;

else if (num > 9)return isDiv3(add_digits(num));

return false;}

public static void main(String[] args) {for (int i = 0; i <= 10; i++)

System.out.println("" + i + "! = " + factorialRecursive(i) + " = "+ factorialIterative(i));

System.out.println();

for (int i = 1; i <= 10; i++)System.out.println("F" + i + " = " + FibonacciRecursive(i) + " = "

+ FibonacciIterative(i));

System.out.println();System.out.println(isDiv3(78391752));System.out.println(isDiv3(78391750));System.out.println(isDiv9(78391752));System.out.println(isDiv9(78391755));

}}

Run:

0! = 1 = 11! = 1 = 12! = 2 = 23! = 6 = 64! = 24 = 245! = 120 = 1206! = 720 = 7207! = 5040 = 50408! = 40320 = 403209! = 362880 = 36288010! = 3628800 = 3628800

F1 = 1 = 1F2 = 1 = 1

F3 = 2 = 2F4 = 3 = 3F5 = 5 = 5F6 = 8 = 8F7 = 13 = 13F8 = 21 = 21F9 = 34 = 34F10 = 55 = 55

truefalsefalsetrue

2

Introductory Java Examples

164 of 165.

Page 165: Basic Java Commands Examples - Faculty & Stafffaculty.salisbury.edu/~xswang/Courses/csc117/IntroJava...Basic Java Commands Examples SphereProperties is a program that will take as

import java.util.Scanner;

public class Recursion002 {

public static void hanoi(int n, String begin, String end, String temp) {if (n == 1)

System.out.println("move " + begin + " to " + end);else {

hanoi(n - 1, begin, temp, end);System.out.println("move " + begin + " to " + end);hanoi(n - 1, temp, end, begin);

}}

public static void main(String[] args) {Scanner keyboard = new Scanner(System.in);

System.out.print("Input the number of disks: ");int numDisks = keyboard.nextInt();hanoi(numDisks, "A", "B", "C");

}}

Runs:

Input the number of disks: 3move A to Bmove A to Cmove B to Cmove A to Bmove C to Amove C to Bmove A to B

Input the number of disks: 4move A to Cmove A to Bmove C to Bmove A to Cmove B to Amove B to Cmove A to Cmove A to Bmove C to Bmove C to Amove B to Amove C to Bmove A to Cmove A to Bmove C to B

3

Introductory Java Examples

165 of 165.


Recommended