2017-11-29 4 views
1

ファイルにある整数の追加に問題があります。コードは、整数を表示するが、 "total + = scanner.nextInt();" (例えば10,20,30,40,50を含むファイルが10,30,50のみを表示し、合計が60(?)を表示する場合など)他のすべての整数をスキップし、NoSuchElementExceptionを返します。私はここで間違って何をしていますか?Java - ファイルから整数を追加する

import java.io.File; 
import java.io.IOException; 
import java.util.InputMismatchException; 
import java.util.NoSuchElementException; 
import java.util.Scanner; 

public class AddingInts { 

    public static void main(String[] args) { 

     File myFile = new File("ints.txt"); 
     Scanner scanner = null; 
     int total = 0; 

     System.out.println("Integers:"); 

      try { 
       scanner = new Scanner(myFile); 

       while (scanner.hasNextInt()) { 
        System.out.println(scanner.nextInt()); 
        //total += scanner.nextInt(); 
       } 

      } 
      catch (IOException ex) { 
       System.err.println("File not found."); 
      } 
      catch (InputMismatchException ex) { 
       System.out.println("Invalid data type."); 
      } 
      catch (NoSuchElementException ex) { 
       System.out.println("No element"); 
      } 
      finally { 
       if (scanner != null) { 
        scanner.close(); 
       } 
      } 

      System.out.println("Total = " + total); 
     } 

} 
+0

あなたが最初のintを印刷し、次を割り当てているのでint等 – notyou

答えて

1

最初のprint文でscanner.nextInt()を呼び出すと、次の番号にインデックスが付けられます。だから、あなたはそれをもう一度呼び出すと、単に値をスキップするだけです。あなたは10、20、30

System.out.print(scanner.nextInt())// performs nextInt() which prints 10 and moves to 20 
total += scanner.nextInt(); //will use the value of 20 instead of 10 because you are currently at 20 and moves the pointer to 30 
+1

今問題を解決するために何をする必要があるかを表示 –

+0

ありがとう!では、それらを一緒に追加する最良の方法は何でしょうか? – zetbo

+1

あなたのprintステートメントを取り出してください。 – notyou

0

があなたのwhileループで一時変数を追加している場合は言い換えれば

  while (scanner.hasNextInt()) { 
       int cur = scanner.nextInt(); 
       System.out.println(cur); 
       total += cur; 
      } 
+0

ありがとうございました! – zetbo

関連する問題