创建带有 while 循环的用户界面

huangapple go评论92阅读模式
英文:

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;        
}

huangapple
  • 本文由 发表于 2020年9月18日 12:39:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/63949414.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定