0

I am working on a project for school and I am having a little issue with an IF statement i have made.

it uses a Scanner input and looks for the answer to what the person typed. It doesn't seem to be working however.

public static void remove(){
    System.out.println("Would you like to remove a student? (y/n)");
    input = new Scanner(System.in);
    String answer=input.nextLine();
    if(answer == "y"){
        Scanner idInput = input;
        System.out.println("Please enter a student ID");
        for(int i=idInput.nextInt();i<=studentlist.size();i++){
            if(studentlist.get(i).getId().equals(i)){
                studentlist.remove(i);
                return;
            }
        }
    }
    return;
}

When I enter 'y' (without quotes) into the console it just skips my if logic and returns to the main method.

    Would you like to remove a student? (y/n)
y
Student ID  Recent Grades   Name        E-Mail          Age
1       [88, 79, 59]    John Smith  John1989@gmail.com  0
2       [91, 72, 85]    Suzan Erickson  Erickson_1990@gmailcom  0
3       [85, 84, 87]    Jack Napoli The_lawyer99yahoo.com   0
4       [91, 98, 82]    Erin Black  Erin.black@comcast.net  0
5       [79, 88, 91]    Joshua Selvidge jselvidge@wgu.edu   0
  • Don't compare Strings using `==` or `!=`. Use the `equals(...)` or the `equalsIgnoreCase(...)` method instead. Understand that `==` checks if the two *object references* are the same which is not what you're interested in. The methods on the other hand check if the two Strings have the same characters in the same order, and that's what matters here. – Hovercraft Full Of Eels Jun 23 '16 at 02:29

1 Answers1

0

The problem is not with the IF statement, but with the comparison operator you used. For String, you need to use equals keyword instead of ==

Something like this:

if("y".equals(answer)){
 ...
}

Hope this helps.

Nguyen Tuan Anh
  • 1,036
  • 8
  • 14