输入重复相同的情况

时间:2015-11-25 00:37:06

标签: java repeat

运行此代码后,它表示BUILD SUCCESSFUL并停止。我应该怎么做才能重复询问具有相同案例的另一个输入?我确实在几个网站上阅读了教程,但我没有帮助。

以下是代码:

import java.util.Scanner;

public class SwitchTry {

public static void main(String[] args) {

    int mth;
    String mthString;
    Scanner scanner = new Scanner(System.in);

    mth =scanner.nextInt();

    switch (mth) {
        case 1: mthString = "January";
            break;
        case 2: mthString = "February";
            break;
        case 3: mthString = "March";
            break;
        case 4: mthString = "April";
            break;
        case 5: mthString = "May";
            break;
        case 6: mthString = "June";
            break;
        case 7: mthString = "July";
            break;
        case 8: mthString = "August";
            break;    
        case 9: mthString = "September";
            break;
        case 10: mthString = "October";
            break;
        case 11: mthString = "November";
            break;
        case 12: mthString = "December";
            break;    
        default: mthString = "Error";
            break;
    }

    System.out.println(mthString);
}

}

感谢您提供的任何帮助。

2 个答案:

答案 0 :(得分:0)

I would try using a while loop to encase the switch. So it keeps asking your input. 
import java.util.Scanner;

public class SwitchTry {

public static void main(String[] args) {

while(true){
    int mth;
    String mthString;
    Scanner scanner = new Scanner(System.in);

    mth =scanner.nextInt();

    switch (mth) {
        case 1: mthString = "January";
            break;
        case 2: mthString = "February";
            break;
        case 3: mthString = "March";
            break;
        case 4: mthString = "April";
            break;
        case 5: mthString = "May";
            break;
        case 6: mthString = "June";
            break;
        case 7: mthString = "July";
            break;
        case 8: mthString = "August";
            break;    
        case 9: mthString = "September";
            break;
        case 10: mthString = "October";
            break;
        case 11: mthString = "November";
            break;
        case 12: mthString = "December";
            break;    
        default: mthString = "Error";
            break;
    }

    System.out.println(mthString);
}
}
}

答案 1 :(得分:0)

正如 MadProgarmmer 所建议的,do-while循环是这种情况的完美用例。您需要在do-while循环中包装输入行以及switch case和print语句,如下所示:

do {
   //so you know that terminal is asking for input
   System.out.println("Input: "); 

   mth =scanner.nextInt();

   //copy/paste your switch case with last System.out.println() here

} while (true); 

我担心执行永远不会结束。也许你想在用户提供-1时结束循环,所以将while(true)更改为while(mth!= -1),那应该是你的终止输入。