英文:
Create user interface with while loop
问题
import java.util.Scanner;
public class Part3{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.println("欢迎,亲爱的用户!");
System.out.println("您想要:");
System.out.println("a) 求和");
System.out.println("b) 退出");
System.out.print("选项: ");
String optionString = input.next();
char option = optionString.charAt(0);
while (option == 'a'){
System.out.println("你好");
}
}
}
我卡在了 while 循环这一部分,编译时出现错误,显示二进制运算符的操作数类型错误。我刚接触 Java,你能帮我解决一下吗?非常感谢。
英文:
I currently have an assignment on creating a user interface with while loop, here is my code so far:
import java.util.Scanner;
public class Part3{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.println("Welcome dear user!");
System.out.println("Would you like to:");
System.out.println("a) sum gain");
System.out.println("b) exit");
System.out.print("Option: ");
String optionString = input.next();
char option = optionString.charAt(0);
while (option == ("a")){
System.out.println("Helo");
}
}
}
I'm stuck with the while loop, when I compile, it is error say a bad operand types for binary operator. I'm new to java so can you guys help me out with this. Thanks a lot
答案1
得分: 1
你可能会遇到以下问题:
Part3.java:14: 错误: 不能比较类型:char 和 String
while (option == ("a")){
因为你正在尝试比较一个 **char (option)** 和一个 **String ("a")**。所以请使用 **'a'** 代替 **"a"**。
即使在解决了这个问题后,当用户选择选项 a 时,你的代码似乎会陷入无限循环。
如果你只想打印一次,请在循环内使用 break; 语句。
```java
while (option == ('a')){
System.out.println("Helo");
break;
}
英文:
You might be facing the following issue:
Part3.java:14: error: incomparable types: char and String
while (option == ("a")){
Because you're trying to compare a char (option) and a String ("a"). So do use 'a' instead of "a".
Even when you'll resolve this issue, it seems that your code will stuck into a infinite loop when user will choose option a.
If you wanna print it only one time use break; statement inside loop.
while (option == ("a")){
System.out.println("Helo");
break;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论