0

try最初にステートメントをwhileループに入れようとしましたが、いくつかのエラーが発生しました。プログラムは、不規則な文字を入力すると、作成した印刷行が表示されることを除いて完全に実行されますが、別の行を再度入力すると、行がポップアップせず、フォーマット例外エラーが発生します。

AddNumbersrealone2.java

import java.io.*;

// create the class
public class AddNumbersrealone2
{
    // allows i/o
  public static void main (String [] args) throws IOException
  {   // initalize variables and strings
    BufferedReader myInput = new BufferedReader  (new InputStreamReader (System.in));
    String sumNumbers;
    //String go;
    double num ;
    double total = 0.0;

    // asks user questions and instructions
    System.out.println("Hello, the following program will ask for your input of a number ");
    System.out.println("Each time you input a number a running total will be added to each previous number")  ;
    System.out.println("Once ready input a number to start!");
    // try and catch block      
    try {

      num = 0;

      // while statement if this occurs stop the program, in this case if a negative integer is inputted

      while (num >= 0) {

        // Contious question asked  
        System.out.println("Input another number..."); 
        sumNumbers = myInput.readLine();
        num = Double.parseDouble (sumNumbers);

        // calculates number (Running total)
        total = total + num;
        System.out.println(total);

        // end error trap
      }
    }
    catch  (Exception e){
      System.out.println("Please refrain from entering regular characters!");
      num = 0;

      // re- while statement if this occurs stop the program, in this case if a negative integer is inputted

      while ( num >= 0) {

        // input question after a character is inputted
        System.out.println("Please input a number: ");
        sumNumbers = myInput.readLine();
        num = Double.parseDouble (sumNumbers);

        total = total + num;
        System.out.println(total);

        // ending statement
      }
    }
    System.out.println("You entered a negative number, the program will exit now");
    System.out.println("Good-bye!");

    // Complete class body
  }
}
4

2 に答える 2

2

Double.parseDouble の周りで例外をキャッチする何かが必要です

例えば。

 while(num >= 0)
    {
    // input question after a character is inputted
       System.out.println("Please input a number: ");
       sumNumbers = myInput.readLine();
       try{
            num = Double.parseDouble (sumNumbers);
            total = total + num;
            System.out.println(total);
       } catch(Exception e)
       {
            System.out.println("Please enter a proper number");
       }    


            // ending statement
  }
于 2013-02-26T21:33:46.917 に答える
0

問題は、最初の例外がスローされるとすぐに、プログラムがcatchステートメント内のwhile()ループ内に巻き込まれることです。したがって、別の無効な入力が入力された場合、try-catchステートメントがないその2番目のwhileループで処理されます。良い修正は、tryステートメントにnum = Double.parseDouble(sumNumbers);と言う行だけを含めることです。例外をキャッチしたら、続行して終了します。プログラムが最初をループバックして別の入力を要求するようにステートメントを記述します。

于 2013-02-26T21:32:46.457 に答える