//Introduction to Java Programming

//p30/603 2021年03月21日 星期日 13时46分12秒
import javax.swing.JOptionPane;
import java.util.Scanner;

public class hello{
/* public static void main(String[] args){
System.out.println(“Welcome to Java!”);
}
wannian07@wannian07-PC:~/Desktop/Introduction to Java Programming$ java hello
Welcome to Java!
/
public static void main(String[] args){
//Welcome1.java 2021年03月21日 星期日 13时49分25秒
/
System.out.println(“Programming is fun!”);
System.out.println(“Fundamentals First!”);
System.out.println(“Problem Driven!”);
wannian07@wannian07-PC:~/Desktop/Introduction to Java Programming$ java hello
Programming is fun!
Fundamentals First!
Problem Driven!

//ComputeExpression.javaSystem.out.println((10.5 + 2* 3)/(45- 3.5));wannian07@wannian07-PC:~/Desktop/Introduction to Java Programming$ java hello0.39759036144578314//WelcomInMessageDialogBox.java
//  JOptionPane.showMessageDialog(null, "welcome to Java!");//ComputerArea.java  2021年03月21日 星期日 14时03分47秒 double radius;double area;radius = 20;area = radius * radius * 3.14159;System.out.println("The area for the circle of radius " + radius + " is "+area);wannian07@wannian07-PC:~/Desktop/Introduction to Java Programming$ java helloThe area for the circle of radius 20.0 is 1256.636Scanner input = new Scanner(System.in);System.out.print("Enter a number for radius: ");double radius = input.nextDouble();double area = radius * radius * 3.14159;System.out.println("The area for the circle of radius "+ radius +" is " + area);wannian07@wannian07-PC:~/Desktop/Introduction to Java Programming$ java helloEnter a number for radius: 15.5The area for the circle of radius 15.5 is 754.7669975//ComputerAverage.javaScanner input = new Scanner(System.in);System.out.print("Enter three numbers: ");double number1 = input.nextDouble();double number2 = input.nextDouble();double number3 = input.nextDouble();double average = (number1 + number2 + number3)/3;System.out.println("The average of " + number1 + " " + number2 +" " + number3 + " is " + average);wannian07@wannian07-PC:~/Desktop/Introduction to Java Programming$ java helloEnter three numbers: 15.516.517.5The average of 15.5 16.5 17.5 is 16.5
//ComputeArea.java: Compute the area of a circledouble radius = 20;final double PI = 3.14159;double area = radius * radius * PI;System.out.println("The area for the circle of radius " + radius + " is "+area);wannian07@wannian07-PC:~/Desktop/Introduction to Java Programming$ java helloThe area for the circle of radius 20.0 is 1256.636//DisplayTime.java  2021年03月21日 星期日 14时16分59秒 Scanner input = new Scanner(System.in);System.out.print("Enter an integer for seconds: ");int seconds = input.nextInt();int minutes = seconds / 60;int remainingSeconds = seconds % 60;System.out.println(seconds + " seconds is " + minutes + " minutes and " + remainingSeconds + " seconds");wannian07@wannian07-PC:~/Desktop/Introduction to Java Programming$ java helloEnter an integer for seconds: 1212512125 seconds is 202 minutes and 5 seconds//FahrenheitToCelsius.java  2021年03月21日 星期日 14时18分20秒 Scanner input = new Scanner(System.in);System.out.print("Enter a degree in Fahrenheit: ");double fahrenheit = input.nextDouble();double celsius = (5.0 / 9)* (fahrenheit - 32);System.out.println("Fahrenheit "+ fahrenheit + " is " + celsius + " in Celsius");wannian07@wannian07-PC:~/Desktop/Introduction to Java Programming$ java helloEnter a degree in Fahrenheit: 100Fahrenheit 100.0 is 37.77777777777778 in Celsius

//ShowCurrentTime.java 2021年03月21日 星期日 14时33分29秒
long totalMilliseconds = System.currentTimeMillis();
long totalSeconds = totalMilliseconds / 1000;
long currentSecond = totalSeconds % 60;
long totalMinutes = totalSeconds / 60;
long currentMinute = totalMinutes % 60;
long totalHours = totalMinutes / 60;
long currentHour = totalHours % 24;
System.out.println("Current time is “+ currentHour + “:”
+ currentMinute + “:” + currentSecond + " GMT”);
wannian07@wannian07-PC:~/Desktop/Introduction to Java Programming$ java hello
Current time is 6:32:51 GMT

//SalesTax.java Scanner input = new Scanner(System.in);System.out.print("Enter puchase amount: ");    double purchaseAmount = input.nextDouble();double tax = purchaseAmount * 0.06;System.out.println("Sales tax is "+ (int)(tax * 100)/ 100.0);wannian07@wannian07-PC:~/Desktop/Introduction to Java Programming$ java helloEnter puchase amount: 197.55Sales tax is 11.85//ComputeLoan.java  2021年03月21日 星期日 14时37分59秒 Scanner input = new Scanner(System.in);System.out.print("Enter yearly interest rate, for example 8.25: ");double annualInterestRate = input.nextDouble();double monthlyInterestRate = annualInterestRate / 1200;System.out.print("Enter number of years as an integer, for example 5: ");int numberOfYears = input.nextInt();System.out.print("Enter loan amount, for example 120000.95: ");double loanAmount = input.nextDouble();double monthlyPayment = loanAmount * monthlyInterestRate / (1-1/Math.pow(1 + monthlyInterestRate, numberOfYears* 12));double totalPayment = monthlyPayment* numberOfYears* 12;System.out.println("The monthly payment is " +(int)(monthlyPayment * 100)/ 100.0);System.out.println("The total payment is " +(int)(totalPayment * 100)/ 100.0);wannian07@wannian07-PC:~/Desktop/Introduction to Java Programming$ java helloEnter yearly interest rate, for example 8.25: 5.75Enter number of years as an integer, for example 5: 15Enter loan amount, for example 120000.95: 250000The monthly payment is 2076.02The total payment is 373684.53

//DispalyUnicode.java 2021年03月21日 星期日 21时40分12秒
JOptionPane.showMessageDialog(null,
“\u6B22\u8FCE\u03b1\u03b2\u03b3”,
“\u6B22\u8FCE Welcome”,
JOptionPane.INFORMATION_MESSAGE);

//ComputeChange.java Scanner input = new Scanner(System.in);System.out.print("Enter an amount in double, for example 11.56: ");double amount = input.nextDouble();int remainingAmount = (int)(amount * 100);int numberOfOneDollars = remainingAmount / 100;remainingAmount = remainingAmount % 100;int numberOfQuarters = remainingAmount / 25;remainingAmount = remainingAmount % 25;int numberOfDimes = remainingAmount / 10;remainingAmount = remainingAmount % 10;int numberOfNickels = remainingAmount % 5;remainingAmount = remainingAmount % 5;int numberOfPennies = remainingAmount;System.out.println("Your amount "+ amount + "consists of\n" +"\t" + numberOfOneDollars + " dollars\n" + "\t" + numberOfQuarters + " quarters\n" + "\t" + numberOfDimes + " dimes\n" +"\t" + numberOfNickels + " nickels\n" + "\t" + numberOfPennies + " pennies"); wannian07@wannian07-PC:~/Desktop/Introduction to Java Programming$ java helloEnter an amount in double, for example 11.56: 11.56Your amount 11.56consists of11 dollars2 quarters0 dimes1 nickels1 pennies//ComputeLoanUsingInputDialog.java 2021年03月21日 星期日 21时55分36秒
String annualInterestRateString = JOptionPane.showInputDialog("Enter yearly interest rate, for example 8.25:");
double annualInterestRate = Double.parseDouble(annualInterestRateString);
double monthlyInterestRate = annualInterestRate / 1200;String numberOfYearsString = JOptionPane.showInputDialog("Enter number of years as an  integer, \nfor example 5:");
int numberOfYears = Integer.parseInt(numberOfYearsString);String loanString = JOptionPane.showInputDialog("Enter loan amount, for example 120000.95:");double loanAmount = Double.parseDouble(loanString);double monthlyPayment = loanAmount * monthlyInterestRate / (1
-1/Math.pow(1 + monthlyInterestRate, numberOfYears * 12));
double totalPayment = monthlyPayment * numberOfYears * 12;monthlyPayment = (int)(monthlyPayment * 100) / 100.0;
totalPayment = (int)(totalPayment * 100)/ 100.0;String output = "The monthly payment is " + monthlyPayment + "\nThe toal payment is " + totalPayment;
JOptionPane.showMessageDialog(null, output);

//AdditionQuiz.java 2021年03月25日 星期四 19时55分38秒
int number1 = (int)(System.currentTimeMillis() % 10);
int number2 = (int)(System.currentTimeMillis() * 7 % 10);
Scanner input = new Scanner(System.in);
System.out.print(
"What is " + number1 + " + " + number2 + " ? ");
int answer = input.nextInt();
System.out.println(
number1 + " + " + number2 + " = " + answer + " is " +
(number1 + number2 == answer));
wannian07@wannian07-PC:~/Desktop/Introduction to Java Programming$ java hello
What is 4 + 8 ? 4
4 + 8 = 4 is false

//SimpleIfDemo.java 2021年03月25日 星期四 19时56分14秒 Scanner input = new Scanner(System.in);System.out.println("Enter an integer: ");int number = input.nextInt();if(number % 5 == 0)System.out.println("HiFive");if(number % 2 == 0)System.out.println("HiEven");
wannian07@wannian07-PC:~/Desktop/Introduction to Java Programming$ java helloEnter an integer: 30HiFiveHiEven//GuessBirthday.java 2021年03月25日 星期四 20时00分43秒 String set1 = "1   3  5  7\n" + "9  11 13 15\n" +"17 19 21 23\n" +"25 27 29 31";String set2 = "2   3  6  7\n" +"10 11 14 15\n" +"20 21 22 23\n" +"28 29 30 31";String set3 = "4   5  6  7\n" +"12 13 14 15\n" +"20 21 22 23\n" +"28 29 30 31";String set4 = "8   9 10 11\n" +"12 13 14 15\n" +"24 25 26 27\n" +"28 29 30 31";String set5 = "16 17 18 19\n" +"20 21 22 23\n" +"24 25 26 27\n" +"28 29 30 31";int day = 0;Scanner input = new Scanner(System.in);System.out.print("Is your birthday in Set1?\n");System.out.print(set1);System.out.print("\nEnter 0 for No and 1 for Yes: ");int answer = input.nextInt();if(answer == 1)day += 1;System.out.print("Is your birthday in Set2?\n");System.out.print(set2);System.out.print("\nEnter 0 for No and 1 for Yes: ");answer = input.nextInt();if(answer == 1)day += 2;System.out.print("Is your birthday in Set3?\n");System.out.print(set3);System.out.print("\nEnter 0 for No and 1 for Yes: ");answer = input.nextInt();if(answer == 1)day += 4;System.out.print("\nIs your birthday in Set4?\n");System.out.print(set4);System.out.print("\nEnter 0 for No and 1 for Yes: ");answer = input.nextInt();if(answer == 1)day += 8;System.out.print("Is your birthday in Set5?\n");System.out.print(set5);System.out.print("\nEnter 0 for No and 1 for Yes: ");answer = input.nextInt();if(answer == 1)day += 16;System.out.println("\nYour birthday is " + day + "!");
wannian07@wannian07-PC:~/Desktop/Introduction to Java Programming$ java helloIs your birthday in Set1?1   3  5  79  11 13 1517 19 21 2325 27 29 31Enter 0 for No and 1 for Yes: 1Is your birthday in Set2?2   3  6  710 11 14 1520 21 22 2328 29 30 31Enter 0 for No and 1 for Yes: 1Is your birthday in Set3?4   5  6  712 13 14 1520 21 22 2328 29 30 31Enter 0 for No and 1 for Yes: 0Is your birthday in Set4?8   9 10 1112 13 14 1524 25 26 2728 29 30 31Enter 0 for No and 1 for Yes: 0Is your birthday in Set5?16 17 18 1920 21 22 2324 25 26 2728 29 30 31Enter 0 for No and 1 for Yes: 1Your birthday is 19!
//SubtractionQuiz.java   2021年03月26日 星期五 07时26分29秒  int number1 = (int)(Math.random() * 10);int number2 = (int)(Math.random() * 10);if(number1 < number2){int temp = number1;number1 = number2;number2 = temp;}System.out.print("What is " + number1 + "-" + number2 +"?");Scanner input = new Scanner(System.in);int answer = input.nextInt();if (number1 - number2 == answer)System.out.println("You are correct!");elseSystem.out.println("Your answer is wrong\n" + number1 +"-" + number2 + " should be " + (number1 - number2));
wannian07@wannian07-PC:~/Desktop/Introduction to Java Programming$ java helloWhat is 8-3?5You are correct!// ComputerBMI.java  2021年03月26日 星期五 07时34分37秒   Scanner input = new Scanner(System.in);System.out.print("Enter weight in pounds: ");double weight = input.nextDouble();System.out.print("Enter height in inches: ");double height = input.nextDouble();final double KILOGRAMS_PER_POUND = 0.45359237;final double METERS_PER_INCH = 0.0254;double weightInKilograms = weight * KILOGRAMS_PER_POUND;double heightInMeters = height * METERS_PER_INCH;double bmi = weightInKilograms /(heightInMeters * heightInMeters);System.out.println("Your BMI is " + bmi);if(bmi < 16)System.out.println("You are seriously underweight");else if(bmi < 18)System.out.println("You are  underweight");else if(bmi < 24)System.out.println("You are normal weight");else if(bmi < 29)System.out.println("You are overweight");else if(bmi < 35)System.out.println("You are seriously overweight");elseSystem.out.println("You are gravely overweight");
wannian07@wannian07-PC:~/Desktop/Introduction to Java Programming$ java helloEnter weight in pounds: 146Enter height in inches: 70Your BMI is 20.948603801493316You are normal weight//ComputeTax.javaScanner input = new Scanner(System.in);System.out.print("(0-single filer, 1-married jointly,\n" +"2-married separately, 3-head of household)\n" +"Enter the filing status: ");int status = input.nextInt();System.out.print("Enter the taxable income: ");double income = input.nextDouble();double tax = 0;if(status == 0){if(income <= 8350)tax = income * 0.10;else if(income <= 33950)  tax = 8350 * 0.10 + (income - 8350)* 0.15;else if(income <= 82250)    tax = 8350 * 0.10 + (33950-8350)* 0.15 + (income - 33950)* 0.25;else if(income <= 171550)    tax = 8350 * 0.10 + (33950 - 8350)* 0.15+ (82250-33950)* 0.25 +(income - 82250) * 0.28;else if(income <= 372950)    tax = 8350 * 0.10 + (33950 - 8350)* 0.15+ (82250-33950)* 0.25 +(171550 - 82250) * 0.28 +(income - 171550)*0.33;elsetax = 8350 * 0.10 + (33950 - 8350)* 0.15+ (82250-33950)* 0.25 +(171550 - 82250) * 0.28 +(372950 - 171550)*0.33 +(income -372950) * 0.35 ; }else if(status == 1){}else if(status == 2){}else if(status == 3){}else {System.out.println("Error: invalid status");System.exit(0);}System.out.println("Tax is " + (int)(tax *100)/100.0);
wannian07@wannian07-PC:~/Desktop/Introduction to Java Programming$ java hello(0-single filer, 1-married jointly,2-married separately, 3-head of household)Enter the filing status: 0Enter the taxable income: 400000Tax is 117683.5

//TestBooleanOperators.java 3-7
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer: ");
int number = input.nextInt();
System.out.println("Is " + number + "\n\tdivisible by 2 and 3? "+
(number % 2 == 0 && number % 3 == 0) + "\n\tdivisible by 2 or 3? " +
(number % 2 == 0 || number % 3 == 0) + "\n\tdivisible by 2 or 3, but not both? "
+ (number % 2 == 0 ^ number % 3 == 0));
wannian07@wannian07-PC:~/Desktop/Introduction to Java Programming$ java hello
Enter an integer: 18
Is 18
divisible by 2 and 3? true
divisible by 2 or 3? true
divisible by 2 or 3, but not both? false

//leapYear.java 3-8 Scanner input = new Scanner(System.in);System.out.print("Enter a year: ");int year = input.nextInt();boolean isLeapYear = (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);System.out.println(year + " is a leap year? " + isLeapYear);wannian07@wannian07-PC:~/Desktop/Introduction to Java Programming$ java helloEnter a year: 2008 2008 is a leap year? truewannian07@wannian07-PC:~/Desktop/Introduction to Java Programming$ java helloEnter a year: 20022002 is a leap year? false//Lottery.java 3-9 2021年03月27日 星期六 10时10分53秒 int lottery = (int)(Math.random() * 100);Scanner input = new Scanner(System.in);System.out.print("Enter your lottery pick(two digits): ");int guess = input.nextInt();int lotteryDigit1 = lottery / 10;int lotteryDigit2 = lottery % 10;int guessDigit1 = guess / 10;int guessDigit2 = guess % 10;System.out.println("The lottery number is " + lottery);if(guess == lottery)System.out.println("Exact match: you win $10,000");else if(guessDigit2 == lotteryDigit1 && guessDigit1 == lotteryDigit2)System.out.println("Match all digits: you win $30,000");else if(guessDigit1 == lotteryDigit1 || guessDigit1 == lotteryDigit2|| guessDigit2 == lotteryDigit1 || guessDigit2 == lotteryDigit2)System.out.println("Match one digit: you win $1,000");elseSystem.out.println("Sorry, no match");wannian07@wannian07-PC:~/Desktop/Introduction to Java Programming$ java helloEnter your lottery pick(two digits): 45The lottery number is 37Sorry, no match//GuessBirthdayUsingConfirmationDialog.java 3-10String set1 = "1   3  5  7\n" + "9  11 13 15\n" +"17 19 21 23\n" +"25 27 29 31";String set2 = "2   3  6  7\n" +"10 11 14 15\n" +"20 21 22 23\n" +"28 29 30 31";String set3 = "4   5  6  7\n" +"12 13 14 15\n" +"20 21 22 23\n" +"28 29 30 31";String set4 = "8   9 10 11\n" +"12 13 14 15\n" +"24 25 26 27\n" +"28 29 30 31";String set5 = "16 17 18 19\n" +"20 21 22 23\n" +"24 25 26 27\n" +"28 29 30 31";int day = 0;int answer = JOptionPane.showConfirmDialog(null, "Is your birthday in these numbers?\n" + set1);if(answer == JOptionPane.YES_OPTION)day += 1;answer = JOptionPane.showConfirmDialog(null, "Is your birthday in these numbers?\n" + set2);if(answer == JOptionPane.YES_OPTION)day += 2;answer = JOptionPane.showConfirmDialog(null, "Is your birthday in these numbers?\n" + set3);if(answer == JOptionPane.YES_OPTION)day += 4;answer = JOptionPane.showConfirmDialog(null, "Is your birthday in these numbers?\n" + set4);if(answer == JOptionPane.YES_OPTION)day += 8;answer = JOptionPane.showConfirmDialog(null, "Is your birthday in these numbers?\n" + set5);if(answer == JOptionPane.YES_OPTION)day += 16;answer = JOptionPane.showConfirmDialog(null, "Your birthday is " +day+ " ! " );//GuessNumberOneTime.java 4-1int number = (int)(Math.random() * 101);Scanner input = new Scanner(System.in);System.out.println("Guess a magic number between 0 and 100");int guess = -1;while (true){System.out.print("\nEnter your guess: ");guess = input.nextInt();if(guess == number)System.out.println("Yes, the number is " + number);else if(guess > number) System.out.println("Your guess is too high ");else System.out.println("Your guess is too low ");}wannian07@wannian07-PC:~/Desktop/Introduction to Java Programming$ java helloGuess a magic number between 0 and 100Enter your guess: 80Your guess is too high Enter your guess: 40Your guess is too low Enter your guess: 60Your guess is too high Enter your guess: 50Your guess is too high Enter your guess: 45Your guess is too high Enter your guess: 42Your guess is too high Enter your guess: 41Yes, the number is 41//GuessNumberOneTime.java 4-1 P92 2021年03月28日 星期日 07时15分35秒 int number = (int)(Math.random() * 101);Scanner input = new Scanner(System.in);System.out.println("Guess a magic number between 0 and 100");int guess = -1;while(guess != number){System.out.print("\nEnter your guess: ");guess = input.nextInt();if(guess == number)System.out.println("Yes, the number is " + number);else if(guess > number)System.out.println("Your geuss is too high");elseSystem.out.println("Your guess is too low");
wannian07@wannian07-PC:~/Desktop/Introduction to Java Programming$ java helloGuess a magic number between 0 and 100Enter your guess: 60Your geuss is too highEnter your guess: 30Your guess is too lowEnter your guess: 45Your geuss is too highEnter your guess: 37Your guess is too lowEnter your guess: 42Your geuss is too highEnter your guess: 40Your geuss is too highEnter your guess: 39Yes, the number is 39}//SubtrationQuizLoop.java 4-3 2021年03月28日 星期日 07时27分25秒 final int NUMBER_OF_QUESTIONS = 5;int correctCount = 0;int count = 0;long startTime = System.currentTimeMillis();String output = " ";Scanner input = new Scanner(System.in);while(count < NUMBER_OF_QUESTIONS){int number1 = (int)(Math.random()* 10);int number2 = (int)(Math.random()* 10);if(number1 < number2){int temp = number1;number1 = number2;number2 = temp;}System.out.print("What is " + number1 + "-" + number2 + "? ");int answer = input.nextInt();if(number1 - number2 == answer){System.out.println("You are correct!");correctCount++;}elseSystem.out.println("Your answer if wrong.\n" + number1+ " - " + number2 + " should be " + (number1 - number2));count++;output += "\n" + number1 + " - " + number2 + " = " + answer +((number1 - number2 == answer)? " correct":" wrong");}long endTime = System.currentTimeMillis();long testTime = endTime - startTime;System.out.println("Correct count is " + correctCount +"\nTest time is " + testTime / 1000 + " seconds\n" + output);
wannian07@wannian07-PC:~/Desktop/Introduction to Java Programming$ java helloWhat is 7-5? 1Your answer if wrong.7 - 5 should be 2What is 9-0? 3Your answer if wrong.9 - 0 should be 9What is 6-0? 4Your answer if wrong.6 - 0 should be 6What is 7-2? 5You are correct!What is 9-6? 3You are correct!Correct count is 2Test time is 10 seconds7 - 5 = 1 wrong9 - 0 = 3 wrong6 - 0 = 4 wrong7 - 2 = 5 correct9 - 6 = 3 correct//4-4 SentinelValue.java 2021年03月28日 星期日 07时42分33秒 Scanner input = new Scanner(System.in);System.out.print("Enter an int value (the program exits if the input is 0):" );int data = input.nextInt();int sum = 0;while(data != 0){sum += data;System.out.print("Enter an int value (the program exits if the input is 0):");data = input.nextInt();}System.out.println("The sum is " + sum);
wannian07@wannian07-PC:~/Desktop/Introduction to Java Programming$ java helloEnter an int value (the program exits if the input is 0):3Enter an int value (the program exits if the input is 0):4Enter an int value (the program exits if the input is 0):5Enter an int value (the program exits if the input is 0):0The sum is 12//4-5 TestDoWhile.javaint data;int sum = 0;Scanner input = new Scanner(System.in);do{System.out.print("Enter an int value (the program exits if the input is 0):");data = input.nextInt();sum += data;    }while(data != 0);System.out.println("The sum is "+ sum);
wannian07@wannian07-PC:~/Desktop/Introduction to Java Programming$ java helloEnter an int value (the program exits if the input is 0):3Enter an int value (the program exits if the input is 0):4Enter an int value (the program exits if the input is 0):5Enter an int value (the program exits if the input is 0):0The sum is 12//4-6 MultiplicationTable.java 2021年03月28日 星期日 07时51分06秒 System.out.println("   Multiplication Table");System.out.print("  ");for(int j = 1; j <= 9; j++)System.out.print("   "+ j);System.out.println("\n---------------------------------------");for(int i = 1; i <= 9; i++){System.out.print(i + "|");for(int j = 1; j <= 9; j++){System.out.printf("%4d", i*j);}System.out.println();}
wannian07@wannian07-PC:~/Desktop/Introduction to Java Programming$ java helloMultiplication Table1   2   3   4   5   6   7   8   9---------------------------------------1|   1   2   3   4   5   6   7   8   92|   2   4   6   8  10  12  14  16  183|   3   6   9  12  15  18  21  24  274|   4   8  12  16  20  24  28  32  365|   5  10  15  20  25  30  35  40  456|   6  12  18  24  30  36  42  48  547|   7  14  21  28  35  42  49  56  638|   8  16  24  32  40  48  56  64  729|   9  18  27  36  45  54  63  72  81//TestSum.java 4-7 2021年03月28日 星期日 08时00分15秒 float sum = 0;for(float i = 0.01f; i <= 1.0f; i = i + 0.01f)sum += i;    System.out.println("The sum is " + sum);
wannian07@wannian07-PC:~/Desktop/Introduction to Java Programming$ java helloThe sum is 50.499985//4-8 GreatestCommonDivisor.java 2021年03月28日 星期日 08时03分15秒
//求最大公约数GCDScanner input = new Scanner(System.in);System.out.print("Enter first integer: ");int n1 = input.nextInt();System.out.print("Enter second integer: ");int n2 = input.nextInt();int gcd = 1;int k = 2;while(k <= n1 && k <= n2){if(n1 % k == 0 && n2 % k == 0)gcd = k;k++;}System.out.println("The greatest common divisor for " + n1 + " and " + n2 + " is " + gcd);//4.9 FutureTuition.java 2021年03月28日 星期日 08时26分18秒 double tuition = 10000;int year = 1;while(tuition < 20000){tuition = tuition * 1.07;year++;}System.out.println("Tuition will be doubled in "+ year + " years");
wannian07@wannian07-PC:~/Desktop/Introduction to Java Programming$ java helloTuition will be doubled in 12 years//4-10 MonteCarloSimulation.java 2021年03月28日 星期日 08时29分31秒 final int NUMBER_OF_TRIALS = 10000000;int numberOfHits = 0;for(int i = 0; i < NUMBER_OF_TRIALS; i++){double x = Math.random() * 2.0 - 1;double y = Math.random() * 2.0 - 1;if(x * x + y * y <= 1)numberOfHits++;}double pi = 4.0 * numberOfHits / NUMBER_OF_TRIALS;System.out.println("PI is " + pi);
wannian07@wannian07-PC:~/Desktop/Introduction to Java Programming$ java helloPI is 3.1413744
//TestBreak.java 4-11 p106 2021年03月30日 星期二 07时35分16秒
int sum = 0;
int number = 0;
while(number < 20){number++;sum += number;if(sum >= 100)break;
}
System.out.println("The number is "+ number);
System.out.println("The sum is " + sum);
wannian07@wannian07-PC:~/Desktop/Introduction to Java Programming$ java helloThe number is 14The sum is 105//TestContinue.java 4-12
int sum = 0;
int number = 0;
while(number < 20){number++;
//  if(number == 10 || number == 11)
//      continue;sum += number;
}
System.out.println("The sum is " + sum);
wannian07@wannian07-PC:~/Desktop/Introduction to Java Programming$ java helloThe sum is 189
wannian07@wannian07-PC:~/Desktop/Introduction to Java Programming$ java helloThe sum is 210(no if )//GuessNumberUsingBreak.java 4-13 2021年03月30日 星期二 07时40分19秒
int number = (int)(Math.random()* 101);
Scanner input = new Scanner(System.in);
System.out.println("Guess a magic number between 0 and 100");
while(true){System.out.print("\nEnter your guess: ");int guess = input.nextInt();if(guess == number){System.out.println("Yes, the number is "+ number);break;}else if(guess > number){System.out.println("Your geuss is too high");}elseSystem.out.println("Your guess is too low");     }

wannian07@wannian07-PC:~/Desktop/Introduction to Java Programming$ java hello
Guess a magic number between 0 and 100

Enter your guess: 60
Your geuss is too highEnter your guess: 30
Your geuss is too highEnter your guess: 15
Your geuss is too highEnter your guess: 6
Your geuss is too highEnter your guess: 3
Your geuss is too highEnter your guess: 1
Your guess is too lowEnter your guess: 2
Yes, the number is 2//PrimeNumber.java p4-14 2021年03月30日 星期二 07时48分37秒
final int NUMBER_OF_PRIMES = 50;
final int NUMBER_OF_PRIMES_PER_LINE = 10;
int count = 0;
int number = 2;
System.out.println("The first 50 prime numbers are \n");
while(count < NUMBER_OF_PRIMES){boolean isPrime = true;for(int divisor = 2; divisor <= number / 2; divisor++){if(number % divisor == 0){isPrime = false;break;}}
if(isPrime){count++;if(count % NUMBER_OF_PRIMES_PER_LINE == 0){System.out.println(number);}elseSystem.out.print(number + " ");}number++;}

wannian07@wannian07-PC:~/Desktop/Introduction to Java Programming$ java hello
The first 50 prime numbers are

2 3 5 7 11 13 17 19 23 29
31 37 41 43 47 53 59 61 67 71
73 79 83 89 97 101 103 107 109 113
127 131 137 139 149 151 157 163 167 173
179 181 191 193 197 199 211 223 227 229//SentinelValueUsingConfirmationDialog.java 4-15 2021年03月30日 星期二 07时55分05秒
int sum = 0;
int option = JOptionPane.YES_OPTION;
while(option == JOptionPane.YES_OPTION){String dataString = JOptionPane.showInputDialog("Enter an int value: ");
int data = Integer.parseInt(dataString);
sum += data;
option = JOptionPane.showConfirmDialog(null, "Continue?");
}
JOptionPane.showMessageDialog(null, "The sum is "+ sum);System.out.println("Sum from 1 to 10 is " + sum(1, 10));
System.out.println("Sum from 1 to 10 is " + sum(20, 30));
System.out.println("Sum from 1 to 10 is " + sum(35, 45));int i = 5;
int j = 2;
int k = max(i, j);
System.out.println("The maximum between " + i+ " and " + j + " is " + k);

}

//显示的是sum方法需要class,重新检查了一下,发现是class的大括号没有把sum方法包括起来
public static int sum(int i1, int i2){
int sum = 0;
for(int i = i1; i <= i2; i++)
sum += i;
return sum;
}

public static int max(int num1, int num2){
int result;
if(num1 > num2)
result = num1;
else
result = num2;
return result;
}
wannian07@wannian07-PC:~/Desktop/Introduction to Java Programming$ java hello
Sum from 1 to 10 is 55
Sum from 1 to 10 is 275
Sum from 1 to 10 is 440
The maximum between 5 and 2 is 5

//TestVoidMethod.java 5-2 2021年03月30日 星期二 19时29分21秒
System.out.print("The grade is ");
getGrade(78.5);
System.out.print("The grade is ");
getGrade(59.5);public static void getGrade(double score){if(score >= 90.0){System.out.println('A');}else if(score >= 80.0){System.out.println('B');}else if(score >= 70.0){System.out.println('C');}else if(score >= 60.0){System.out.println('D');}else {System.out.println('F');}
}System.out.print("The grade is "+ getGrade(78.5));
System.out.println("\nThe grade is "+ getGrade(59.5));
}public static char getGrade(double score){if(score >= 90.0)    return 'A';else if(score >= 80.0)return 'B';else if(score >= 70.0)return 'C';else if(score >= 60.0)return 'D';else return 'F';
}
wannian07@wannian07-PC:~/Desktop/Introduction to Java Programming$ java helloThe grade is CThe grade is F//Increment.java p5-4 2021年03月30日 星期二 19时51分49秒
int x = 1;
System.out.println("Before the call, x is " + x);
increment(x);
System.out.println("after the call, x is " + x);
}public static void increment(int n){n++;System.out.println("n inside the method is " + n);
}
wannian07@wannian07-PC:~/Desktop/Introduction to Java Programming$ java helloBefore the call, x is 1n inside the method is 2after the call, x is 1//TestPassByValue.java 5-5 2021年03月30日 星期二 19时54分52秒
int num1 = 1;
int num2 = 2;
System.out.println("Before invoking the swap method, num1 is " +num1 + " and num2 is " + num2);
swap(num1, num2);
System.out.println("After invoking the swap method, num1 is " +num1 + " and num2 is " + num2);
}public static void swap(int n1, int n2){System.out.println("\tInside the swap method");System.out.println("\t\tBefore swapping n1 is " + n1 +" n2 is " + n2);int temp = n1;n1 = n2;n2 = temp;System.out.println("\t\tAfter swapping n1 is " + n1 +" n2 is " + n2);
}
wannian07@wannian07-PC:~/Desktop/Introduction to Java Programming$ java helloBefore invoking the swap method, num1 is 1 and num2 is 2Inside the swap methodBefore swapping n1 is 1 n2 is 2After swapping n1 is 2 n2 is 1After invoking the swap method, num1 is 1 and num2 is 2

//5-6 p131 GreatestCommonDivisorMethod.java
Scanner input = new Scanner(System.in);
System.out.print("Enter first integer: ");
int n1 = input.nextInt();
System.out.print("Enter second integer: ");
int n2 = input.nextInt();
System.out.println("The greatest common divisor for "+ n1 +
" and " + n2 + " is " + gcd(n1, n2));
}
public static int gcd(int n1, int n2){
int gcd = 1;
int k = 2;
while (k <= n1 && k <= n2){
if(n1 % k == 0 && n2 % k == 0)
gcd = k;
k++;
}
return gcd;
}
wannian07@wannian07-PC:~/Desktop/Introduction to Java Programming$ java hello
Enter first integer: 45
Enter second integer: 75
The greatest common divisor for 45 and 75 is 15

//PrimeNumberMethod.java 2021年04月01日 星期四 13时38分30秒
System.out.println("The first 50 prime numbers are \n");
printPrimeNumbers(50);

}
public static void printPrimeNumbers(int numberOfPrimes){
final int NUMBER_OF_PRIMES_PER_LINE = 10;
int count = 0;
int number = 2;
while (count < numberOfPrimes){
if(isPrime(number)){
count++;
if(count % NUMBER_OF_PRIMES_PER_LINE == 0){
System.out.printf("%-5s\n", number);
}else
System.out.printf("%-5s", number);
}
number++;
}
}
public static boolean isPrime(int number){
for(int divisor = 2; divisor <= number / 2; divisor++){
if(number % divisor == 0){
return false;
}
}
return true;
wannian07@wannian07-PC:~/Desktop/Introduction to Java Programming$ java hello
The first 50 prime numbers are

 2    3    5    7    11   13   17   19   23   29   31   37   41   43   47   53   59   61   67   71   73   79   83   89   97   101  103  107  109  113  127  131  137  139  149  151  157  163  167  173  179  181  191  193  197  199  211  223  227  229  //5-8 Decimal2HexConversion.java p133  2021年04月01日 星期四 13时48分09秒
Scanner input = new Scanner(System.in);
System.out.print("Enter a decimal number: ");
int decimal = input.nextInt();
System.out.println("The hex number for decimal " + decimal + " is " + decimalToHex(decimal));
}
public static String decimalToHex(int decimal){String hex = "";while(decimal != 0){int hexValue = decimal % 16;hex = toHexChar(hexValue) + hex;decimal = decimal / 16;} return hex;
}
public static char toHexChar(int hexValue){if(hexValue <= 9 && hexValue >= 0)return (char)(hexValue + '0');elsereturn (char)(hexValue - 10 + 'A');
wannian07@wannian07-PC:~/Desktop/Introduction to Java Programming$ java helloEnter a decimal number: 1234The hex number for decimal 1234 is 4D2//5-9 TestMethodOverloading.java 2021年04月01日 星期四 13时58分43秒
System.out.println("The maximum between 3 and 4 is " + max(3, 4));
System.out.println("The maximum between 3.0 and 5.4 is " + max(3.0, 5.4));
System.out.println("The maximum between 3.0 and 5.4, and 10.14 is " + max(3.0, 5.4, 10.14));
}
public static int max(int num1, int num2){if(num1 > num2)return num1;elsereturn num2;
}
public static double max(double num1, double num2){if(num1 > num2)return num1;elsereturn num2;
}
public static double max(double num1, double num2, double num3){return max(max(num1, num2),num3);}
wannian07@wannian07-PC:~/Desktop/Introduction to Java Programming$ java helloThe maximum between 3 and 4 is 4The maximum between 3.0 and 5.4 is 5.4The maximum between 3.0 and 5.4, and 10.14 is 10.14
//bank.java P7     2021年04月01日 星期四 20时56分00秒
BankAccount ba1 = new BankAccount(100.00);
System.out.print("Before transactions, ");
ba1.display();
ba1.deposit(74.35);
ba1.withdraw(20.00);System.out.print("After transactions, ");
ba1.display();
}

// 错误: 无法从静态上下文中引用非静态 变量 this
// BankAccount ba1 = new BankAccount(100.00);
// class BankAccount{} 改成 public staic class BankAccount{}

public static  class BankAccount{private double balance;public BankAccount(double openingBalance){balance = openingBalance;}public void deposit(double amount){balance = balance + amount;}public void withdraw(double amount){balance = balance - amount;}public void display(){System.out.println("balance= " + balance);}
}wannian07@wannian07-PC:~/Desktop/Introduction to Java Programming$ java helloBefore transactions, balance= 100.0After transactions, balance= 154.35long[] arr;
arr = new long[100];
int nElems = 0;
int j;
long searchKey;
arr[0] = 77;
arr[1] = 99;
arr[2] = 44;
arr[3] = 55;
arr[4] = 22;
arr[5] = 88;
arr[6] = 11;
arr[7] = 00;
arr[8] = 66;
arr[9] = 33;
nElems = 10;for(j = 0; j < nElems; j++)System.out.print(arr[j] + " ");
System.out.println("");searchKey = 66;
for(j = 0; j < nElems; j++)if(arr[j] == searchKey)  break;if(j == nElems)System.out.println("Can't find " + searchKey);elseSystem.out.println("found " + searchKey);searchKey = 55;
for(j = 0; j < nElems; j++)if(arr[j] == searchKey)  break;
for(int k = j; k < nElems; k++)arr[k] = arr[k+1];   //后面的高位覆盖前面55的数字位置nElems--;for(j = 0; j < nElems; j++)System.out.print(arr[j] + " ");
System.out.println("");
}wannian07@wannian07-PC:~/Desktop/Introduction to Java Programming$ java hello77 99 44 55 22 88 11 0 66 33 found 6677 99 44 22 88 11 0 66 33 //2.2 lowArray.java
LowArray arr;
arr = new LowArray(100);
int nElems = 0;
int j;arr.setElem(0, 77);
arr.setElem(1, 99);
arr.setElem(2, 44);
arr.setElem(3, 55);
arr.setElem(4, 22);
arr.setElem(5, 88);
arr.setElem(6, 11);
arr.setElem(7, 00);
arr.setElem(8, 66);
arr.setElem(9, 33);
nElems = 10;for(j = 0; j < nElems; j++)System.out.print(arr.getElem(j) + " ");
System.out.println("");int searchKey = 26;
for(j = 0; j < nElems; j++)if(arr.getElem(j) == searchKey)  break;if(j == nElems)System.out.println("Can't find " + searchKey);elseSystem.out.println("found " + searchKey);searchKey = 55;
for(j = 0; j < nElems; j++)if(arr.getElem(j) == searchKey)  break;
for(int k = j; k < nElems; k++)arr.setElem(k, arr.getElem(k+1)); //后面的高位覆盖前面55的数字位置nElems--;for(j = 0; j < nElems; j++)System.out.print(arr.getElem(j) + " ");
System.out.println("");
}public static class LowArray{private long[] a;public LowArray(int size){a = new long[size];}public void setElem(int index, long value){a[index] = value;}public long getElem(int index){return a[index];}
}wannian07@wannian07-PC:~/Desktop/Introduction to Java Programming$ java hello77 99 44 55 22 88 11 0 66 33 Can't find 2677 99 44 22 88 11 0 66 33 //highArray.java 2-3 p28
int maxSize = 100;
HighArray arr;
arr = new HighArray(maxSize);arr.insert(77) ;
arr.insert(99) ;
arr.insert(44) ;
arr.insert(55) ;
arr.insert(22) ;
arr.insert(88) ;
arr.insert(11) ;
arr.insert(00) ;
arr.insert(66) ;
arr.insert(33) ;arr.display();int searchKey = 35;if(arr.find(searchKey))System.out.println("Can't find " + searchKey);elseSystem.out.println("found " + searchKey);arr.delete(00);
arr.delete(55);
arr.delete(99);
arr.display();

}

public static class HighArray{private long[] a;private int nElems;public HighArray(int max){a = new long[max];nElems = 0;      }public boolean find(long searchKey){int j;for(j = 0; j < nElems; j++)if(a[j] == searchKey) break;if(j == nElems) return false;elsereturn true;}public void insert(long value){a[nElems] = value;nElems++;}public boolean delete(long value){//vlaue 打错了int j;for(j = 0; j < nElems; j++)if( value == a[j])// a[j] 错打成了 arr[j]break;if(j == nElems)  return false;else{for(int k = j; k < nElems; k++)a[k] = a[k+1];nElems--;return true;}}public void display(){for(int j = 0; j < nElems; j++)System.out.print(a[j] + " ");System.out.println("");}
}wannian07@wannian07-PC:~/Desktop/Introduction to Java Programming$ java hello77 99 44 55 22 88 11 0 66 33 found 3577 44 22 88 11 66 33

//2.4 orderArray.java p36 2021年04月02日 星期五 20时53分48秒

int maxSize = 100;
OrdArray arr;
arr = new OrdArray(maxSize);arr.insert(77) ;
arr.insert(99) ;
arr.insert(44) ;
arr.insert(55) ;
arr.insert(22) ;
arr.insert(88) ;
arr.insert(11) ;
arr.insert(00) ;
arr.insert(66) ;
arr.insert(33) ;
int searchKey = 55;
if(arr.find(searchKey) != arr.size())System.out.println("Found " + searchKey);
elseSystem.out.println("Can't find " + searchKey);
arr.display();
arr.delete(00);
arr.delete(55);
arr.delete(99);
arr.display();

}

public static class OrdArray{private long[] a;private int nElems;public OrdArray(int max){a = new long[max];nElems = 0;}public int size(){return nElems;}public int find(long searchKey){int lowerBound = 0;int upperBound = nElems - 1;int curIn;while(true){curIn = (lowerBound + upperBound) / 2;if(a[curIn] == searchKey)return curIn;else if(lowerBound > upperBound)return nElems;else{if(a[curIn] < searchKey)lowerBound = curIn + 1;elseupperBound = curIn - 1;}}}public void insert(long value){int j;for(j = 0; j < nElems; j++)if(a[j] > value)break;for(int k = nElems; k > j; k--)a[k] = a[k-1];a[j] = value;nElems++;}public boolean delete(long value){int j = find(value);if(j == nElems)return false;else{for(int k = j; k < nElems; k++)a[k] = a[k+1];nElems--;return true;}}public void display(){for(int j = 0; j < nElems; j++)System.out.print(a[j] + " ");System.out.println("");}
}wannian07@wannian07-PC:~/Desktop/Introduction to Java Programming$ java helloFound 550 11 22 33 44 55 66 77 88 99 11 22 33 44 66 77 88 //classDataArray.java p42 2021年04月02日 星期五 21时09分40秒
int maxSize = 100;
ClassDataArray arr;
arr = new ClassDataArray(maxSize);
arr.insert("Evans", "Patty", 24);
arr.insert("Smith", "Lorraine", 37);
arr.insert("Yee", "Tom", 43);
arr.insert("Adams", "Henry", 63);
arr.insert("Hashimoto", "Sato", 21);
arr.insert("Stimso", "Henry", 29);
arr.insert("Velasquez", " Jose", 72);
arr.insert("Lamarque", "Henry", 54);
arr.insert("Vang", "Minh", 22);
arr.insert("Creswell", "Lucinda", 18);
arr.displayA();String searchKey = "Stimson";
Person found;
found = arr.find(searchKey);
if(found != null){System.out.print("Found ");found.displayPerson();
}elseSystem.out.println("Can't find " + searchKey);System.out.println("Deleting Smith, Yee,  and Creswell");
arr.delete("Smith");
arr.delete("Yee");
arr.delete("Creswell");arr.displayA();

}

public static class Person{private String lastName;private String firstName;private int age;public Person(String last, String first, int a){lastName = last;firstName = first;age = a;}public void displayPerson(){System.out.print("  Last name: " + lastName);System.out.print(",  First name: " + firstName);System.out.print(", Age: " + age);}public String getLast(){return lastName;}
}public static class ClassDataArray{private Person[] a;private int nElems;public ClassDataArray(int max){a = new Person[max];nElems = 0;}public Person find(String searchName){int j ;for(j = 0; j < nElems; j++)if(a[j].getLast().equals(searchName))break;if(j == nElems)return null;elsereturn a[j];}public void insert(String last, String first, int age){a[nElems] = new Person(last, first, age);nElems++;} public boolean delete(String searchName){int j;for(j = 0; j < nElems; j++)if(a[j].getLast().equals(searchName))break;if(j == nElems)return false;else{for(int k = j; k < nElems; k++)a[k] = a[k+1];nElems--;return true;}}public void displayA(){for(int j = 0; j < nElems; j++){a[j].displayPerson();                }}}wannian07@wannian07-PC:~/Desktop/Introduction to Java Programming$ java hello

Last name: Evans First name: Patty, Age: 24
Last name: Smith First name: Lorraine, Age: 37
Last name: Yee First name: Tom, Age: 43
Last name: Adams First name: Henry, Age: 63
Last name: Hashimoto First name: Sato, Age: 21
Last name: Stimso First name: Henry, Age: 29
Last name: Velasquez First name: Jose, Age: 72
Last name: Lamarque First name: Henry, Age: 54
Last name: Vang First name: Minh, Age: 22
Last name: Creswell First name: Lucinda, Age: 18
Can’t find Stimson
Deleting Smith, Yee, and Creswell
Last name: Evans First name: Patty, Age: 24
Last name: Adams First name: Henry, Age: 63
Last name: Hashimoto First name: Sato, Age: 21
Last name: Stimso First name: Henry, Age: 29
Last name: Velasquez First name:
//3.1 p57 bubbleSort.java 2021年04月02日 星期五 21时48分21秒
int maxSize = 100;
ArrayBub arr;
arr = new ArrayBub(maxSize);

arr.insert(77) ;
arr.insert(99) ;
arr.insert(44) ;
arr.insert(55) ;
arr.insert(22) ;
arr.insert(88) ;
arr.insert(11) ;
arr.insert(00) ;
arr.insert(66) ;
arr.insert(33) ;
arr.display();
arr.bubbleSort();
arr.display();

}

public static class ArrayBub{private long[] a;private int nElems;public ArrayBub(int max){a = new long[max];nElems = 0;}public void insert(long value){a[nElems] = value;nElems++;}public void display(){for(int j = 0; j < nElems; j++)System.out.print(a[j] + " ");System.out.println("");}public void bubbleSort(){int out, in;for(out = nElems-1; out > 1; out--)for(in = 0; in < out; in++)if(a[in] > a[in + 1])swap(in, in+1);}private void swap(int one, int two){long temp = a[one];a[one] = a[two];    a[two] = temp;}
}wannian07@wannian07-PC:~/Desktop/Introduction to Java Programming$ java hello77 99 44 55 22 88 11 0 66 33 0 11 22 33 44 55 66 77 88 99
//RandomCharacter.java 2021年04月03日 星期六 07时47分53秒 p140final int NUMBER_OF_CHARS = 175;final int CHARS_PER_LINE = 25;for(int i = 0; i < NUMBER_OF_CHARS; i++){char ch = RandomCharacter.getRandomLowerCaseLetter();if((i+1)% CHARS_PER_LINE == 0)System.out.println(ch);elseSystem.out.print(ch);}
}    //漏了 }public static class RandomCharacter{  // 少打了 public staticpublic static char getRandomCharacter(char ch1, char ch2){return(char)(ch1 + Math.random() * (ch2 - ch1 + 1));}public static char getRandomLowerCaseLetter(){return getRandomCharacter('a', 'z');}public static char getRandomUpperCaseLetter(){return getRandomCharacter('A', 'Z');}public static char getRandomDigitCharacter(){return getRandomCharacter('0', '9');}public static char getRandomCharacter(){return getRandomCharacter('\u0000', '\uFFFF');}
}wannian07@wannian07-PC:~/Desktop/Introduction to Java Programming$ java hellopajapbgtjkwafwnkwejgvlxpkofqjuvritdarqgdzeqzvwruaaqquvexmcqlwwoymlvuipsxhjwiivoqipzinxtghxkizvrxfjmtfrgfifxbrdvrlpbyjyhqgcgxfpwmsvjdvdhjhtfvfdqlttprzkmrznyqoopnssyxptmsreqzzqoScanner input = new Scanner(System.in);
System.out.print("Enter full year (e.g.,2001): ");
int year = input.nextInt();
System.out.print("Enter month as number between 1 and 12: ");
int month = input.nextInt();
printMonth(year, month);
}public static void printMonth(int year, int month){System.out.print(month + " " + year);
}
public static void printMonthBody(int year, int month){}
public static String getMonthName(int month){return "January";
}
public static int getTotalNumberOfDays(int year, int month){return 10000;
}
public static int getNumberOfDaysInMonth(int year, int month){return 31;
}
public static boolean isLeapYear(int year){return true;
}wannian07@wannian07-PC:~/Desktop/Introduction to Java Programming$ java helloEnter full year (e.g.,2001): 2020Enter month as number between 1 and 12: 44 2020//PrintCalendar.java p144 2021年04月03日 星期六 08时17分07秒
Scanner input = new Scanner(System.in);
System.out.print("Enter full year (e.g.,2001): ");
int year = input.nextInt();
System.out.print("Enter month as number between 1 and 12: ");
int month = input.nextInt();
printMonth(year, month);
}public static void printMonth(int year, int month){printMonthTitle(year, month);printMonthBody(year, month);
}
public static void printMonthTitle(int year, int month){System.out.println("   "+ getMonthName(month) + " " + year);System.out.println("-----------------------------");System.out.println(" Sun Mon Tue Wed Thu Fri Sat ");
}
public static String getMonthName(int month){String monthName = " ";switch(month){case 1 : monthName = "January"; break;  case 2 : monthName = "February"; break;case 3 : monthName = "March"; break;   case 4 : monthName = "April"; break;case 5 : monthName = "May"; break;    case 6 : monthName = "June"; break;case 7 : monthName = "July"; break;    case 8 : monthName = "August"; break;case 9 : monthName = "September"; break; case 10: monthName = "October"; break;case 11: monthName = "November"; break; case 12: monthName = "December"; }return monthName;
}
public static void printMonthBody(int year, int month){int startDay = getStartDay(year, month);int numberOfDaysInMonth = getNumberOfDaysInMonth(year, month);int i = 0;for(i = 0; i < startDay; i++)System.out.print("  ");for(i = 1; i <= numberOfDaysInMonth; i++){System.out.printf("%4d", i);//printf  打错了 printif((i + startDay) % 7 == 0)System.out.println();}System.out.println();
}
public static int getStartDay(int year, int month){final int START_DAY_FOR_JAN_1_1800 = 3;int totalNumberOfDays = getTotalNumberOfDays(year, month);return (totalNumberOfDays + START_DAY_FOR_JAN_1_1800) % 7;
}
public static int getTotalNumberOfDays(int year, int month){int total = 0;for(int i = 1800; i < year; i++)if(isLeapYear(i))total = total + 366;elsetotal = total + 365;for(int i = 1; i < month; i++)total = total + getNumberOfDaysInMonth(year, i);return total;
}
public static int getNumberOfDaysInMonth(int year, int month){if(month == 1 || month == 3 || month == 5 || month == 7 ||month == 8 || month == 10 || month == 12)return 31;if(month == 4 || month == 6 || month == 9 || month == 11)return 30;if(month == 2) return isLeapYear(year) ? 29 : 28;return 0;
}
public static boolean isLeapYear(int year){return year % 400 == 0 || (year % 4 == 0 && year % 100 != 0);
}wannian07@wannian07-PC:~/Desktop/Introduction to Java Programming$ java helloEnter full year (e.g.,2001): 2021Enter month as number between 1 and 12: 4April 2021-----------------------------Sun Mon Tue Wed Thu Fri Sat 1   2   34   5   6   7   8   9  1011  12  13  14  15  16  1718  19  20  21  22  23  2425  26  27  28  29  30

//3.2 p63 selectSort.java 2021年04月03日 星期六 18时10分07秒
int maxSize = 100;
ArraySel arr;
arr = new ArraySel(maxSize);

arr.insert(77) ;
arr.insert(99) ;
arr.insert(44) ;
arr.insert(55) ;
arr.insert(22) ;
arr.insert(88) ;
arr.insert(11) ;
arr.insert(00) ;
arr.insert(66) ;
arr.insert(33) ;
arr.display();
arr.selectionSort();
arr.display();

}
public static class ArraySel{
private long[] a;
private int nElems;

 public ArraySel(int max){a = new long[max];nElems = 0;}public void insert(long value){a[nElems] = value;nElems++;}public void display(){for(int j = 0; j < nElems; j++)System.out.print(a[j] + " ");System.out.println("");}public void selectionSort(){int out, in, min;for(out = 0; out < nElems - 1; out++){min = out;for(in = out + 1; in <nElems; in++)if(a[in] < a[min])min = in;swap(out, min);}}private void swap(int one, int two){long temp = a[one];a[one] = a[two];a[two] = temp;}}wannian07@wannian07-PC:~/Desktop/Introduction to Java Programming$ java hello77 99 44 55 22 88 11 0 66 33 0 11 22 33 44 55 66 77 88 99

//3.3 p70 insertSort.java 2021年04月03日 星期六 19时16分52秒
int maxSize = 100;
ArrayIns arr;
arr = new ArrayIns(maxSize);

arr.insert(77) ;
arr.insert(99) ;
arr.insert(44) ;
arr.insert(55) ;
arr.insert(22) ;
arr.insert(88) ;
arr.insert(11) ;
arr.insert(00) ;
arr.insert(66) ;
arr.insert(33) ;
arr.display();
arr.insertionSort();
arr.display();

}
public static class ArrayIns{
private long[] a;
private int nElems;

 public ArrayIns(int max){a = new long[max];nElems = 0;}public void insert(long value){a[nElems] = value;nElems++;}public void display(){for(int j = 0; j < nElems; j++)System.out.print(a[j] + " ");System.out.println("");}public void insertionSort(){int in, out;for(out = 1; out < nElems; out++){long temp = a[out];in = out;while(in > 0 && a[in -1] >= temp){a[in] = a[in - 1];--in;}a[in] = temp;}}
}wannian07@wannian07-PC:~/Desktop/Introduction to Java Programming$ java hello77 99 44 55 22 88 11 0 66 33 0 11 22 33 44 55 66 77 88 99 //objectSort.java p72 2021年04月03日 星期六 19时33分40秒
int maxSize = 100;
ArrayInOb arr;
arr = new ArrayInOb(maxSize);
arr.insert("Evans", "Patty", 24);
arr.insert("Smith", "Doc", 59);
arr.insert("Smith", "Lorraine", 37);
arr.insert("Smith", "Paul", 37);
arr.insert("Yee", "Tom", 43);
arr.insert("Adams", "Henry", 63);
arr.insert("Hashimoto", "Sato", 21);
arr.insert("Stimso", "Henry", 29);
arr.insert("Velasquez", " Jose", 72);
arr.insert("Lamarque", "Henry", 54);
arr.insert("Vang", "Minh", 22);
arr.insert("Creswell", "Lucinda", 18);
System.out.println("Before sorting: ");
arr.display();
arr.insertionSort();System.out.println("After sorting:");
arr.display();
}public static class Person{private String lastName;private String firstName;private int age;public Person(String last, String first, int a){lastName = last;firstName = first;age = a;}public void displayPerson(){System.out.print("  Last name: " + lastName);System.out.print(",  First name: " + firstName);System.out.print(",  Age: " + age);}public String getLast(){return lastName;}
}
public static class ArrayInOb{private Person[] a;private int nElems;public ArrayInOb(int max){a = new Person[max];nElems = 0;}public void insert(String last, String first, int age){a[nElems] = new Person(last, first, age);nElems++;}public void display(){for(int j = 0; j < nElems; j++)a[j].displayPerson();System.out.println("");}public void insertionSort(){int in, out;for(out = 1; out < nElems; out++){Person temp = a[out];in = out;while(in > 0 && a[in-1].getLast().compareTo(temp.getLast())>0){a[in] = a[in - 1];--in;}a[in] = temp;}}
}wannian07@wannian07-PC:~/Desktop/Introduction to Java Programming$ java hello

Before sorting:
Last name: Evans, First name: Patty, Age: 24
Last name: Smith, First name: Doc, Age: 59
Last name: Smith, First name: Lorraine, Age: 37
Last name: Smith, First name: Paul, Age: 37
Last name: Yee, First name: Tom, Age: 43
Last name: Adams, First name: Henry, Age: 63
Last name: Hashimoto, First name: Sato, Age: 21
Last name: Stimso, First name: Henry, Age: 29
Last name: Velasquez, First name: Jose, Age: 72
Last name: Lamarque, First name: Henry, Age: 54
Last name: Vang, First name: Minh, Age: 22
Last name: Creswell, First name: Lucinda, Age: 18
After sorting:
Last name: Adams, First name: Henry, Age: 63
Last name: Creswell, First name: Lucinda, Age: 18
Last name: Evans, First name: Patty, Age: 24
Last name: Hashimoto, First name: Sato, Age: 21
Last name: Lamarque, First name: Henry, Age: 54
Last name: Smith, First name: Doc, Age: 59
Last name: Smith, First name: Lorraine, Age: 37
Last name: Smith, First name: Paul, Age: 37
Last name: Stimso, First name: Henry, Age: 29
Last name: Vang, First name: Minh, Age: 22
Last name: Velasquez, First name: Jose, Age: 72
Last name: Yee, First name: Tom, Age: 43

//stack.java p84 2021年04月03日 星期六 19时35分00秒
StackX theStack = new StackX(10);
theStack.push(20);
theStack.push(40);
theStack.push(60);
theStack.push(80);while(!theStack.isEmpty()){long value = theStack.pop();System.out.print(value);System.out.print(" ");
}
System.out.println(" ");

}

public static class StackX{private int maxSize;private long[] stackArray;private int top;public StackX(int s){maxSize = s;stackArray = new long[maxSize];top = -1;    }public void push(long j){stackArray[++top] = j;}public long pop(){  // long 型 错误打成void 型return stackArray[top--];}public long peek(){return stackArray[top];}public boolean isEmpty(){return (top == -1);}public boolean isFull(){return (top == maxSize - 1);      }
}wannian07@wannian07-PC:~/Desktop/Introduction to Java Programming$ java hello80 60 40 20  //4-2 reverse.java p87 2021年04月03日 星期六 19时46分35秒
String input, output;
while(true){System.out.print("Enter a string: ");System.out.flush();input = getString();if(input.equals(""))break;Reverser theReverser = new Reverser(input);
output = theReverser.doRev();
System.out.println("Reversed: " + output);
}

}
public static String getString() throws IOException{
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
String s = br.readLine();
return s;
}

public static class StackX{private int maxSize;private char[] stackArray;private int top;public StackX(int max){maxSize = max;stackArray = new char[maxSize];top = -1;    }public void push(char j){stackArray[++top] = j;}public char pop(){  // long 型 错误打成void 型return stackArray[top--];}public char peek(){return stackArray[top];}public boolean isEmpty(){return (top == -1);}public boolean isFull(){return (top == maxSize - 1);      }
}public static class Reverser{private String input;private String output;public Reverser(String in){input = in;}public String doRev(){int stackSize = input.length();StackX theStack = new StackX(stackSize);for(int j = 0; j < input.length(); j++){char ch = input.charAt(j);theStack.push(ch);}        output = " ";while(!theStack.isEmpty()){char ch = theStack.pop();output = output + ch;}return output;}
}wannian07@wannian07-PC:~/Desktop/Introduction to Java Programming$ java helloEnter a string: partReversed:  trapEnter a string: I love JavaReversed:  avaJ evol I//错误: 未报告的异常错误IOException; 必须对其进行捕获或声明以便抛出  input = getString();//在Java中,根据错误性质将运行错误分为两类:错误和异常。//在Java程序的执行过程中,如果出现了异常事件,就会生成一个异常对象。生成的异常对象将传递Java运行时系统,//这一异常的产生和提交过程称为抛弃(throw)异常。当Java运行时系统得到一个异常对象时,//它将会沿着方法的调用栈逐层回溯,寻找处理这一异常的代码。找到能够处理这类异常的方法后,//运行时系统把当前异常对象交给这个方法进行处理,这一过程称为捕获(catch)异常。//       https://blog.csdn.net/qq_37423198/article/details/68922379// 解决:1     即在main函数的后面加入throws Exception的异常捕获//      2   利用try,catch

*/
}

