[英]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);
}
如您所見,無論文本文件中有多少行代碼,最后一行代碼都會被多次打印出來。 有沒有辦法讓這個只打印一次? 提前致謝。
我想您想要做的是僅在您閱讀整個文件后才顯示此錯誤消息。 您可以使用初始化為false
的布爾變量stationFound
,並在找到匹配站時將其設置為true
。 在while 循環之后,您可以檢查stationFound
是否為真,如果不為真,則顯示您的錯誤消息。
請注意,您還可以在找到匹配站后使用break
,以避免在不需要時讀取整個文件。
這是它在代碼中的樣子:
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);
}
如果你想打印一次這個語句並退出循環,你可以添加 break; 在 if 語句之后
else if(!stationName.equalsIgnoreCase(name))
{
System.out.println("No information was found for station " + stationName);
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.