0

I'm a beginner at java and I just recently started to study interfaces so I triead to make a program that had classes which implemented intefaces. Anyways, i ran into a problem with the while loop in my program. I'm tryng to give the user the opportunity to choose between talking to a robor or a person, and as far as i understand && checks for both of the conditions (If either one of them is true it runs the loop).

import java.util.Scanner;
public class App {

public static void main(String[] args) {
    Scanner ai = new Scanner(System.in);
    Conversation guy = new Human();
    Conversation rox = new Robot();
    System.out.println("What do you want to talk to?");
    String choice = ai.nextLine();
    while (choice != "Robot" && choice!= "Person"){
        System.out.println("Option not available, choose again.");
        choice = ai.nextLine();
    }
    switch(choice){
    case "Person":
        System.out.println("What's my name?");
        guy.greet();
        guy.conv();
        guy.bye();
        break;
    case "Robot":
        System.out.println("What's my name?");
        rox.greet();
        rox.conv();
        rox.bye();
        break;
    }
    ai.close();

    }
}

I'm trying to make it so that if the input is neither "Person" or "Robot" it scans again for new input but despite the input being either one the program always runs the loop, Why?

Diego Perozo
  • 67
  • 1
  • 5

1 Answers1

0

You are comparing Objects (String) using == which compares references here:

choice != "Robot" && choice!= "Person"

You need to use the .equals() method to compare Strings meaningfully

Kon
  • 10,702
  • 6
  • 41
  • 58
  • thanks that solved. I'm still trying to get myhead around the difference between using `==` and `.equals()` but it worked so thanks. – Diego Perozo Apr 19 '15 at 19:12
  • @DiegoPerozo `==` compares Object references, to see if they are pointing to the same actual object in memory. `.equals()` is a method in the `Object` class which is therefore inherited by all classes. You can implement it however you want. For the `String` class, the developers have implemented a meaningful `.equals()` which compares all the characters in the String to the target String and returns true only if they match. – Kon Apr 19 '15 at 19:24
  • That's the drawback of not having String as a primitive type. – Tarik Apr 20 '15 at 00:18