有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

使用java进行eclipse基本输入验证。木卫一

我是一个初学者程序员,我已经写了大约三个星期的代码了。我想做一个简单的程序,要求用户输入温度,并告诉用户是否发烧(温度高于39)。我还想验证用户输入,这意味着如果用户键入“poop”或“!@·R%·%”(符号乱码),程序将输出短语“无效输入”。我正在尝试使用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无法解析为变量”,因为我是初学者,我真的不知道该怎么做,请帮助


共 (1) 个答案

  1. # 1 楼答案

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