gpt4 book ai didi

java - 为什么我的程序不等待输入?

转载 作者:行者123 更新时间:2023-11-30 11:07:10 26 4
gpt4 key购买 nike

我正在尝试获取用户输入并使用正则表达式对其进行验证。但是,当我运行该程序时,它似乎并没有等待接收任何额外的用户输入。相反,我得到了

Exception in thread "main" java.util.NoSuchElementException`

任何关于正在发生的事情的帮助都会很棒!

这是我的代码:

//Retrieve name
System.out.println("What name would you like to search for? (Enter first name only without spaces)");
Scanner input = new Scanner(System.in);
while (!input.hasNext("[A-Za-z]+")) {
System.out.println("Invalid entry. Please enter first name only.");
input.next();
}
String name = input.next();
System.out.println("You gave me as input the name:" + name);
}

最佳答案

工作正常。将其作为一个完整的工作类进行尝试(将其保存为 myInput.java,然后使用javac myInput.java编译> ,然后使用java myInput运行它:

import java.io.*;
import java.util.Scanner;
class myInput {
public static void main(String[] args) {
//Retrieve name
System.out.println("What name would you like to search for? (Enter first name only without spaces)");
Scanner input = new Scanner(System.in);
while (!input.hasNext("[A-Za-z]+")) {
System.out.println("Invalid entry. Please enter first name only.");
input.next();
}
String name = input.next();
System.out.println("You gave me as input the name:" + name);
}
}

OUTPUT(我首先给出无效输入(test1),然后正确打印有效(test)):

test1
Invalid entry. Please enter first name only.
test
You gave me as input the name:test

关于java - 为什么我的程序不等待输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29017231/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com