簡體   English   中英

如何打破涉及hasNextLine()的while循環?

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

我有一組雙精度值,可以通過調用屬於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;
      }
}

例如

輸入:

0.500
0.600
0.700

我已經break; 在循環的末尾。 還有什么可以做的?

如果您將輸入讀取為字符串,然后將其解析為雙精度字,則可以在空白行上使循環中斷。

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

或者,您可以在現有代碼中使用hasNextDouble()代替hasNextLine() 混合hasNextLine()nextDouble()是錯誤的。

我猜您正在使用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);
            }
        }
    }
}

否則,如果您的文件格式與雙hasNextDouble模式匹配(取決於您的語言環境...),則可能要使用hasNextDoublenextDouble

導入java.util.Scanner;

公共類代碼段{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!

如果您不想使用goto類的操作,則可以while始終向您添加boolean標志條件。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM