这是我当前的代码:
import java.lang.String;
import java.io.*;
class InvalidAgeException extends Exception
{
public InvalidAgeException()
{
super("The age you entered is not between 0 and 125");
}
}
public class questionOne
{
public static void main(String args[])
{
System.out.println("What is your name?");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String name;
try
{
name = br.readLine();
}
catch(IOException e)
{
System.out.println("Error: " + e);
System.exit(1);
}
System.out.println("Hello " + name + ", how old are you?");
String i;
int age;
try
{
i = br.readLine();
age = Integer.valueOf(i);
}
catch(IOException e)
{
System.out.println("Error: " + e);
System.exit(1);
}
catch(InvalidAgeException e)
{
System.out.println("Error: " + e);
System.exit(1);
}
finally
{
System.out.println("No errors found.");
}
}
}
作业是编写一个程序,询问用户的姓名和年龄,如果年龄不在 0 到 125 之间,则抛出异常。我的代码中出现两个错误:
questionOne.java:31: variable name might not have been initialized
System.out.println("Hello " + name + ", how old are you?");
^
questionOne.java:46: exception InvalidAgeException is never thrown in body of corresponding try statement
catch(InvalidAgeException e)
^
2 errors
我不确定如何修复它们。
最佳答案
您的第一个错误是由于从未初始化名称引起的。请记住,它只在 Try Catch block 中初始化,这会导致编译器抛出错误,因为它可能永远不会在程序中初始化。因此,将 try catch block 上方的行更改为
String name = "";
将解决该错误。
编辑:
这可能是您需要在 try catch block 之外执行的操作。
if (age < 0 || age > 125){
throw new InvalidAgeException();
}
关于java - 我的 Java 作业中有两个错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6116029/