简体   繁体   中英

How to break out of while loop that involves hasNextLine()?

I have a set of double values, and they can be retrieved by calling the method getArrivalTime() which belongs to the Customer class. When I run through this while loop, I am unable to print out my output as I cannot exit the loop.

while (sc.hasNextLine()) {

      Customer customer = new Customer(sc.nextDouble());

      String timeToString = String.valueOf(customer.getArrivalTime());

      if (!(timeToString.isEmpty())) {
        c.add(customer);
      } else {
        break;
      }
}

eg

Inputs:

0.500
0.600
0.700

I have already included a break; at the end of the loop. What else can do?

You could make this break from the loop on a blank line if you read the input as strings and then parse them into doubles.

while (sc.hasNextLine()) {
    String line = sc.nextLine();
    if (line.isEmpty()) {
        break;
    }
    c.add(new Customer(Double.parseDouble(line)));
}

Alternatively you could use hasNextDouble() instead of hasNextLine() in your existing code. It is an error to mix hasNextLine() and nextDouble() .

I guess you are using a Scanner . You are iterating line by line. So don't call nextDouble but nextLine then parse your line as Double.

Here's a simplified version :

import java.util.Scanner;

public class Snippet {
    public static void main(String[] args) {

        try (Scanner sc = new Scanner("0.500\r\n" + "0.600\r\n" + "0.700");) {
            while (sc.hasNextLine()) {
                String line = sc.nextLine();
                double customer = Double.parseDouble(line);
                System.out.println(customer);
            }
        }
    }
}

Otherwise, if your file format matches the double pattern (it depends on your Locale...), you may want to use hasNextDouble with nextDouble :

import java.util.Scanner;

public class Snippet { public static void main(String[] args) {

    try (Scanner sc = new Scanner("0,500\r\n" + "0,600\r\n" + "0,700");) {
        while (sc.hasNextDouble()) {
            double customer = sc.nextDouble();
            System.out.println(customer);
        }
    }
}

}

HTH!

If you don't want use goto like operations you could always add a boolean flag condition to you while .

boolean flag = true;
while (sc.hasNextLine() && flag) {

      Customer customer = new Customer(sc.nextDouble());

      String timeToString = String.valueOf(customer.getArrivalTime());

      if (!(timeToString.isEmpty())) {
        c.add(customer);
      } else {
        flag = false;
      }
}

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