简体   繁体   中英

Searching for a string in a text file using Java

I am trying to make the user input an Airport Name, and the program will search from a text file to get the matching Code, right now I only need it to read the line. I have looked into many similar questions in here, but nothing works for me. The program return the else result rather than the found result.

This is my code so far

 public static void main (String[] args) throws IOException
 {
  File file = new File("codes01.dat");
  Scanner myFile = new Scanner(file);

  Scanner kb = new Scanner(System.in);

  String line;
  System.out.println("Hey man, this is totally leigt, just enter an Airport code and I'll hook you up.");
  System.out.print("First, y'all need to give me the file name: ");
  String fileName = kb.nextLine();


  if (fileName.equalsIgnoreCase("codes01"))
  {

     System.out.print("Cool, now give me your Airport Name: ");
     String AirportName = kb.nextLine();
   while (myFile.hasNextLine())
    {
     line = myFile.nextLine();
     String name = myFile.next();
     System.out.println(line);
     if(name.equalsIgnoreCase(AirportName))
     {

     System.out.println("IT'S WORKING, I DON'T KNOW HOW BUT IT IS "+line);
     break;
     }

     else
     {
     System.out.println("Sorry, dude, ain't no airport in my VERY limited list with that name");
     break;
     }
   }

  }

The program return the else result rather than the found result.

That is because you are breaking out of the loop after testing the first line in your file.

Look carefully at your code ... in context.

 if(name.equalsIgnoreCase(AirportName)) {
     System.out.println("It is working");
     break;
 } else {
     System.out.println("Sorry");
     break;   // What????
 }

Why are you using the break statement in the if-else block? Try to get rid of the break statement and then execute your code.

if(name.equalsIgnoreCase(AirportName))
{
  System.out.println("The name of Airport matches");
}
else
{
 System.out.println("Sorry No Match Found");
}

Look closely at these two lines. There's a problem there. Step through the code in your head pretending you are the Scanner class.

line = myFile.nextLine();
String name = myFile.next();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM