如何使一个do语句重新启动?(How to make a do statement restart?)

我真的不知道怎么解释这个但是我们走了。

我正在测试一些我必须制作的更大程序的东西。 在程序中,我必须验证用户的输入,看看它是否被接受为有效答案。

我有代码,如果输入无效,它将说明如果我试图输入另一个字母,代码崩溃与此错误:

Enter a letter: f Your answer is not valid. A Enter a letter: Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0 at java.lang.String.charAt(String.java:695) at example.main(example.java:18)

这是代码:

import java.util.Scanner; public class example { public static void main(String[] args) { Scanner input = new Scanner(System.in); boolean UserInput; do { char user_answer = 0; System.out.println("Enter a letter:"); user_answer=input.nextLine().charAt(0); if ( user_answer == 'A') { UserInput = true; } else if (user_answer == 'B') { UserInput = true; } else if (user_answer == 'C') { UserInput = true; } else if (user_answer == 'D') { UserInput = true; } else { System.out.println("Your answer is not valid."); UserInput = false; input.next(); } } while (!UserInput); } }

I really do not know to how explain this but here we go.

I am testing something for a bigger program I have to make. In the program I have to validate input from the user to see if it is being to be accepted as a valid answer.

I have the code to where it will say if the input is invalid but if I attempted to enter another letter the code crashes with this error:

Enter a letter: f Your answer is not valid. A Enter a letter: Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0 at java.lang.String.charAt(String.java:695) at example.main(example.java:18)

Here is the code:

import java.util.Scanner; public class example { public static void main(String[] args) { Scanner input = new Scanner(System.in); boolean UserInput; do { char user_answer = 0; System.out.println("Enter a letter:"); user_answer=input.nextLine().charAt(0); if ( user_answer == 'A') { UserInput = true; } else if (user_answer == 'B') { UserInput = true; } else if (user_answer == 'C') { UserInput = true; } else if (user_answer == 'D') { UserInput = true; } else { System.out.println("Your answer is not valid."); UserInput = false; input.next(); } } while (!UserInput); } }

最满意答案

删除input.next()或将其更改为input.nextLine()正在发生的事情是input.next()将捕获您输入的A 然后你回到do的开头并重新开始,然后执行input.nextLine()但是你已经按enter键输入A并且A被input.next()消耗了。

either remove input.next() or change it to input.nextLine() What's happening is that input.next() will catch the A you input. Then you go back to the beginning of the do and start over, and do input.nextLine() but you had already pressed enter to input A and the A was consumed by input.next().

更多推荐