板凳——————————————————(昏鸦)Introduction to Java Programming相关推荐

  1. Java Programming Test Question 3

    import java.util.HashSet;public class JPTQuestion3 {public static void main(String[] args) {HashSet ...

  2. Java Programming Test Question 2

    public class JPTQuestion2 {public static void main(String[] args) {String s3 = "JournalDev" ...

  3. CSCI 1300 Introduction to Computer Programming

    CSCI 1300作业代做.代写TA/CA留学生作业.代做C/C++程序作业.C/C++课程设计作业代写 CSCI 1300 Introduction to Computer Programming ...

  4. ZUCC_Object Oriented Programming_Lab01 Introduction to Java

    感谢LDingHui同学提供的代码 Lab Report 01 Note: All your lab reports should be uploaded to BB before the deadl ...

  5. [Java in NetBeans] Lesson 01. Java Programming Basics

    这个课程的参考视频在youtube. 主要学到的知识点有: Create new project, choose Java Application. one .jar file/ package(.j ...

  6. Fast Intro To Java Programming (2)

    Java局部变量 局部变量声明在方法.构造方法或者语句块中: 局部变量在方法.构造方法.或者语句块被执行的时候创建,当它们执行完成后,变量将会被销毁: 访问修饰符不能用于局部变量: 局部变量只在声明它 ...

  7. 魔鬼细节之Java Programming

    1. 实体类的序列化 如果这个实体类要与实际网络进行交互,要实现Serializable接口 2. 在测试Web项目前,先把其他修改过的Java项目intall下,如pojo类,interface 3 ...

  8. Java性能 - Java Programming Guidelines

    这一部分包含了Java编码和性能方面的问题, 这个guidelines不是专门针对应用服务器的,但这是一些在很多情况下的偶通用的规则,如需了解Java coding最佳实践的完整分析探讨,请参考 Ja ...

  9. 【软件构造】实验笔记(一)Lab1-Fundamental Java Programming and Testing

    一.前言 <软件构造>课程是我校根据MIT.CMU等计算机领域名校的相关课程近年来开展的软件开发相关的课程.课程的实验和课件都很大程度上参考了上述学校. 本笔记对在课程实验练习进行中遇到的 ...

最新文章

  1. python pytest allure_python-pytest-Allure2测试报告生成
  2. 分区表在安装系统(MBR)丢失或损坏
  3. python word排版_使用Python通过win32 COM实现Word文档的写入与保存方法
  4. 【转】Go 语言教程(2)——表达式
  5. 超级计算机预测降雪,南方九省即将大雪纷飞?超级计算机:可能性增加,但还没有确定...
  6. 项目管理过程中的一些注意事项
  7. Web Storage中的sessionStorage和localStorage
  8. 常见排序算法的时间复杂度
  9. Javascript学习总结 - JS基础系列 二
  10. python判断正数负数_python判断正负数方式
  11. VMWAre+centeros7下tomcat的安装
  12. 深入Asyncio(八)异步迭代器
  13. bzoj 1622: [Usaco2008 Open]Word Power 名字的能量
  14. basename 从绝对路径中取得文件名
  15. 西门子dcs系统组态手册下载_PLC/DCS/HMI 知识普及
  16. 有限元基础(一) Jacobian 矩阵和高斯积分
  17. 调用百度API,文字转语音
  18. HTML怎么消除链接下划线,HTML怎么去掉超链接的下划线
  19. Java基础算法,获得相反数
  20. 背景图片,banner图片随屏幕大小变化而变化

热门文章

  1. 如何进行ocr表格识别?简单的识别方法来啦
  2. 十进制与二进制的数位关系
  3. python 使用 selenium 爬取中国福利彩票双色球历史中奖号码
  4. 韩国烧脑片力荐,错过一眼都可能会是遗憾
  5. android下的即时通信autobahn
  6. 如何生活而不是活着?
  7. 幻霄科技CTO高天寒:创新教育体验—探索AIGC在元宇宙教学实训中的无限潜能|量子位·视点分享回顾...
  8. 炙手可热的区块链落地金融,是行之将至还是渐行渐远?
  9. 2022高压电工上岗证题目及答案
  10. DCF Plus:拥抱数字经济,用科技创造美好未来