jeudi 29 août 2019

My if-statement won't work when passing in a Scanner value? [duplicate]

This question already has an answer here:

I'm trying to use a Scanner to read an input from the user. The input should be '+', '-', '*' or '/'. For some reason, whenever I try and pass this input into my if-statement, it doesn't read, instead stopping all input, saying my program is no longer running.

I've tried figuring out exactly what the Scanner is being passed, but I can't really find anything suggesting it's not just a string.

import java.util.Scanner;

public class TestIfStatements{

public static void main(String[] args){
    Scanner sc = new Scanner(System.in);
    System.out.print("Enter the operation: *, +, -, and /: ");
    if (sc.nextLine() == "+"){
        System.out.println("Hello");
    }
}

}

It should be printing "Hello" on an input of "+" but it's not. Instead, it says my program has stopped running.

Aucun commentaire:

Enregistrer un commentaire