Java编写do-while循环录入学生信息输入y不触发循环如何解决
问题解决建议
核心错误原因
你代码中循环不触发的核心问题是错误使用==运算符做字符串内容比较:
Java中==用于引用类型(比如String)时,比较的是两个对象的内存地址是否一致,而非内容是否相同。你通过Scanner输入得到的another字符串对象,和代码中写死的常量字符串"Y"/"y"内存地址不同,所以判断条件永远返回假,循环直接终止。
新手可直接落地的修改方案
- 替换字符串比较逻辑
使用String类的equalsIgnoreCase()方法做大小写不敏感的内容比较,修改两处字符串比较代码:
- 循环条件修改为:
while(another.equalsIgnoreCase("y")); - 末尾退出提示的判断修改为:
if(another.equalsIgnoreCase("n"))
- 替换字符串比较逻辑
- 补充输入合法性校验(可选优化)
可以增加对年级、课程选项的合法性判断,比如用户输入的课程编号不在1-4范围内时,提示重新输入,避免程序逻辑异常。
- 补充输入合法性校验(可选优化)
- 统一输入处理逻辑(可选优化)
你当前在nextInt()之后调用scan.nextLine()吞掉残留换行符的逻辑是正确的,新手也可以选择所有输入都用nextLine()接收,再手动转为int类型,降低遗漏吞换行符导致输入错位的概率。
- 统一输入处理逻辑(可选优化)
修改后的完整可运行代码
import java.util.Scanner; public class Practice{ public static void main(String[]args) { Scanner scan = new Scanner(System.in); String studentName, another; int year,choice; do{ System.out.println("Student name: "); studentName = scan.nextLine(); System.out.println("Year: "); year = scan.nextInt(); System.out.println("\t1.BSIT \n\t2.BSCS \n\t3.BSCpE \n\t4.BSN"); System.out.print("Choice: "); choice = scan.nextInt(); scan.nextLine(); // 吞掉nextInt残留的换行符 if(choice == 1) { System.out.println("Course is BSIT"); } else if(choice == 2 ) { System.out.println("Course is BSCS"); } else if(choice == 3 ) { System.out.println("Course is BSCpE"); } else if(choice == 4) { System.out.println("Course is BSN"); } else { System.out.println("Invalid course choice"); } System.out.println("Another Student? type Y if yes, and N if no"); another = scan.nextLine(); }while(another.equalsIgnoreCase("y")); if (another.equalsIgnoreCase("n")) { System.out.println("You are the last student."); } scan.close(); // 关闭Scanner避免资源泄漏 } }
内容的提问来源于stack exchange,提问作者Klyne Ajido
相关产品推荐
相关产品推荐

