[英]While loop using Scanner method hasNext() fails to loop, exits unexpectedly
所以我一直在做學校作業。 它說要制作一個執行以下操作的程序:1.提示用戶輸入2.從用戶處輸入三次,存儲為浮點數3.將變量傳遞給使用Math.min()計算最小值的方法minimum()。 4.打印結果。5.再次提示用戶並循環播放,直到收到EOF。
好吧,我做到了,但是感覺並不像挑戰。 我已經修改了代碼,以使其不斷提示用戶輸入並將元素添加到ArrayList,該數組傳遞給minimum(),該數組返回一個要打印的浮點數,然后程序應再次提示用戶輸入,並且應該再次循環,直到收到EOF。
// imports
import java.util.Scanner;
import java.lang.Math;
import java.util.ArrayList;
public class FindMin{
public static void main(String args[]){
// define vars
float x;
int iter = 1;
// create new instance of Scanner called input
Scanner input = new Scanner(System.in);
// create new instance of ArrayList called nums with Float elements
ArrayList<Float> nums = new ArrayList<Float>();
// print the instructions and prompt the user for a number
System.out.printf("%s\n %s\n %s\n",
"Type the end-of-file indicator to terminate",
"On UNIX/Linux/Mac OS X type <ctrl> d then press Enter",
"On Windows type <ctrl> z then press Enter");
System.out.print("Enter a number: ");
// loop until EOF, then quit
while(input.hasNext()){ // get user input and exit if input is EOF
// assign input to x, add x as a new element of nums, then prompt user
x = input.nextFloat();
nums.add(x);
iter++;
System.out.print("Enter a number: ");
// loop until EOF, then calculate min
while(input.hasNext()){
x = input.nextFloat();
nums.add(x);
iter++;
System.out.print("Enter a number: ");
} // end while
// calculate min and set iter back to 1
System.out.printf("\n Minimum is: %f\n\n", minimum(nums));
iter=1;
// re-prompt user
System.out.printf("%s\n %s\n %s\n",
"Type the end-of-file indicator to terminate",
"On UNIX/Linux/Mac OS X type <ctrl> d then press Enter",
"On Windows type <ctrl> z then press Enter");
System.out.print("Enter a number: ");
} // end while, should continue looping but doesn't
} // end method main
public static float minimum(ArrayList<Float> n){ // returns a float, takes an ArrayList with <Float> elements
// assigns element at index 0 of n to min
float min = n.get(0).floatValue();
// iterates through i and assigns min to Math.min() called with previous
// value of min and element at index i of n
for(int i=1;i < n.size();i++){
min = Math.min(min, n.get(i).floatValue());
} // end for
return min;
} // end method minimum
} // end class FindMin
問題是外循環意外退出。 據我了解,input.hasNext()會提示用戶輸入,如果有輸入,則返回true,否則返回false。 它似乎似乎不檢查輸入。 有人可以告訴我發生了什么事嗎?
你已經去那里很可能做什么你認為一個問題是嵌套的while
秒。
基本上,一旦內部while循環終止,因為它與外部while循環具有相同的條件,則外部循環將在內部循環和結束括號之間執行代碼,然后也退出。 您在代碼的注釋中自己說了這一點-給出EOF后,兩個循環都會終止。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.