03-选择
-
3.1 引言
- 程序可以基于条件决定执行哪些语句。
-
3.2 boolean数据类型
- boolean数据类型声明一个具有true或者flase的变量。
- 相等的关系操作符是两个等号(==),而不是一个等号(=),比较的结果是一个布尔值:true或flase。true和flase都是字面值,他们被当做保留字一样,不能用作程序的标识符.
操作符 名称 < 小于 <= 小于等于 > 大于 >= 大于等于 == 等于 != 不等于
- 3.3 if语句
- if语句是一个构造,允许程序确定执行的可选路径。
- Java中有几种类型的选择语句:单分支if语句、双分支if-else语句、嵌套if语句、多分支if-else语句、switch语句和条件操作符。
- 单分支if语句是指当且仅当条件为true是执行的一个动作。单分支if语句的语法是:
```java
if(布尔表达式){
语句(组);
}
```

- 示例:
- 提示用户输入一个整数。如果该数字是5的倍数,打印HiFive。如果该数字能被2整除,打印HiEven。
```java
package chapter03;
import java.util.Scanner;
public class SimpleIfDemo {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer: ");
int number = input.nextInt();
if (number % 5 ==0)
System.out.println("HiFive");
if (number % 2 ==0)
System.out.println("HiEven");
}
}
```
- 3.4 双分支 if-else 语句
- if-else语句根据条件是真或者是假,决定执行的路径。下面是双分支if-else语句的语法:
```java
if(布尔表达式){
布尔表达式为真时执行的语句(组);
}
else{
布尔表达式为假时执行的语句(组);
}
```

