在我的主要方法中,我有以下代码片段:
try {
select = scanner.nextInt();
} catch (InputMismatchException e) {
scanner.next(); //we should read erroneous
System.out.println("Error. Please input number.");
continue;
}
我让mvn clezan install->转到目标目录。并开始使用应用程序
实际上,我输入了数字,但是在控制台中,我看到以下消息:
D:\freelance\Новая папка\myrepository\target>java -jar palindrome-artifactId-1.0
-SNAPSHOT.jar
Please type your name:
u1
Please select menu item
1 - suggest word, 2 - change user, 3 - my score, 4 - my word list, 5 - records,
6 - exit
1
Error. Please input number.
Please select menu item
1 - suggest word, 2 - change user, 3 - my score, 4 - my word list, 5 - records,
6 - exit
当我从idea(选择main方法)调用应用程序时,我没有看到这个问题。
请帮助解决我的问题。
附言
完整的主要方法:
public static void main(String[] args) {
System.out.println("Please type your name:");
try (Scanner scanner = new Scanner(System.in)) {
scanner.useDelimiter("\n");
String userName = scanner.next();
Game game = new Game(userName);
AtomicInteger atomicInteger = new AtomicInteger();
int select = 0;
do {
System.out.println("Please select menu item");
System.out.println("1 - suggest word, 2 - change user, 3 - my score, 4 - my word list, 5 - records, 6 - exit");
try {
select = scanner.nextInt();
} catch (InputMismatchException e) {
scanner.next(); //we should read erroneous
System.out.println("Error. Please input number.");
continue;
}
switch (select) {
case 1:
System.out.print("Word:");
String word = scanner.next();
if (game.suggestWord(word)) {
System.out.println("Accepted: your score - " + game.getCurrentUserScore());
} else {
System.out.println("Rejected: Word already exists in your list or it is not palindrome");
System.out.println("Your score - " + game.getCurrentUserScore());
}
break;
case 2:
System.out.print("Name:");
String name = scanner.next();
game.changeUser(name);
System.out.println("User changed successfully. Your score - " + game.getCurrentUserScore());
break;
case 3:
System.out.println("Your score - " + game.getCurrentUserScore());
break;
case 4:
System.out.println("Accepted words:");
game.getCurrentUserAcceptedWords().forEach(System.out::println);
break;
case 5:
atomicInteger.set(1);
game.getScores().forEach((k, v) -> System.out.println("#" + atomicInteger.getAndIncrement() + ". name: " + k + " , score: " + v));
break;
case 6:
System.out.println("Goodbye! thanks for the game");
break;
default:
System.out.println("You selected nonexistent menu item. Please try one more time.");
}
} while (select != 6);
}
}
最佳答案
您的问题可能是定界符。它正在寻找\n
,但是在Windows上,每行以\r\n
结尾。因此,尽管您没有看到"u1\r"
(检查其长度),但您获得的用户名可能是\r
,并且您输入的数字被读取为"1\r"
,该数字不能解析为数字。
我想您的IDE中的模拟控制台会将您的紧迫返回解释为\n
,这就是它在那里起作用的原因。
因此,将您的分隔符(而不是\n
)更改为\r?\n
。分隔符是一个正则表达式,这意味着“可选的回车符,后跟换行符”。