gpt4 book ai didi

java - 制作菜单时在Java中创建while循环

转载 作者:行者123 更新时间:2023-12-02 12:43:42 25 4
gpt4 key购买 nike

我一直在尝试使用 Java 中的“do”功能创建一个菜单。我首先为用户提供一系列选项,然后请求用户通过键盘输入他们的选项,然后创建字符串变量“选择”。但是,当我在循环表达式中引用“选择”变量时,会出现错误指示“选择无法解析为变量”。为什么会这样?我该如何纠正这个问题?

请引用下面的代码。

do{
//output presenting the user with options
System.out.print("A simple Menu\n");
System.out.print("Y - Yolk\n");
System.out.print("N - Naan\n");
System.out.print("X - Exit\n\n");

//request user input using the import.util.*; feature
System.out.print("Enter your selection: ");
String selection=keyboard.nextLine();
// So here the 'selection' string is made

}
//Now here, whatever the user has selected as an option will be
// passed through and more options will appear.
while(selection!="X");

//however I get prompted with the red squiggly line underneath the
//'selection' variable that seems to not recognize 'selection' as a string

最佳答案

当循环尝试再次检查它时,您的selection变量超出了范围(或者您可以认为它已经被破坏)。所以在循环之外定义它。

String selection ="";
do{
//output presenting the user with options
System.out.print("A simple Menu\n");
System.out.print("Y - Yolk\n");
System.out.print("N - Naan\n");
System.out.print("X - Exit\n\n");

//request user input using the import.util.*; feature
System.out.print("Enter your selection: ");
selection=keyboard.nextLine();
// So here the 'selection' string is made

}
//Now here, whatever the user has selected as an option will be
// passed through and more options will appear.
while(!selection.equals("X"));

编辑

我完全同意@Tim Biegeleisen 的观点。但他的错误消息不是关于字符串与逻辑运算符的比较。不管怎样,我编辑了我的答案。非常感谢您指出这一点。

关于java - 制作菜单时在Java中创建while循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44859598/

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