Java - Jak wyrwać się z warunku hasNext ()?
Piszę prosty program do obliczania średniej z zestawu liczb. Otrzymujesz liczby za pomocąScanner
, więc używamwhile
zapętlić z.hasNext()
jako warunek. Jednak pętla jest nieskończona.
Czy możliwe jest wyrwanie się z niego bez zapisania na wejściu jakiegoś słowa, takiego jak „stop”?
public class main {
public static void main(String[] args){
Scanner Input = new Scanner(System.in);
int count = 0;
int temp;
int sum = 0;
while(Input.hasNextInt()){
count++;
temp = Input.nextInt();
sum += temp;
System.out.println(temp);
System.out.println(count);
} // End of while
double average = sum / count;
System.out.println("The average is: " + average);
} // End of method main
}