我是一名初学者程序员,我已经写了大约三个星期的代码。我想编写一个简单的程序,询问用户输入温度,并告诉用户是否发烧(温度高于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行(​​当我将numone转换为临时变量时)出现错误,提示“ numone无法解析为变量”,因为我是初学者,我真的不知道该怎么办,请帮忙。

最佳答案

numone的声明移到try块之外。基本上,numonedeclared块的scope内,并且在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(..)
{
...
}

10-04 11:06