我如何只在while循环中打印一次语句?

时间:2016-03-29 20:42:58

标签: java 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);
     }

正如您所看到的,最终的代码行将被多次打印出来,因为文本文件中有许多行代码。有没有办法让这个只打印一次? 提前谢谢。

4 个答案:

答案 0 :(得分:4)

我想你想要做的只是在你读完整个文件后才显示这条错误信息。您可以使用初始化为stationFound的布尔变量false,并在找到匹配的工作站时将其设置为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);
}

答案 1 :(得分:-2)

你只需要一个'break'语句来摆脱while循环

像这样:

else if(!stationName.equalsIgnoreCase(name))
 {
    System.out.println("No information was found for station " + stationName);
    break;
 }

答案 2 :(得分:-2)

如果要打印此语句一次并退出循环 你可以加 打破;在if语句之后

type *.out|clip

答案 3 :(得分:-2)

你考虑过插入休息吗?

 else if(!stationName.equalsIgnoreCase(name))
{
    System.out.println("No information was found for station " + stationName);
    break;
}