2014-11-07 46 views
0

我是一名初學者程序員,現在我已經寫了大約三個星期的代碼。我想做一個簡單的程序,要求用戶輸入溫度,並告訴用戶是否有發燒(溫度高於39)。我也想驗證用戶輸入,這意味着如果用戶輸入「poop」或「!@·R%·%」(符號亂碼),程序將輸出短語「無效輸入」。我試圖使用try/catch語句,這是我的代碼:使用java.io進行基本輸入驗證

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

答案已經給出了,但看看這裏的一些信息:http://www.java2s.com/Tutorial/Java/0020__Language/VariableScope.htm – 2014-11-07 02:36:27

+0

,所以我做了回答說什麼,加該額外的行,沒有更多的錯誤,仍然該程序不履行其職能,通過這個我的意思是,當我鍵入短語或字母作爲輸入程序仍然崩潰,而不是與catch語句 – 2014-11-07 02:48:39

+0

地方'int temp =整數。 '嘗試'塊內'' – Niroshan 2014-11-07 02:57:39

回答

1

numone的聲明移至try塊外部。基本上,numonetry塊的scope內的declared,並且在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(..) 
{ 
... 
} 
+0

嘗試該人,它出現了第二個錯誤說:「令牌的語法錯誤:刪除這個令牌」,考慮到我已經檢查和字符串寫入正確。 – 2014-11-07 02:37:47

+0

你能否請你用你試過的東西更新你的問題。 – BatScream 2014-11-07 02:39:20

+0

從頭開始,愚蠢的錯誤,但仍然當我寫「不」作爲輸入程序崩潰 – 2014-11-07 02:40:46

相關問題