如何突破涉及hasNextLine()的while循环?

问题描述 投票:1回答:3

我有一组double值,可以通过调用属于Customer类的方法getArrivalTime()来检索它们。当我经历这个while循环时,我无法打印输出,因为我无法退出循环。

while (sc.hasNextLine()) {

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

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

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

EG

输入:

0.500
0.600
0.700

我已经在循环结束时包含了一个break;。还能做什么?

java while-loop infinite
3个回答
2
投票

如果您将输入作为字符串读取,然后将它们解析为双精度数,则可以在空行上从循环中进行此中断。

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

或者,您可以在现有代码中使用hasNextDouble()而不是hasNextLine()。混合hasNextLine()nextDouble()是错误的。


0
投票

我想你正在使用Scanner。你是逐行迭代的。因此,不要调用nextDouble,但nextLine然后将你的行解析为Double。

这是一个简化版本:

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);
            }
        }
    }
}

否则,如果您的文件格式与双重模式匹配(这取决于您的Locale ...),您可能希望将hasNextDoublenextDouble一起使用:

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!


0
投票

如果您不想使用goto之类的操作,您可以随时添加boolean标志条件给你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;
      }
}
© www.soinside.com 2019 - 2024. All rights reserved.