您好我想尝试运行一些java但是我一直收到错误信息这里是消息:
unreported exception IOException; must be caught or declared to be thrown myName = in.readLine();
import java.io.*;
public class While{
public static void main(String []args){
int num = 0;
while (num != 999){
System.out.println("Enter a number:");
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
num = Integer.parseInt(in.readLine());
System.out.println("You typed: " + num);
}
System.out.println("999 entered, so the loop has ended.");
}
}
Run Code Online (Sandbox Code Playgroud)
刚刚出去,我没有使用java,这是我第一次使用它,我的老板问我是否可以看看它到目前为止我能做的一切但我无法解决此错误消息,欢迎任何和所有帮助.
用try-catch语句包围代码并BufferedReader在while循环之前移动初始化.此外,请确保在使用后始终关闭资源.
public static void main(String []args) {
int num = 0;
BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(System.in));
while (num != 999){
System.out.println("Enter a number:");
num = Integer.parseInt(in.readLine());
System.out.println("You typed: " + num);
}
} catch (Exception e) {
//handle your exception, probably with a message
//showing a basic example
System.out.println("Error while reading the data.");
e.printStacktrace(System.in);
} finally {
if (in != null) {
try {
in.close();
} catch (Exception e) {
System.out.println("Problem while closing the reader.");
e.printStacktrace(System.in);
}
}
}
System.out.println("999 entered, so the loop has ended.");
}
Run Code Online (Sandbox Code Playgroud)
如果您使用的是Java 7,则可以使用try with resources语句来利用所有代码:
public static void main(String []args) {
int num = 0;
try(BufferedReader in = new BufferedReader(new InputStreamReader(System.in))) {
while (num != 999){
System.out.println("Enter a number:");
num = Integer.parseInt(in.readLine());
System.out.println("You typed: " + num);
}
} catch (Exception e) {
//handle your exception, probably with a message
//showing a basic example
System.out.println("Error while reading the data.");
e.printStacktrace(System.in);
}
System.out.println("999 entered, so the loop has ended.");
}
Run Code Online (Sandbox Code Playgroud)