-3

So I'm currently just messing around with classes and objects to fully understand how it works, and tried to create a tiny search engine that would give information based on user input. The user basically has to enter the name of an animal (so far only 2 animals added).

I tried creating an if statement, so that if the input == animal (for instance a dolphin) it would spit out information on the dolphin. It won't recognize the "animal" in dolphin.animal, and I cannot seem to understand the issue.

Any help would be appreciated! Here's my code:

package Zoo;

import java.util.Scanner;

public class Animals {

    //instance fields
    String Name;
    String Animal;
    String Color;
    int AgeYear;
    String FavoriteFood;


    //constructor method
    public Animals(String name, String animal, String color, int ageYear, String favoriteFood) {
        Name = name;
        Animal = animal;
        Color = color;
        AgeYear = ageYear;
        FavoriteFood = favoriteFood;
    }

    //main method
    public static void main(String[] args) {
        Animals dolphin = new Animals("Gretha", "dolphin", "gray", 2, "salmon");
        Animals orangutan = new Animals("Peter", "orangutan", "black", 15, "bananas");


        System.out.println("Please enter the name of an animal to view information regarding said animal.");
        Scanner input = new Scanner(System.in);
        input.nextLine();

        if(input == dolphin.animal)  {
            System.out.println(dolphin.Animal + dolphin.Name + dolphin.AgeYear + dolphin.Color + dolphin.FavoriteFood);

        }


    }
}

EDIT: yes I'm aware that the outprint is unfinished, but that I can fix afterwards of course

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
bdrdrdr
  • 1
  • 2

2 Answers2

0
if(input == dolphin.animal) 

should be

if (input == dolphin.Animal)

also you have to assign the result of input.nextLine() to a variable and then compare that variable with dolphin.Animal

vincendep
  • 528
  • 4
  • 10
0

javadoc is your friend. Method nextLine() in class Scanner returns a String. You need to save that value in a variable, for example using this code:

String theName = input.nextLine();

Then you need to use method equals() to see if theName equals "dolphin", i.e.

if (theName.equals(dolphin.Animal)) {
   // print the details
}

By the way, if you adhere to the java naming conventions you make it easier for others to read and understand your code.

Abra
  • 19,142
  • 7
  • 29
  • 41