Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/395.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如果输入不正确,我需要重新输入,我该怎么做?_Java_Loops_While Loop - Fatal编程技术网

Java 如果输入不正确,我需要重新输入,我该怎么做?

Java 如果输入不正确,我需要重新输入,我该怎么做?,java,loops,while-loop,Java,Loops,While Loop,如果输入不正确,我需要重新输入,我该怎么做 public static void main(String[] args) throws InterruptedException { String welcomeMessage = "Welcome to our system! Please enter your details to log in.\n"; System.out.println(welcomeMessage); TimeU

如果输入不正确,我需要重新输入,我该怎么做

public static void main(String[] args) throws InterruptedException
    {
        String welcomeMessage = "Welcome to our system! Please enter your details to log in.\n";
        System.out.println(welcomeMessage);

        TimeUnit.SECONDS.sleep(3);

        Scanner inputUserName = new Scanner(System.in);

        String userName = "User Name: ";
        System.out.println(userName);

        String userNameInput = inputUserName.nextLine();

        while (true)
        {

            if (userNameInput.contains("@"))
            {
                System.out.println("Shap");
                break;
            } else
            {
                System.out.println("\nPlease enter a valid user name!");
                String enterAgain = userName;
                System.out.println(enterAgain);
            }
        }
    }

尝试在while条件下使用此选项

Scanner inputUserName = new Scanner(System.in); 

String userNameInput = inputUserName.nextLine();


while (!userNameInput.contains("@")) 

{

    System.out.println("\nPlease enter a valid user name!");

    userNameInput = inputUserName.nextLine(); 
}

System.out.println("Success");

您可以使用while循环来实现这一点-

 Scanner inputUserName = new Scanner(System.in);
    String userName = "User Name: ";
        System.out.println(userName);

        String userNameInput = inputUserName.nextLine();

        while (!userNameInput.contains("@"))
        {
                System.out.println("\nPlease enter a valid user name!");
                System.out.println(userName);
                userNameInput = inputUserName.nextLine()
            }
        }
    System.out.println("Shap");

使用do while循环你可能有一个例子吗?是的。这个不错。但是,通过使用do while,您只能有一行input@HariPrasad你能举个例子吗?@BenCollins试试这个扫描仪inputUserName=new ScannerSystem.in;字符串userNameInput=;执行{System.out.println\n请输入有效的用户名!;userNameInput=inputUserName.nextLine;}while!userNameInput.contains@;