我是初学程序员,我现在已经编写了大约三个星期的代码。我想制作一个简单的程序,询问用户输入温度,并告诉用户是否发烧(温度高于39)。我还想验证用户输入,这意味着如果用户输入“poop”或“!@·R%·%”(符号乱码),程序将输出短语“invalid input”。我正在尝试使用try / catch语句,这是我的代码:
package feverPack;
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException{
try{
InputStreamReader inStream = new InputStreamReader(System.in);
BufferedReader stdIn = new BufferedReader(inStream);
System.out.println("please input patient temperature in numbers");
String numone =stdIn.readLine();}
catch (IOException e) {
System.out.println("invalid input");
}
catch (NumberFormatException e){
System.out.println("invalid input");
}
int temp = Integer.parseInt(numone) ;
System.out.println("Your temperature is " + temp + "ºC");
if (temp > 39) {
System.out.println("You have fever! Go see a doctor!");
}
else{
System.out.println("Don't worry, your temperature is normal");
}
}
}
第22行出现错误(当我将数字转换为临时数时)说“数字无法解析为变量”,因为我是初学者,我真的不知道该怎么做,请帮助。
答案 0 :(得分:1)
将numone
的声明移到try块之外。基本上,numone
在declared
块的scope
内是try
,并且在try
块的范围之外无法使用,因此将其移出会给出它的可见度更高。
String numone = null;
int temp = 0;
try
{
...
numone = stdIn.readLine();
temp = Integer.parseInt(numone) ;
System.out.println("Your temperature is " + temp + "ºC");
if (temp > 39) {
System.out.println("You have fever! Go see a doctor!");
}
else{
System.out.println("Don't worry, your temperature is normal");
}
}
catch(..)
{
...
}