import java.util.Scanner;
public class HelloWorld
{
public static void main(String[] args)
{
Scanner math = new Scanner(System.in);
System.out.println("What is 2 + 2?");
int num = math.nextInt();
System.out.println("Wrong."); // Displays "Wrong." no matter the answer.
{
Thread.sleep(2000); // Adds a timer for 2 seconds.
}
catch(InterruptedException e)
{
System.out.println("Please, try again :-)");
}
int num1 = math.nextInt();
System.out.println(""); //Displays some message.
}
}
代码应该显示"什么是2 + 2?",用户输入答案,代码返回"错误。"不管答案是什么。暂停2秒后,代码显示"请再试一次: - )"并且用户输入一个整数,代码返回一条消息。
错误发生在使用catch标记的行上。错误是: 令牌上的语法错误" catch",(预期, 语法错误,插入" - > LambdaBody"完成LambdaExpression, 语法错误,插入" AssignmentOperator Expression"完成作业, 语法错误,插入";"完成声明
答案 0 :(得分:1)
要在java中使用catch
,您需要拥有try
。它被称为try..catch
块。请阅读文档here
因此,如下添加try
应该可以解决您在此处提出的错误:
System.out.println("Wrong."); // Displays "Wrong." no matter the answer.
try // Looks like you missed the try here
{
Thread.sleep(2000); // Adds a timer for 2 seconds.
} catch (InterruptedException e) {
System.out.println("Please, try again :-)");
}
答案 1 :(得分:0)
我看不到尝试阻止。你可以使用这种方式,而不用尝试捕获。 Main方法可以抛出InterruptedException ...
public class HelloWorld {
public static void main(String[] args) throws InterruptedException {
Scanner math = new Scanner(System.in);
System.out.println("What is 2 + 2?");
int num = math.nextInt();
System.out.println("Wrong."); // Displays "Wrong." no matter the answer.
{
Thread.sleep(2000); // Adds a timer for 2 seconds.
}
int num1 = math.nextInt();
System.out.println(""); //Displays some message.
}
}