简体   繁体   中英

How to break while loop when see empty line in Java?

Write a code that reads a list of student grades from standard input line-by-line until there are no more lines to read or an empty line is encountered.

However, I cannot exit the loop anyway. I tried to write Scanner input = new Scanner(input.hasNext()); and else break but it is not working

public class NumInput {
  public static void main(String [] args) {
    float min = Float.MAX_VALUE;
    float max = Float.MIN_VALUE;
    float total=0;
    int count=0;
    Scanner input = new Scanner(System.in);
    while (input.hasNext()) {

      float val = input.nextFloat();


      if (val < min) {
          min = val;
      }
      if (val > max) {
         max = val;
      }
      count++; 
      total += val ;
    }
    float average = (float) total / count;
    System.out.println("min: " + min);
    System.out.println("max: " + max);
    System.out.println("The Average value is: " + average);
  }
}

Instead of while(input.hasNext()); , try while(input.hasNextFloat()); if it's always going to be a float type.

Also, while(input.hasNextFloat()); will continue reading the user's input until a non float value (or non int value) is entered. So you can enter 1 and 2 and finally q , then because q is not an float / int it'll exit the loop.

A more specific way of solving this would be to do the following:

while(input.hasNextLine()) {
    String command = input.nextLine();
    if(command.equals("")) {
        System.out.println("breaking out of the loop");
        break;
    }
    // rest of the code but make sure to use Float.parseFloat() on the `command`;
}

This documentation has good examples as well as explanation for hasNextFloat() , hasNextLine() , and parseFloat() : http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html

To check empty line you can use nextLine instead of nextFloat then compare with "" , here is working code

import java.util.Scanner;

public class NumInput {
  public static void main(String [] args) {
    float min = Float.MAX_VALUE;
    float max = Float.MIN_VALUE;
    float total=0;
    int count=0;
    Scanner input = new Scanner(System.in);
    String str;
    while (input.hasNextLine()) { 

       str = input.nextLine();
       if(str.equals(""))   //Check if it is empty line then break
           break;
      float val = Float.parseFloat(str);  //Convert string to float


      if (val < min) {
          min = val;
      }
      if (val > max) {
         max = val;
      }
      count++; 
      total += val ;
    }
    float average = (float) total / count;
    System.out.println("min: " + min);
    System.out.println("max: " + max);
    System.out.println("The Average value is: " + average);
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM