0

I've been making a program which reads several strings from a Notepad file which's location is set through user input. Then they enter a string which is in the file, a positive message is shown if it's not then a negative one is shown.

However I can only scan the first string of the file and return whether that's a yes or no. How do I change this code so it scans every string in the file and THEN tell us whether the word is in the file.

public static void main(String[] args)throws IOException {
        // TODO code application logic here

        String phrase, phrase2;
      Scanner fileScan;

      Scanner scan = new Scanner (System.in);

      System.out.println ("Input file:");
      phrase = scan.nextLine();

      fileScan = new Scanner (new File(phrase));

      System.out.println ("Enter string to search for: ");
      phrase2 = scan.nextLine();

      if (fileScan.hasNext(phrase2)) {
      System.out.println("This file does contain the string \"" + phrase2 + "\"");
      }

      else if (phrase != phrase2) {
      System.out.println("This file does not contain the string \"" + phrase2 + "\"");
      }

    }

}

And of course suggest any help/advice you are able to!!

2
Contributors
2
Replies
3
Views
6 Years
Discussion Span
Last Post by javaAddict
0

Just read it back, bad wording and punctuation on first two lines. I'll say them again...

I've been making a program which reads several strings from a Notepad file which's location is set through user input. Then they enter a string AND IF it is in the file; a positive message is shown. If it's not then a negative one is shown.

0

First of all phrase is the input file and phrase2 is the word you want to search. why do you compare them.
Also never compare Strings with == or != . Use: equals:
str1.equals(str2)

Try running this code:

while (fileScan.hasNext()) {
  String line = fileScan.nextLine();
  if (phrase2.equals(line)) {
    System.out.println("This file does contain the string \"" + phrase2 + "\"");
  } else {

  }
}

Or using your code, although I haven't tested:

int i = 1;
while (fileScan.hasNext(phrase2)) {
  System.out.println(i + ": This file does contain the string \"" + phrase2 + "\"");
  i++;
}

Or if you don't want to read the entire file, then use the first version and once the phrase2 is found brake from the loop:

boolean found = false;
while (fileScan.hasNext()) {
  String line = fileScan.nextLine();
  if (phrase2.equals(line)) {
    found = true;
    [B]break;[/B]
  }
}

// use the found variable

Edited by javaAddict: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.