Java流程控制-if和switch
if
- If (boolean表达式) {为true,执行这里的} else
package opearater;
import java.util.Scanner;
public class SuanYuanYunSuanFu {
public static void main(String[] args) {
int HaoGanDu = 90;
Scanner scanner = new Scanner(System.in);
System.out.println("请输入你对我的好感度:0-100");
while (scanner.hasNextInt()) {
HaoGanDu = scanner.nextInt();
// System.out.println(HaoGanDu > 80 ? "我喜欢你" : "我对你没感觉");
if (HaoGanDu >= 99){
System.out.println("我爱你");
}else if(HaoGanDu >= 90 ){
System.out.println("我特别喜欢你");
}else if (HaoGanDu>=80){
System.out.println("我喜欢你");
}else if (HaoGanDu >= 40){
System.out.println("我对你没感觉");}
else {
System.out.println("我讨厌你");
}
// scanner.close();
}
// scanner.close();
}
}
switch
package opearater;
import java.util.Scanner;
public class Switch {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请写下你对我的感觉");
while (scanner.hasNextLine()){
String feeling = scanner.nextLine();
switch (feeling){
case "我爱你":
System.out.println("好感度>=99");
break;
case "我特别喜欢你":
System.out.println("好感度>90");
break;
case "我喜欢你":
System.out.println("好感度>80");
break;
case "我讨厌你":
System.out.println("好感度<20");
break;
default:
System.out.println("我对你没感觉");
}
}
}
}
- 将生成的class文件拖入Idea,从得到的反编译文件可知switch(字符串)也是转化为switch(数字)处理的
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//
package opearater;
import java.util.Scanner;
public class Switch {
public Switch() {
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请写下你对我的感觉");
while(scanner.hasNextLine()) {
String feeling = scanner.nextLine();
byte var4 = -1;
switch(feeling.hashCode()) {
case -877105257:
if (feeling.equals("我特别喜欢你")) {
var4 = 1;
}
break;
case 25052448:
if (feeling.equals("我爱你")) {
var4 = 0;
}
break;
case 769834857:
if (feeling.equals("我喜欢你")) {
var4 = 2;
}
break;
case 782944075:
if (feeling.equals("我讨厌你")) {
var4 = 3;
}
}
switch(var4) {
case 0:
System.out.println("好感度>=99");
break;
case 1:
System.out.println("好感度>90");
break;
case 2:
System.out.println("好感度>80");
break;
case 3:
System.out.println("好感度<20");
break;
default:
System.out.println("我对你没感觉");
}
}
}
}