pimpvader pimpvader - 1 month ago 6
Java Question

Coding with Java Eclipes

I need to make a program where a user can input a name, and the program will search through the file line by line until it has a match, then return all the match. So this is what i Have, I got the file into the program, but cant seem to code the program to search the file for the user input. Any help?

Assignment: this what the code has to be able to do.

read in each row, parse out the name part, perform a match on names, if match return full name, else move to next row. Have message if you reach the end without a match.

import java.util.Scanner;
import java.io.*;

public class USpres {
public static void main(String[] args) throws FileNotFoundException {

File file = new File ("USPres.txt");
Scanner kb = new Scanner(System.in);
Scanner scanner = new Scanner(file);

System.out.println("Please enter the name you would like to search for: ");
String name = kb.nextLine();

while (scanner.hasNextLine())
{

if(scanner.nextLine() == kb)
{
System.out.println("I found " +name+ " in file " +file.getName());

}
break;

Answer
if(scanner.nextLine() == kb)
{ 
    System.out.println("I found " +name+ " in file " +file.getName());

}

should become

if(scanner.nextLine().equalsIgnoreCase(name))
{ 
    System.out.println("I found " +name+ " in file " +file.getName());

}

just like they said above in the comments. Also, .equals() is meant to compare two Objects, not two strings. Since they are both strings, you may have success with this method, but I would suggest always using .equalsIgnoreCase() when comparing Strings.