0

How can I use object inside if statement I tried 2 ways one like this:

import java.util.Scanner;

public class Species{

String kind;

public void talk() { System.out.println(kind + " is talking");}
public void walk() { System.out.println(kind + " is walking");}
public void swim() { System.out.println(kind + " is swimming");}
public void check() { 

    if (kind == "woman") {talk(); walk();}
    else if (kind == "fish") {swim();}
    else System.out.println("Sorry not one of our option.");
}

public static void main(String [] args) {

    Scanner read = new Scanner (System.in);

    Species sp1 = new Species();

    sp1.kind = null ;

    System.out.print("Enter a kind: ");
    sp1.kind = read.nextLine();

    sp1.check();

}} 

And another one:

import java.util.Scanner;

public class Species{

String kind;

public void talk() { System.out.println(kind + " is talking");}
public void walk() { System.out.println(kind + " is walking");}
public void swim() { System.out.println(kind + " is swimming");}


public static void main(String [] args) {

    Scanner read = new Scanner (System.in);

    Species sp1 = new Species();

    sp1.kind = null ;

    System.out.print("Enter a kind: ");
    sp1.kind = read.nextLine();

    if (sp1.kind == "woman") {sp1.talk(); sp1.walk();}
    else if (sp1.kind == "fish") {sp1.swim();}
    else System.out.println("Sorry not one of our option.");        


}}

Each time it shows the message Sorry not one of our option I know it's a simple program but it wouldn't work

Njood
  • 1
  • 2
  • 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 Feb 01 '20 at 02:36
  • Side note: learn Java code formatting standards and follow them as they help other people (such as *us*) to more easily understand your code – Hovercraft Full Of Eels Feb 01 '20 at 02:37

0 Answers0