使用Scanner方法hasNext()的循环无法循环时,意外退出

时间:2014-11-09 16:03:27

标签: java arraylist while-loop java.util.scanner eof

所以我一直在为学校做作业。它说要制作一个执行以下操作的程序: 1.提示用户输入 2.从用户输入三次,存储为浮动 3.将变量传递给方法minimum(),该方法使用Math.min()来计算最小值。 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。它似乎没有检查输入。有人能告诉我发生了什么吗?

1 个答案:

答案 0 :(得分:0)

你去那里的一个问题可能就是你认为嵌套的while

基本上,一旦内部while循环终止,因为它具有与外部while循环相同的条件,外部循环将执行内部循环和结束括号之间的代码,然后也退出。你自己在代码中的注释中说过 - 一旦给出了EOF,两个循环都会终止。