-1

I am trying to make a program where I enter the name of a shape and it tells me how many sides it has. I cannot seem to get it to work. Can anyone explain how to do this?

import java.util.Scanner;

public class Shapes {

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

    System.out.print("Enter shape: ");
    shape = reader.next();

    if (shape == "hexagon") {
        System.out.println("A hexagon has 6 sides.");
    }

    if (shape == "decagon"); {
        System.out.println("A decagon has 10 sides.");
    }


  }

}
David
  • 208,112
  • 36
  • 198
  • 279

3 Answers3

0

In Java, you want to use .equals() with a string.

For example:

if(shape.equals("hexagon"))

Since the == operator is asking whether or not the String object shape is exactly the same thing as "hexagon" (which it isn't - hexagon is a constant and shape is an object).

SubSevn
  • 1,008
  • 2
  • 10
  • 27
0

Objects are compared with equals in Java:

if (shape.equals("hexagon")) {
    System.out.println("A hexagon has 6 sides.");
}

Only the value of primitive types (int, long, double, etc.) can be compared with ==. If you compare objects with == you compare the object identity, not the value.

Jimmy T.
  • 4,033
  • 2
  • 22
  • 38
0

Use shape.equals("triangle") in if

The operator, ==, tests to see if two object reference variables refer to the exact same instance of an object.

The method, .equals(), tests to see if the two objects being compared to each other are equivalent -- but they need not be the exact same instance of the same object.

You can use == with primitive types. For String use equals()

SKT
  • 1,821
  • 1
  • 20
  • 32
  • I used the shape.equals("hexagon"). but now when I type in hexagon it gives me both "A hexagon has 6 sides" and "A decagon has 10 sides" – user2744425 Sep 05 '13 at 16:57
  • use if and else if and use .equals() method in both conditions – SKT Sep 05 '13 at 16:59
  • This is what I have and it is still doing the same thing. System.out.print("Enter shape: "); shape = reader.next(); if(shape.equals("hexagon")) { System.out.println("A hexagon has 6 sides."); } else if(shape.equals("decagon")); { System.out.println("A decagon has 10 sides."); } – user2744425 Sep 05 '13 at 17:07