2017-08-11 32 views
1

此刻,我將方法reader.nextInt()調用兩次,因此它僅對每個其他值使用addNumber()方法,而不是每個值。需要調用掃描器方法read.nextInt()兩次,但要求兩個值相同

我該如何解決這個問題?

我試過使用while循環包含(true)以及下面打印的,都遇到相同的問題。

我忘了提,我需要程序打印輸入的所有整數的總和。這是通過輸入-1的值來觸發的。 -1意味着從總和中排除。

import java.util.Scanner; 

public class Main { 
    public static void main(String[] args) { 
    NumberStatistics stats = new NumberStatistics(); 
    Scanner reader = new Scanner (System.in); 

    System.out.println("Type numbers:"); 

    while (reader.nextInt() != -1) {    
     stats.addNumber(reader.nextInt()); 
    } 

    System.out.println("sum: " + stats.sum()); 

    } 
} 

public class NumberStatistics { 

private int amountOfNumbers; 
private int sum; 

    public NumberStatistics() { 
    amountOfNumbers = 0; 
    sum = 0; 
    } 

    public void addNumber(int number) { 
    this.amountOfNumbers++; 
    this.sum += number; 
    } 

    public int amountOfNumbers() { 
    return this.amountOfNumbers; 
    } 

    public int sum() { 
    return this.sum; 
    } 

    public double average() { 

    if (this.sum() == 0) { 
     return 0; 
    } 
    else { 
     return (double) this.sum/this.amountOfNumbers; 
    } 
    } 
} 
+3

請將代碼在這裏!!!! –

+0

[Scanner在使用next(),nextInt()或其他nextFoo()之後跳過nextLine()?](https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after- using-next-nextint-or-other-nextfoo) –

+0

@KenReid你在哪看到這兩個問題之間的聯繫? – Tom

回答

2

要調用兩次nextInt(),因此閱讀量擬合選取一前一後。

你可以做你想做這樣的東西:

int num; 
while ((num = reader.nextInt()) != -1) { 
    stats.addNumber(num); 
} 

這使得使用的事實,即賦值表達式(這一點:num = reader.nextInt())不僅並將值num,但ASLO評估爲被分配值,以便我們可以將其與-1進行比較。

+0

你祝福親切的人,我可以吻你,謝謝! –

+0

@DanielCutter如果您認爲答案可以解答您的問題,請考慮點擊該選中標記來接受答案! – Sweeper

+0

@Sweeper你應該添加一個關於發生了什麼的簡短解釋恕我直言,這將更清楚如果有人檢查它! :D無論如何得到你的upvote,你比我更快:( – Nathan

2

這裏的問題是,掃描儀將跳轉到下一個令牌的nexInt()每次調用,這就是爲什麼你會得到下面的編號,而跳過預期之一。

所以不要在你的while條件中使用nextInt(),使用hasNextInt()代替。

所以,你的代碼應該是這樣的:

int next; 
while (reader.hasNextInt() && (next = reader.nextInt()) != -1){ 
    stats.addNumber(next); 
} 
+0

或者,也可以將結果保存在變量中,以繞過調用'Scanner'方法來第二次訪問結果。 – Zabuza

+0

@Zabuza是的,但這可能會降低性能,並可能導致NPE。 –

+1

但是,這將接受'-1'作爲有效的輸入,OP的原始不是。 – Sweeper

1

當您調用nextInt()時,掃描器中的指針將解析int,然後轉到下一個元素。所以基本上,你有:

pointer 
    | 
    | 
    12345  12346 12347 

while (nextInt() ...) // pointer moves to next int 

      pointer 
      | 
      | 
    12345  12346 12347 

stats.addNumber(reader.nextInt()); // Now the pointer is already at the next one 

所以你正在閱讀他們兩個兩個。你可以通過這樣做來糾正:

int a; 
while ((a = reader.nextInt()) != -1) 
    stats.addNumber(a); 

這樣,Reader#nextInt方法只被調用一次。