简体   繁体   中英

basic input validation with java.io

I'm a beginner programmer, I have been writing code for about three weeks now. I want to make a simple program that asks for user input temperature and tells whether or not the user has fever (temperature higher than 39). I also want to validate the user input, meaning that if the user types "poop" or "!@·R%·%" (symbol gibberish), the program will output the phrase "invalid input". I'm trying to use the try/catch statements, this is my code:

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");
        }
    }
}

There is an error in line 22 (when i transform numone into a temp) saying "numone cannot be resolved to a variable", as I am a beginner I don't really know what to do, please help.

Move the declaration of numone outside the try block. Basically, numone was declared within the scope of the try block and was not available outside the scope of the try block, so moving it out would give it a wider visibility.

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(..)
{
...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM