如何在输入错误后循环回到数组的开头

时间:2017-11-22 09:01:39

标签: java

首先发布在这里。 我被指示更改我的代码以循环回到数组的开头,并在输入无效的内容后再次询问用户输入(例如0或5)。 如果有人能指出我正确的方向,我会很感激。

package lepackage;
import java.util.Scanner;
public class SwitchItUp {
    public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
       System.out.println("Enter menu item:");
       int input = scanner.nextInt();
        String inputString;
        switch (input) {
            case 1:  inputString = "User want to Enter data";
                     break;
            case 2:  inputString = "User want to Display sata";
                     break;
            case 3:  inputString = "User want to Print data";
                     break;
            case 4:  inputString = "User want to Exit";
                     break;
            default: inputString = "Invalid Number";
                     break;
        }
        System.out.println(inputString);
    }
}

2 个答案:

答案 0 :(得分:3)

我用do...while循环

围绕它
do {
//your code here
} while (!(input > 0 && input < 5));

See it online!

答案 1 :(得分:1)

如何在此处使用标签。虽然与做..而相比,这不是更清洁的方法。 see the code。还don't forget to close the scanner !!

 Scanner scanner = new Scanner(System.in);
        int input;
        badinput: while (true) {
            System.out.println("Enter menu item:");
            input = scanner.nextInt();
            String inputString;
            if ((!(input > 0 && input < 5)))
                continue badinput;
            else {
                switch (input) {
                //switch case
                }
                System.out.println(inputString);
                break;
            }

        }
        scanner.close();