将“if”语句变为“switch”

时间:2017-01-20 23:04:56

标签: java

在java中,我需要使用3个case语句。它会询问用户输入,如果输入小于或等于0的数字,它会告诉他们一些东西。如果他们输入10或更高,它会说其他的东西。如果他们在1到9之间输入,它会说出一些内容,并为每个大于1的数字添加一个单词,直到他们输入的数字。到目前为止,我已经弄清楚如何通过使用“if”语句来完成大部分操作,但需要使用“switch”来完成。另外,我还没有真正考虑在句子的末尾添加额外的单词,如果它在1-9之间,那么如果你能指出我正确的方向那将是很酷的。

到目前为止,这是我的代码的一部分:

public static void main(String[] args) { 

String Str = "Add more to number";
String Str2 = "Too much number";
String Str3 = "Just right";
int num1 = 0;
Scanner scanIn = new Scanner(System.in);

System.out.println("How much number");
num1 = scanIn.nextInt();

if (num1 <= 0) System.out.println(Str);
else if (num1 > 10) System.out.println(Str2);
else if (num1 < 10 || num1 > 1) System.out.println(Str3);

1 个答案:

答案 0 :(得分:1)

使用if语句是正确的。就像每个人都说过的情况/开关不适合这种情况。此外,它看起来你正在做一个数字猜谜游戏,所以你会想要反复询问输入,直到用户猜对,你会希望他们猜出一个特定的数字。在我的例子中,我使用7作为我的数字来猜测。

public static void main(String[] args) {
    String Str = "Add more to number";
    String Str2 = "Too much number";
    String Str3 = "Just right";
    int num1 = 0;
    int numToGuess = 7; //you can change this to whatever you want
    Scanner scanIn = new Scanner(System.in);

    //we want to ask for a number until it is the same as our numToGuess
    do {
        System.out.println("How much number");
        num1 = scanIn.nextInt();
        //if the number entered is less let them know
        if(num1 < numToGuess)
        {
            System.out.println(Str);
        }
        else if(num1 > numToGuess)
        {
            System.out.println(Str2);
        }
    } while (num1 != numToGuess); 
    //we will continue to ask until our num1 is equal to numToGuess

    //since we got out we guessed correctly
    System.out.println(Str3);

}//main method
相关问题