-1

I just started reading about JAVA and I want to make a little program that when using Scanner is I type "yes", "no" or just something random I will get different messages.The problem if with the lines:

 if (LEAVE == "yes") {
        System.out.println("ok, lets go");
     if (LEAVE == "no") {
        System.out.println("you dont have a choice");
} else {
        System.out.println("it's a yes or no question");

I receive the error : Operator "==" cannot be applied to "java.util.scanner", "java.lang.String". I saw on a site that it would be better if I replaced "==" with .equals,but I still get an error..

Help please :S

Code below:

package com.company;
import java.util.Scanner;
public class Main {

    public static void main(String[] args) {
        Scanner LEAVE = new Scanner(System.in);

        System.out.println("do you want to answer this test?");
        LEAVE.next();

        System.out.println("first q: would you leave the hotel?");
        LEAVE.next();
        if (LEAVE == "yes") {
            System.out.println("ok, lets go");
        }
        LEAVE.nextLine();
        if (LEAVE == "no") {
            System.out.println("you dont have a choice");
            LEAVE.nextLine();
        } else {
            System.out.println("it's a yes or no question");

        }
    }}
Nir Alfasi
  • 49,889
  • 11
  • 75
  • 119
  • Also: https://stackoverflow.com/questions/11871520/how-can-i-read-input-from-the-console-using-the-scanner-class-in-java – Nir Alfasi Nov 19 '17 at 06:27

1 Answers1

1
Scanner LEAVE = new Scanner(System.in);

Implies that LEAVE is Scanner class object. Right.

if (LEAVE == "yes")

You are comparing the Scanner type object with String type object and hence you are getting

Operator "==" cannot be applied to "java.util.scanner", "java.lang.String"

Now consider

LEAVE.next();

you are calling next() which belongs to LEAVE object. That next function is suppose to read a value and return that to you. So what you do is receive this value in another String type object and then further compare it to 'YES' or 'NO' or whatever.

String response = LEAVE.next()
if(response.equalsIgnoreCase("yes")){
   // do something
}else if(response.equalsIgnoreCase("no")){
   // do something else
}

More about Scanner class GeeksForGeeks

SMagic
  • 197
  • 1
  • 8