2016-05-15 11 views
0

forループを2度目に実行すると、現在NoSuchElementExceptionが表示されます。自分のコードを変更する前に問題なくループすることができました。このクラスの同じScannerオブジェクトを使用して、その入力を読み取る代わりに、メソッドsetRiskAmount()のユーザー入力を移動する必要がありました。それが私がエラーを得るのを開始したときです。 Scannerから何も読み込めないときに例外がスローされることは知っていますが、なぜこのシナリオでどうやってコードを調整するのかが分かりません。Scannerオブジェクトを使用してループ内で反復処理中にNoSuchElementExceptionが発生する

更新: setRiskAmount()のメソッドですべてのコードを削除してもエラーは発生せず、次の繰り返しでユーザーの入力を読み取ることができます。私は別のやり方でやっていたし、完璧にうまくいった。私は自分のアプリケーションの特定の要件を満たすために変更を加えました。

@Override 
void setRiskAmount() { 
    // Ask for user input using a Scanner 

    Scanner input = new Scanner(System.in); 
    System.out.print("Please enter risk amount for Property Insurance >> "); 
    riskAmount = input.nextFloat(); 
    input.close(); 
} 

入力してください保険の種類(プロパティ、オート、旅行)または

財産財産保険のリスク量を入力してください>> 25000 を終了するには、QUIT ****** ************ PROPERTY INSURANCEレートは:0.25リスク量は25000.0です。不動産保険の保険料は:6250.0 ***************** *保険タイプ(プロパティ、オート、トラベル)を入力してください。終了するには、終了してください。>>スレッド "メイン"の例外 java.util。 NoSuchElementException: UseInsurance.main(UseInsurance.java:25)で java.util.Scanner.nextLine(不明なソース)で見つかりませんでした行が

public class UseInsurance { 

    public static void main(String[] args) { 
     // The Scanner object will be used for user input 
     Scanner input = new Scanner(System.in); 

     String t = ""; 

     // Create the user interface 
     // Loop will continue looping until the user decides to exit 
     for (int i = 10; i > 0; i++) { 
      System.out.println("Please enter insurance type (Property, Auto, Travel) or QUIT to exit >> "); 
      t = input.nextLine(); 
      if (t.equals("Property")) { 
       // Create an instance of PropertyInsurance, set the object name and type, ask for user input for risk amount 
       // calculate and add to the total quote. Display the results. 

       PropertyInsurance pInsurance = new PropertyInsurance("Property"); 
       pInsurance.setInsuredObjectName(); 
       pInsurance.setRiskAmount(); 
       InsuranceAgentApp.totalPremium += pInsurance.getPremium(); 
       pInsurance.display(); 
      } else if (t.equals("Auto")) { 
       // Create an instance of AutomobileInsurance, set the object name and type, ask for user input for risk amount 
       // calculate and add to the total quote. Display the results. 
       AutomobileInsurance aInsurance = new AutomobileInsurance("Auto"); 
       aInsurance.setInsuredObjectName(); 
       aInsurance.setRiskAmount(); 
       InsuranceAgentApp.totalPremium += aInsurance.getPremium(); 
       aInsurance.display(); 
      } else if (t.equals("Travel")) { 
       // Create an instance of TravelInsurance, set the object name and type, ask for user input for risk amount 
       // calculate and add to the total quote. Display the results. 
       TravelInsurance tInsurance = new TravelInsurance("Travel"); 
       tInsurance.setInsuredObjectName(); 
       tInsurance.setRiskAmount(); 
       InsuranceAgentApp.totalPremium += tInsurance.getPremium(); 
       tInsurance.display(); 
      } else if ((t.equals("QUIT")) || (t.equals("quit")) || (t.equals("Quit"))) { 
       // Exit the loop upon the user typing QUIT, quit or Quit 

       break; 
      } else { 
       // If none of the above options are selected, display a message 
       // and loop again. 

       System.out.println("Invalid input"); 
      } 
     } 

     // Display the amount of the total quote 
     System.out.println("The total quote is " + InsuranceAgentApp.totalPremium); 
     // Close the Scanner object 
     input.close(); 

    } 

} 

答えて

0

問題がsetRiskAmount()です。 System.inからのScannerを閉じると、その特定のScannerを閉じるだけでなく、System.inも閉じます。これにより、メインメソッド内のScannerSystem.inからの入力を読み取ることができなくなります。

解決策は、これを閉じる行を単に削除することです。Scanner。後でコード内でSystem.inから入力を読み取らなければならない可能性がある場合は、System.inからのScannerの読み取りを決して閉じないでください。

+0

これを行いました。ありがとうございました! – user2057488

1

問題は、引用符の後に入力を閉じているだけで、その行を削除するだけです。また、より洗練され、より統合されているので、あなたのためにうまくいくかもしれないコードがいくつか含まれています。私は何をしたのかを説明するコメントを残しました。それは1000%に動作します

 Boolean done = false; //Boolean variable to monitor loop without increments 

     // Create the user interface 
     // Loop will continue looping until the user decides to exit 
     while(!done){ 
      System.out.println("Please enter insurance type (Property, Auto, Travel) or QUIT to exit >> "); 
      t = input.nextLine(); 
      t = t.toUpperCase();//normalizes the string to all upercase letters 
      switch(t){ 
       case "PROPERTY": 
        //your code 
       case "AUTO": 
        //your code 
       case "TRAVEL": 
        //your code 
       case "QUIT": 
        done = true;//loop wil exit when done is true 

       default: 
        System.out.println("Invalid Input"); 
        } 


     } 
+0

't = input.nextLine()。toUpperCase();'で十分です。 2つの別々の行に分割する必要はありません。 –

+0

@Bethany Louiseなぜ私はそれを考えたのか分からない。ありがとう! – sbowde4

0
public class Test { 
static float riskAmount; 
static Scanner input = new Scanner(System.in); 
public static void main(String[] args) { 
    for (int i = 0; i < 10; i++) { 
     setRiskAmount(); 
     if(i==9){ 
      System.out.println("Total Risk Amount is: "+ riskAmount); 
     } 
    } 
} 
static void setRiskAmount() { 
    System.out.print("Please enter risk amount for Property Insurance >> "); 
    riskAmount+= input.nextFloat(); 
} } 

私はあなたのためにそれを行います。 Scannerをグローバルに宣言するだけです。

+0

最後の操作の後にスキャナを閉じることができます。 System.out.println( "Total Risk Amountは" + riskAmount ")などです。 input.close(); –

0
public class Test { 
static float riskAmount; 
static Scanner input = new Scanner(System.in); 
public static void main(String[] args) { 
    for (int i = 0; i < 10; i++) { 
     setRiskAmount(); 
     if(i==9){ 
      System.out.println("Total Risk Amount is: "+ riskAmount); 
      input.close(); 
     } 
    } 
} 
static void setRiskAmount() { 
    System.out.print("Please enter risk amount for Property Insurance >> "); 
    riskAmount+= input.nextFloat(); 
} } 
関連する問題