- 3.5 嵌套的if语句和多分支if-else语句
- if语句可以在另外一个if语句中,形成嵌套的if语句。
```java
if (i > k){
if (j > k)
System.out.println("i and j are greater than k");
}
else
System.out.println("i is less than or equal to k");
```
- 3.6 常见错误和陷进
- 常见错误1:忘记必要的括号
- 常见错误2:错误地在if行出现分号
- 常见错误3:对布尔值的冗余测试
- 常见错误4:悬空else出现的歧义(每一组if-else都要进行相应的缩进进行对齐,避免造成if-else不匹配的现象)
- 常见错误5:两个浮点数值的相等测试
- 常见陷阱1:简化布尔变量赋值
```java
if (number % 2 == 0)
even = true;
else
even = false;
//上面的代码就等价于下面的代码,但是 下面的代码形式会更加的好
boolean even
= number % 2 ==0;
```
- 常见陷阱2:避免不同情形中的重复代码
```java
package chapter01;
public class Try {
public static void main(String[] args){
int tuition;
boolean inState = true;
if (inState){
tuition = 5000;
System.out.println("The tuition is " + tuition);
}
else {
tuition = 15000;
System.out.println("The tuition is " + tuition);
}
//上面的代码等价于下面的代码,但是下面的代码的形式会更加的好,显得更加的简捷
if (inState){
tuition = 5000;
}
else {
tuition = 15000;
}
System.out.println("The tuition is " + tuition);
}
}
```
- 3.7 产生随机数
- 使用Math.random()来获得一个0.0到1.0之间的随机double值,不包括1.0。
- 示例:假设你想开发一个让一年级学生练习减法的程序。程序随机生成两个一位整数:number1,number2,且满足number1>=number2。程序向学生显示问题,例如,“What is 9-2?”。当学生输入答案之后,程序会显示一个消息表明改答案是否正确。
```java
package chapter03;
import java.util.Scanner;
public class SubtractionQuiz {
public static void main(String[] args){
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!");
else {
System.out.println("Your answer is wrong.");
System.out.println(number1 + "-" + number2 + " should be " + (number1 - number2));
}
}
}
```
-
3.8 示例学习:计算身体质量指数
package chapter03; import java.util.Scanner; public class ComputeAndInterpretBMI { public static void main(String[] args){ 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("BMI is " + bmi); if (bmi < 18.5) System.out.print("Underweight"); else if (bmi < 25) System.out.println("Normal"); else if (bmi < 30) System.out.println("Overweight"); else System.out.println("Obese"); } }
-
3.9 示例学习:计算税率
package chapter03; import java.util.Scanner; public class ComputeTax { public static void main(String[] args){ Scanner input = new Scanner(System.in); System.out.print("(0-single filer,1-married jointly or " + "qualifying window(er),2-married separately,3-head of " + "household) 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.22; else tax = 8350 * 0.10 + (33950 - 8350) * 0.15 + (82250 - 33950) * 0.25 + (171550 - 82250) * 0.28 + (372950 - 171550) * 0.22 + (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(1); } System.out.println("Tax is " + (int)(tax * 100) / 100.0); } }
-
3.10 逻辑操作符
- 逻辑操作符!、&&、||和^可以用于产生复合布尔表达式。
操作符 名称 说明 ! 非 逻辑非 && 与 逻辑与 | 或 逻辑或 ^ 异或 逻辑异或
```java
package chapter03;
import java.util.Scanner;
public class TestBooleanOperators {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer: ");
int number = input.nextInt();
if (number % 2 == 0 && number % 3 == 0)
System.out.println(number + "is divisible by 2 and 3.");
if (number % 2 == 0 || number % 3 == 0)
System.out.println(number + "is divisible by 2 or 3.");
if (number % 2 == 0 ^ number % 3 == 0)
System.out.println(number + "is divisible by 2 or 3,but not both.");
}
}
```
- 从数学的角度看,1<=2<=3是正确的,但是在Java中必须将两个部分分开的,1<=2&&2<=3。
-
3.11 示例学习:判定闰年
package chapter03; import java.util.Scanner; public class LeapYear { public static void main(String[] args){ 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); } }
-
3.12 示例学习:彩票
package chapter03; import java.util.Scanner; public class Lottery { public static void main(String[] args){ 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 $3,000"); else if (guessDigit1 == lotteryDigit1 || guessDigit1 == lotteryDigit2 || guessDigit2 == lotteryDigit1 || guessDigit2 == lotteryDigit2) System.out.println("Match one digit: you win $1,000"); else System.out.println("Sorry, no match"); } }
-
3.13 switch语句
- switch语句基于变量或者表达式的值来执行语句,下面是switch语句的完整语句。
```java
switch(switch表达式){
case 值1:语句(组)1;
break;
case 值2:语句(组)2;
break;
...
case 值N:语句(组)N;
break;
default:默认情况下执行的语句(组)
}
```
- switch语句遵从下述规则:
- 1、switch表达式必须是能计算出一个char、byte、short、int或者String型值,并且需用括号括主。
- 2、value1,value2,...,valueN必须与swtch表达式具有相同的数据类型。注意:value1,value2,...,valueN都是常量表达式,也就是说这里的表达式是不能包含变量的,例如,不允许出现1+x。
- 3、当switch表达式的值与case语句的值相匹配时,执行从case开始的语句,直到遇到一个break语句或到达该switch语句的结束。
- 4、默认情况下(default)是可选的,当没有一个给出的case与switch表达式匹配时,则执行该操作。
- 5、关键字break是可选的。break语句会立即终止switch语句。
```java
package chapter03;
import java.util.Scanner;
public class ChineseZodiac {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.print("Enter a year: ");
int year = input.nextInt();
switch (year % 12){
case 0:System.out.println("monkey");break;
case 1:System.out.println("rooster");break;
case 2:System.out.println("dog");break;
case 3:System.out.println("pig");break;
case 4:System.out.println("rat");break;
case 5:System.out.println("ox");break;
case 6:System.out.println("tiger");break;
case 7:System.out.println("rabbit");break;
case 8:System.out.println("dragon");break;
case 9:System.out.println("snake");break;
case 10:System.out.println("horse");break;
case 11:System.out.println("sheep");break;
}
}
}
```
- 不要忘记在需要的时候使用break语句。一旦匹配其中一个case,就从匹配的case处开始执行, 遇到break语句或者到达switch语句的结束。这种现象称为落空行为。
- 3.14 条件操作
- 符号?和:一起出现,称为条件操作符(也称为三元操作符,是Java中唯一的一个三元操作符)该语法如下:
```java
boolean-expression?expression1:expression2
```
```java
if(x>0)
y=1;
else
y=-1;
```
和下面的三元操作符是等价的:
```java
y=(x>0)?1:-1;
```
-
3.15 操作符的优先级和结合规则
在这里插入图片描述 -
3.16 调试
- 调试是在程序中找到和修改错误的过程。
- 1、一次执行一条语句
- 2、跟踪进入或者一步运行一个方法
- 3、设置断点
- 4、显示变量
- 5、显示调用堆栈
- 6、修改变量
-
编程小习题
-
1、在这里插入图片描述
package chapter03; import java.util.Scanner; public class Code_01 { public static void main(String[] args){ Scanner input = new Scanner(System.in); System.out.print("Enter a,b,c: "); double a = input.nextDouble(); double b = input.nextDouble(); double c = input.nextDouble(); double discriminant = b * b - 4 * a * c; if (discriminant > 0){ double answer1 = (-b + Math.pow(discriminant,0.5)) / (2 * a); double answer2 = (-b - Math.pow(discriminant,0.5)) / (2 * a); System.out.println("The equation has two roots " + answer1 + " and " + answer2); } else if (discriminant == 0){ double answer1 = (-b + Math.pow(discriminant,0.5)) / (2 * a); System.out.println("The eqution has one root " + answer1); } else System.out.println("The eqution has no real roots"); } }
-
2、在这里插入图片描述
-
1、
```java
package chapter03;
import java.util.Scanner;
public class Code_03 {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.print("Enter a,b,c,d,e,f: ");
double a = input.nextDouble();
double b = input.nextDouble();
double c = input.nextDouble();
double d = input.nextDouble();
double e = input.nextDouble();
double f = input.nextDouble();
double medius = a * d - b * c;
if (medius == 0){
System.out.println("The eqution has no solution");
}
else{
double x = (e * d - b * f) / medius;
double y = (a * f - e * c) / medius;
System.out.println("x is " + x + " and y is " + y);
}
}
}
```
- 3、
```java
package chapter03;
import java.util.Random;
public class Code_04 {
public static void main(String[] args){
Random r = new Random();
int month = r.nextInt(12) + 1;
switch (month){
case 1:System.out.println("January");break;
case 2:System.out.println("Febrary");break;
case 3:System.out.println("March");break;
case 4:System.out.println("April");break;
case 5:System.out.println("May");break;
case 6:System.out.println("June");break;
case 7:System.out.println("July");break;
case 8:System.out.println("August");break;
case 9:System.out.println("September");break;
case 10:System.out.println("October");break;
case 11:System.out.println("November");break;
case 12:System.out.println("December");break;
}
}
}
```
- 4、
```java
package chapter03;
import java.util.Scanner;
public class Code_05 {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.print("Enter today's day: ");
int number1 = input.nextInt();
System.out.print("Enter the number of days elapsed since today: ");
int number2 = input.nextInt();
System.out.print("Today is ");
method(number1);
System.out.print(" and the future day is ");
method(number2);
}
static void method(int n){
switch (n){
case 0:System.out.print("Sunday");break;
case 1:System.out.print("Monday");break;
case 2:System.out.print("Tuesday");break;
case 3:System.out.print("Wednesday");break;
case 4:System.out.print("Thursday");break;
case 5:System.out.print("Friday");break;
case 6:System.out.print("Saturday");break;
}
}
}
```
- 5、[图片上传失败...(image-b8f19-1601914568733)]
```java
package chapter03;
import java.util.Arrays;
import java.util.Scanner;
public class Code_08 {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.print("Enter three number(int): ");
int a = input.nextInt();
int b = input.nextInt();
int c = input.nextInt();
int[] arr = {a,b,c};
Arrays.sort(arr);
for(int i = 0; i < arr.length; i++){
System.out.print(arr[i]+" ");
}
}
}
```
- 6、
```java
package chapter03;
public class Code_09 {
public static void main(String[] args){
java.util.Scanner input = new java.util.Scanner(System.in);
System.out.print("Enter the first 9 digits of an ISBN as integer: ");
int first9Digits = input.nextInt();
int d9 = first9Digits %10;
int d8 = first9Digits /10 % 10;
int d7 = first9Digits /100 % 10;
int d6 = first9Digits /1000 % 10;
int d5 = first9Digits /10000 % 10;
int d4 = first9Digits /100000 % 10;
int d3 = first9Digits /1000000 % 10;
int d2 = first9Digits /10000000 % 10;
int d1 = first9Digits /100000000;
int d10 = (int)((d1 *1 + d2 * 2 + d3 * 3 + d4 * 4 + d5 * 5 + d6 * 6 + d7 * 7 + d8 * 8 + d9 * 9)%11);
if(d10 == 10)
System.out.println("The ISBN-10 number is " +first9Digits+"X");
else
System.out.println("The ISBN-10 number is " +first9Digits+d10);
}
}
```
- 7、[图片上传失败...(image-7c0eb1-1601914568733)]
```java
package chapter03;
import java.util.Random;
import java.util.Scanner;
public class Code_10 {
public static void main(String[] args){
Random r1 = new Random();
int one = r1.nextInt(100);
int two = r1.nextInt(100);
System.out.print(one + " - " + two + " = ");
Scanner input = new Scanner(System.in);
int answer = input.nextInt();
if (answer == one - two)
System.out.println("You are right!");
else
System.out.println("You are wrong!");
}
}
```
- 8、
```java
package chapter03;
import java.util.Scanner;
public class Code_12 {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.print("Enter a three-digits integer: ");
String str1 = input.nextLine();
String str2 = "";
for (int i = str1.length() - 1;i >= 0;i--){
str2 += str1.charAt(i);
}
if (str1.equals(str2))
System.out.println(str1 + " is a palindrome");
else
System.out.println(str1 + " is not a palindrome");
}
}
```
- 9、[图片上传失败...(image-c9e8f5-1601914568734)]
```java
package chapter03;
import java.util.Arrays;
import java.util.Scanner;
public class Code_19 {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.print("Enter three integers: ");
int a = input.nextInt();
int b = input.nextInt();
int c = input.nextInt();
int[] arr = {a,b,c};
Arrays.sort(arr);
if (arr[0] + arr[1] > arr[2])
System.out.println("legitimate");
else
System.out.println("not legitimate");
}
}
```
- 10、[图片上传失败...(image-56f103-1601914568734)]
```java
package chapter03;
import java.util.Random;
public class Code_24 {
public static void main(String[] args){
Random r1 = new Random();
Random r2 = new Random();
int size = r1.nextInt(13);
int color = r2.nextInt(4);
switch (size){
case 0:System.out.print("The card you picked is 1 of ");break;
case 1:System.out.print("The card you picked is 2 of ");break;
case 2:System.out.print("The card you picked is 3 of ");break;
case 3:System.out.print("The card you picked is 4 of ");break;
case 4:System.out.print("The card you picked is 5 of ");break;
case 5:System.out.print("The card you picked is 6 of ");break;
case 6:System.out.print("The card you picked is 7 of ");break;
case 7:System.out.print("The card you picked is 8 of ");break;
case 8:System.out.print("The card you picked is 9 of ");break;
case 9:System.out.print("The card you picked is 10 of ");break;
case 10:System.out.print("The card you picked is Jack of ");break;
case 11:System.out.print("The card you picked is Queen of ");break;
case 12:System.out.print("The card you picked is King of ");break;
}
switch (color){
case 0:System.out.print("Clubs");break;
case 1:System.out.print("Diamonds");break;
case 2:System.out.print("Hearts");break;
case 3:System.out.print("Spades");break;
}
}
}
```
- 11、
```java
package chapter03;
public class Code_28 {
public static void main(String[] args){
java.util.Scanner input = new java.util.Scanner(System.in);
System.out.print("Enter r1's center x-,y-cooordinates, width,and height:");
double x1 = input.nextDouble();
double y1 = input.nextDouble();
double w1 = input.nextDouble();
double h1 = input.nextDouble();
System.out.print("Enter r2's center x-,y-coordinates, width,and height:");
double x2 = input.nextDouble();
double y2 = input.nextDouble();
double w2 = input.nextDouble();
double h2 =input.nextDouble();
double xDistance = x1 -x2 >=0 ? x1-x2 : x2-x1;
double yDistance = y1-y2 >=0? y1-y2 : y2-y1;
if (xDistance <= (w1 - w2) / 2 && yDistance <= (h1 - h2) / 2)
System.out.println("r2 is inside r1");
else if (xDistance <= (w1 + w2) / 2 && yDistance <= (h1 + h2) / 2)
System.out.println("r2 overlaps r1");
else System.out.println("r2 does not overlap r1");
}
}
```