2013-04-12 31 views
2

請在此代碼中幫助指定僅爲整數的輸入 .............................. ..................................如何指定輸入

 int shape=0; 
     boolean inp=false; 
     while (! inp) { 
      try 
      { 
       shape = (int)(System.in.read()-'0'); 

      }//try 
      catch (IOException e) 
      { 
       System.out.println("error"); 
       System.out.println("Please enter the value again:"); 
      }//catch 
       if ((shape == 1) || (shape == 2)) { 
       inp = true; 
      }//if 
     }//while 
+0

你不能強迫用戶進入控制檯模式的特定輸入。 – deepmax

+1

使用Integer.parse然後驗證生成的Integer。 –

回答

1

我編輯了答案並放入了完整碼。它現在可以工作(測試它)。使用BufferedReader中可以讀取實際Strings(這就是爲什麼它被卡在之前一個無限循環)

int shape = 0; 
    boolean inp = false; 
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)); 
    while (!inp) { 
     try { 
      System.out.println("Type in a number"); 
      shape = Integer.parseInt(bufferedReader.readLine()); // parse the string explicitly 
      System.out.println("thanks"); 
     }//try 
     catch (IOException e) { 
      System.out.println("error"); 
      System.out.println("Please enter the value again:"); 
     }//catch 
     catch (NumberFormatException e) // here you catch the exception if anything but a number was entered 
     { 
      System.out.println("error"); 
      System.out.println("Please enter the value again:"); 
     }//catch 
     System.out.println("Shape = " + shape); 
     if ((shape == 1) || (shape == 2)) { 
      System.out.println("should be true"); 
      inp = true; 
     }//if 
+0

它給我這個錯誤 找到parseInt函數(INT) 方法的Integer.parseInt(字符串)沒有合適的方法是不適用 (實際參數INT不能通過方法調用轉換被轉換成字符串) 方法的Integer.parseInt(字符串,int)不適用 (實際的和正式的參數列表長度不同) –

+0

那麼你可以強制輸入是像這樣的String類型:Integer.parseInt(「」+ System.in.read() );' – GameDroids

+0

確定錯誤消失了,但是當我輸入一個字母並沒有發現任何錯誤,並且進入了無限循環 –

2

如果唯一有效的輸入爲12然後我只想限制爲那些確切的字符 (編輯:這已經測試和工程):

char c = '-'; //invalid character to default 
while (! (c == '1' || c == '2')) 
{ 
    System.out.println("Please enter 1 or 2:"); 
    c = (char) System.in.read(); 
    System.out.println(c); 
} 
+0

是這是工作,但我不能使用字符只有整數.. 它是一個作業項目 –

+0

那麼這很不幸,因爲他們教你糟糕的做法。我將與你分享一些我在學習編程時真的希望有人告訴我的東西:如果你不打算用它做數學,那麼不要把它當作數字。永遠。你打開自己的各種驗證惡夢和奇怪的錯誤。儘量避免僅僅因爲有人告訴你做錯事。 – MikeTheLiar

+0

感謝您的建議,我會始終保持在我的腦海:) 作爲一級學習者,他們限制我們遵守一些規則,有時他們甚至不接受課程以外的代碼。 但爲了我自己的發展,我正在盡一切可能的方式來編寫代碼。 –

0
Integer i = null; 
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); 
    while (true) 
    { 
     System.out.println("Please enter 1 or 2:"); 
     try { 
      i = Integer.parseInt(in.readLine()); 
      if(i==1 || i==2){ 
       System.out.println("Success! :)"); 
       break; 
      } 
     } catch (IOException ex) { 
      System.out.println("IO Exception"); 
     } catch (NumberFormatException e){ 
      System.out.println("Invalid input"); 
     }  
    } 
相關問題