2017-11-29 22 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 etc – 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

인쇄 진술서를 꺼내십시오. – notyou

0

이 while 루프에서 임시 변수를 추가있는 경우 즉

:

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

고마워요! – zetbo