2012-03-28 19 views
2

「x」を入力するまで、数字を入力する必要のあるコンソールアプリケーションがあります。 もちろん、 "x"を入力すると、NumberFormatExceptionが返されます。コンソール入力java。文字列の解析

"x"を入力しても例外なくプログラムを終了するにはどうしたらいいですか?

BufferedReader buf = new BufferedReader(new InputStreamReader(System.in)); 
    String s; 
    int input; 
    String name = args[0]; 
    SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss"); 
    Date date = new Date(); 


    System.out.println("Good morning " + name + " Today's date is " + sdf.format(date)); 

    System.out.println("Please enter any number between 0 and 10"); 

    try 
    { 


     do 
     { 
     s = buf.readLine(); 

     input = Integer.parseInt(s); 

     while(input <= 0 || input > 10) 
     { 
      System.out.println("Make sure about the correct input...between 0 and 10 please"); 
      s = buf.readLine(); 
      input = Integer.parseInt(s); 
      System.out.println(input); 
     } 
     }while(s != "x"); 

答えて

3

ちょうどあなたがまだアンドレアスのような例外をキャッチする必要があるので、これは、sが整数であることを保証するものではありませんラインに

s = buf.readLine(); 
if ("x".equals(s)) break; // add this line 

を追加

3

sInteger.parseInt()xに等しいかどうかをチェックするループ(単数または複数)を並べ替えます。 ==または!=ではなく、String.equals()を使用して文字列を比較してください。

これは宿題なので、変更されたコードは掲載しません。

EDIT:

ちょうどString.equals()を使用する理由を説明する:セクションから

15.21.3リファレンス平等演算子==と= Java言語仕様3.0:!

==を使用してString型の参照を比較することができますが、このような等価性テストでは、2つのオペランドが参照するかどうかを判断します同じStringオブジェクトに追加します。オペランドが同じ文字列を含んでいても、別個のStringオブジェクトであれば結果はfalseになります。 2つの文字列sとtの内容は、メソッド呼び出しs.equals(t)によって等しいかどうかをテストできます。

1

if文int型に文字列をペアリングする前に追加します。

if(s.equals("x")) 
     system.exit(1); 

    else{ 
    input = Integer.parseInt(s); 

      while(input <= 0 || input > 10) 
      { 
       System.out.println("Make sure about the correct input...between 0 and 10 please"); 
       s = buf.readLine(); 
       input = Integer.parseInt(s); 
       System.out.println(input); 
} 
2

をのtry..catchブロック内のコードをラップします。

try/catchブロックで
input=-1; 
try{ 
    input = Integer.parseInt(s); 
    while(input <= 0 || input > 10) 
    { 
    System.out.println("Make sure about the correct input...between 0 and 10 please"); 
    s = buf.readLine(); 
    input = Integer.parseInt(s); 
    System.out.println(input); 
    } 
}catch(Exception ex) { } 
.... 
2

ラップInteger.parseInt声明:!whileループに

try { 
input = Integer.parseInt(s); 
} catch{NumberFormatException nfe) { 
System.out.println("Illegal input"); 
// know you could do one of the following: (uncomment) 
// continue;  // would continue the while loop 
// break;   // would exit the while loop 
// System.exit(0); // would exit the application 
} 
2

変更と

while (s != "x") { 
    // your logic 

}

かのかどうか確認を行います=この行の前の「x」:

input = Integer.parseInt(s); 
2

を提案した例外をキャッチ:

s = buf.readLine(); 
if("x".compareToIgnoreCase(s)) { 
    // im quit 
    return; 
}