Java代码如何编写else语句实现用户输入n/N时终止程序?
问题根因
- 字符串比较逻辑错误:Java中
==比较String类型时校验的是对象内存地址,而非字符串内容,即使输入内容是y/Y,也会因为字符串对象不是同一个实例导致判断不成立,触发你写的else退出逻辑。 - if分支作用域错误:原代码的if判断后没有加花括号,只有紧随其后的
sc.nextLine()属于if分支,后续代码不管判断是否成立都会执行,添加else后逻辑完全不符合预期。 - 存在多余输入读取逻辑:if判断通过后额外调用的
sc.nextLine()属于无效代码,会导致程序多吞一行输入,引发逻辑异常。
修复后完整代码
import java.util.*; class FirstExample{ static void arithmetic(){ Scanner sc = new Scanner(System.in); while(true){ System.out.println("\nDo u want to perform the arithmetic operations? (Y/N): "); String input = sc.nextLine(); // 忽略大小写判断是否要继续 if(input.equalsIgnoreCase("y")) { System.out.println("Enter first number: "); double first = sc.nextDouble(); System.out.println("Enter second number: "); double second = sc.nextDouble(); System.out.println("Addition of the two number is: "+(first+second)); System.out.println("Subtraction of the two number is: "+(first-second)); System.out.println("Multiplication of the two number is: "+(first*second)); System.out.println("Division of the two number is: "+(first/second)); // 吃掉nextDouble遗留的换行符 sc.nextLine(); } else if(input.equalsIgnoreCase("n")) { // 输入n/N时退出 System.exit(0); } else { // 非法输入提示 System.out.println("Invalid input, please enter Y/N"); } } } public static void main(String[]args){ FirstExample.arithmetic(); } }
优化说明
- 采用
equalsIgnoreCase()方法比较字符串,自动匹配大小写的Y/N,无需分开写两个判断条件 - 给if/else分支都加上了花括号,明确作用域,避免逻辑混乱
- 新增了非法输入的提示,避免用户输入其他内容时程序无响应
内容的提问来源于stack exchange,提问作者Yash Deole
相关产品推荐
相关产品推荐

