java - I have to enter my input twice to get the output
问题描述
When it comes to the letter a,b,c , if i enter them i need to enter them twice(2 spaces is used). Compared to when I enter an integer or an blank space, my Exception returns it with 1 line. I tried using only String answer = scan.next but it does not read and return when i enter empty spaces so i'm using String answer = scan.nextLine();
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String questions[] = {"What is the color of the sky? ", "What is 1 + 1? ",
"What is the capital of the Philippines? ", "Who is the current president of the Philippines? ",
"What is the capital of Japan? ", "What is 2 + 3? ",
"What is 9 + 1?", "What is the capital of the United States? ",
"What is 10 + 10? ", "How many hand fingers do humans have? "};
String choices[] = {"a","b","c"};
int x = 0;
int y = 0;
System.out.println("Choose a Letter: a , b , c");
try {
while(x<=9) {
System.out.println("No." + (x+1) + " " + questions[x]);
String answer = scan.nextLine();
x++;
if(answer.equals(choices[0])) {
scan.nextLine();
} else if (answer.equals(choices[1])) {
scan.nextLine();
} else if (answer.equals(choices[2])) {
scan.nextLine();
} else if (answer.equals(" ")) {
throw new EmptyInputException();
} else {
throw new InvalidLetterException();
}
}
} catch(InvalidLetterException e) {
System.out.println(); //Spacing
System.out.println(e.getMessage());
System.out.println(); //Spacing
System.out.println("You can try again.");
System.out.println(); //Spacing
do {
System.out.println("No." + (y+1) + " " + questions[y]);
scan.next();
y++;
}while(y<=9);
} catch (EmptyInputException e) {
System.out.println(); //Spacing
System.out.println(e.getMessage());
System.out.println(); //Spacing
System.out.println("You can try again.");
System.out.println(); //Spacing
do {
System.out.println("No." + (y+1) + " " + questions[y]);
scan.next();
y++;
}while(y<=9);
}
}
解决方案
推荐阅读
- python - 根据 URL 包含的最高参数过滤 URL 的 Python 列表
- python - 将 django 应用程序从 localhost 应用程序部署到 Web 应用程序
- laravel-5 - 为什么 DB::select 工作但 DB::table 不起作用?
- java - 为 servlet [dispatcherServlet] 提供错误 Servlet.service() 的自定义异常处理
- node.js - AWS Lambda 函数不会插入 Dynamo DB
- c - 为什么这个while条件没有捕捉到EOF?我得到分段错误
- php - 如何使用输入表单组合数组
- c++ - 如何将浮点算法转换为定点?
- php - 如何在 Yii2 项目中使用rectorphp/rector?
- javascript - 通过 Ajax 将数据发送到 .NET 中的处理程序。XML 解析错误:找不到根元素