0

I'm kinda new to Java so I'm looking for an help to do this.

As the title says, I'm trying to write a program that checks if a number given by the user from console is inside a text file with one number for each line or not.

I am using the Scanner class to check every line, but I am having problems with what condition the if statement should have when the number is found inside the file. I wrote down this part code (I'm not even sure if it's correct itself, so correct me if I'm wrong):

int lines = 0;
while (filescanner.hasNextLine()) {
    String line = filescanner.nextLine();
    lines++;
    if(conditon here) {
        System.out.println("I found the number on line " + lines);
    }
}

Thanks in advance.

rghome
  • 8,529
  • 8
  • 43
  • 62
David
  • 1
  • 3
  • `line.contains(value)` You might need to call the `toString()` method on the value – XtremeBaumer Feb 12 '18 at 14:48
  • What is the type of `filesscanner` variable? – curlyBraces Feb 12 '18 at 14:51
  • Where is the part where you let the user input the number ? How do you get the input ? – Exception_al Feb 12 '18 at 14:58
  • @curlyBraces filescanner is a Scanner variable with argument the file variable previously declared(File file=new File() – David Feb 12 '18 at 15:17
  • @Exception_al i let the user input the number with: int number; number=keyboard.nextInt(); the keyboard variable is another Scanner type(Scanner keyboard=new Scanner(System.in) – David Feb 12 '18 at 15:20
  • Possible duplicate of [How do I convert a String to an int in Java?](https://stackoverflow.com/questions/5585779/how-do-i-convert-a-string-to-an-int-in-java) – rghome Feb 12 '18 at 16:21

2 Answers2

0

Since you are getting the input number from Scanner keyboard, you can get its value like this:

String input = keyboard.next();

Then your if condition can be if(line.contains(input))

curlyBraces
  • 1,095
  • 8
  • 12
0

You need to convert the line to an integer and then test it. If it is not an integer the parseInt method throws an exception.

try {
    int n = Integer.parseInt(line);
    if (n == number) {
        // found it
    }
} catch (NumberFormatException e) {
    // Not a number
}
rghome
  • 8,529
  • 8
  • 43
  • 62