如果输入错误的值,如何去一行

时间:2016-07-21 10:56:01

标签: java loops

我一直试图弄清楚这一点:如何确保程序继续运行,直到输入正确的值,如果输入错误的值,则不会终止。

代码:

package class3;

import java.util.Scanner;

public class dayName {

public static void main(String args[]){

    Scanner input = new Scanner(System.in);
    System.out.println("\nEnter any of the following values from 0 to 7 and \nI'll tell you the corresponding day.\n");
    int day = input.nextInt();

    switch (day){

    case 0: day = 0;
    if (day == 0)
        System.out.println("\nThat would be Sunday!\n");
        break;
    case 1: day = 1;
    if (day == 1)
        System.out.println("\nThat would be Monday!\n");
        break;
    case 2: day = 2;
    if (day == 2)
        System.out.println("\nThat would be Tuesday!\n");
        break;
    case 3: day = 3;
    if (day == 3)
        System.out.println("\nThat would be Wednesday!\n");
        break;
    case 4: day = 4;
    if (day == 4)
        System.out.println("\nThat would be Thursday!\n");
        break;
    case 5: day = 5;
    if (day == 5)
        System.out.println("\nThat would be Friday!\n");
        break;
    case 6: day = 6;
    if (day == 6)
        System.out.println("\nThat would be Saturday!\n");
        break;
    default: if(day < 0 && day > 6);
        System.out.println("\nThere's no day as such!\n");
        System.exit(0);

    }
}

}

感谢。

1 个答案:

答案 0 :(得分:1)

boolean isValid = false;
do
{
    final int day = scanner.nextInt();
    if (day >= 0 && day <= 6)
    {
        isValid = true;
    }
    else
    {
         switch (day)
         {
            case 0:
              System.out.println("Sunday");
              break;
            case 1:
              System.out.println("Monday");
              break;
            case 2:
              System.out.println("Tuesday");
              break;
            case 3:
              System.out.println("Wednesday");
              break;
            case 4:
              System.out.println("Thursday");
              break;
            case 5:
              System.out.println("Friday");
              break;
            case 6:
              System.out.println("Saturday");
              break;
            default:
              System.out.println("Incorrect");
        }
    }
} while (!isValid);

此代码适用于我。如果它不适合你,你一定做错了。