[英]How do I only print statement once in a while loop?
{
System.out.println("Enter input file name:");
Scanner keyboard = new Scanner(System.in);
String fileName = keyboard.nextLine();
File read = new File(fileName);
Scanner inputFile = new Scanner(read);
if(read.length() == 0)
{
System.out.println("empty file");
return;
}
inputFile.useDelimiter(":");
String name, code, line, distance;
System.out.println("Enter station name");
String stationName = keyboard.nextLine();
while(inputFile.hasNextLine())
{
name = inputFile.next();
code = inputFile.next();
line = inputFile.next();
distance = inputFile.nextLine();
if(stationName.equalsIgnoreCase(name))
{
System.out.println("Station code: " + code + " name: " + name);
System.out.println("distance " + distance + " kms, is on the " + line + " line");
}
else if(!stationName.equalsIgnoreCase(name))
{
System.out.println("No information was found for station " + stationName);
}
As you can see the final line of code will be printed out multiple times for however many lines of code there are in the text file.如您所见,无论文本文件中有多少行代码,最后一行代码都会被多次打印出来。 Is there any way to make this only print once?
有没有办法让这个只打印一次? Thanks in advance.
提前致谢。
I guess what you want to do is to display this error message only once you have read the entire file.我想您想要做的是仅在您阅读整个文件后才显示此错误消息。 You could use a boolean variable
stationFound
initialized to false
and that you set to true
when you found a matching station.您可以使用初始化为
false
的布尔变量stationFound
,并在找到匹配站时将其设置为true
。 After your while loop, you can then check if stationFound
is true, and if not display your error message.在while 循环之后,您可以检查
stationFound
是否为真,如果不为真,则显示您的错误消息。
Note that you can also use a break
once you have found a matching station to avoid reading the whole file when not needed.请注意,您还可以在找到匹配站后使用
break
,以避免在不需要时读取整个文件。
Here is what it would look like in code:这是它在代码中的样子:
boolean stationFound = false;
while(inputFile.hasNextLine())
{
// ...
if(stationName.equalsIgnoreCase(name))
{
System.out.println("Station code: " + code + " name: " + name);
System.out.println("distance " + distance + " kms, is on the " + line + " line");
stationFound = true;
break;
}
}
if(!stationFound)
{
System.out.println("No information was found for station " + stationName);
}
If you want to print this statement once and exits the loop you can add break;如果你想打印一次这个语句并退出循环,你可以添加 break; after the if statement
在 if 语句之后
else if(!stationName.equalsIgnoreCase(name))
{
System.out.println("No information was found for station " + stationName);
break;
}
Have you considered inserting a break?你有没有考虑插入休息?
else if(!stationName.equalsIgnoreCase(name))
{
System.out.println("No information was found for station " + stationName);
break;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.