gpt4 book ai didi

java - 字节扫描仪未正确比较,Java

转载 作者:行者123 更新时间:2023-12-02 09:32:07 26 4
gpt4 key购买 nike

我正在尝试比较 switch 语句中的扫描仪编号。扫描仪工作正常,但未按应有的方式进行比较。

    private String gradeLevel;

public byte askGrade(){
Scanner scan = new Scanner(System.in);
System.out.println("Please enter grade level; ");
System.out.println(" 1-Freshman \n 2-Sophomore \n 3-Junior \n 4-Senior ");
byte grade = scan.nextByte();
switch(grade){
case 1: gradeLevel = "Freshman";
case 2: gradeLevel = "Sophomore";
case 3: gradeLevel = "Junior";
case 4: gradeLevel = "Senior";
default: gradeLevel = "Withdrawn";
}
return gradeLevel;
}

始终默认为“撤回”

最佳答案

在每种情况下都应该使用 break

来自switch documentation

Each break statement terminates the enclosing switch statement. Control flow continues with the first statement following the switch block. The break statements are necessary because without them, statements in switch blocks fall through: All statements after the matching case label are executed in sequence, regardless of the expression of subsequent case labels, until a break statement is encountered

Scanner scan = new Scanner(System.in);
System.out.println("Please enter grade level; ");
System.out.println(" 1-Freshman \n 2-Sophomore \n 3-Junior \n 4-Senior ");
byte grade = scan.nextByte();
String gradeLevel;
switch (grade) {
case 1:
gradeLevel = "Freshman";
break;
case 2:
gradeLevel = "Sophomore";
break;
case 3:
gradeLevel = "Junior";
break;
case 4:
gradeLevel = "Senior";
break;
default:
gradeLevel = "Withdrawn";
}
System.out.println(gradeLevel);

输出

Please enter grade level; 
1-Freshman
2-Sophomore
3-Junior
4-Senior
2
Sophomore

关于java - 字节扫描仪未正确比较,Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57878778/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com