[英]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. 我有一组双精度值,可以通过调用属于Customer类的方法
getArrivalTime()
来检索它们。 When I run through this while loop, I am unable to print out my output as I cannot exit the loop. 当我运行此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 例如
Inputs: 输入:
0.500
0.600
0.700
I have already included a break;
我已经
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. 或者,您可以在现有代码中使用
hasNextDouble()
代替hasNextLine()
。 It is an error to mix hasNextLine()
and nextDouble()
. 混合
hasNextLine()
和nextDouble()
是错误的。
I guess you are using a Scanner
. 我猜您正在使用
Scanner
。 You are iterating line by line. 您正在逐行进行迭代。 So don't call
nextDouble
but nextLine
then parse your line as Double. 因此,不要调用
nextDouble
而是nextLine
然后将您的行解析为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
: 否则,如果您的文件格式与双
hasNextDouble
模式匹配(取决于您的语言环境...),则可能要使用hasNextDouble
和nextDouble
:
import java.util.Scanner; 导入java.util.Scanner;
public class Snippet { public static void main(String[] args) { 公共类代码段{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! HTH!
If you don't want use goto
like operations you could always add a boolean
flag condition to you while
. 如果您不想使用
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.