0

I'm working on my university homework and i have faced this problem. What i need to accomplish is when the user inputs a metallic element of either zinc, iron, aluminum and sodium i want the program to return true. When the element which is compared is true, the boolean still outputs false. Can you please identify the problem in this code?

class IonicCompound

public class IonicCompound {

    public static void main(String args[]) {
        Scanner input = new Scanner(System.in);
        System.out.println("Please enter a metallic element: ");
        String element1 = input.nextLine();
        System.out.println("Please enter a non-metallic element: ");
        String element2 = input.nextLine();
        Elements element = new Elements(element1, element2);
        element.isMetal(element.first);
        if (element.isMetal(element.first) == true) {
            System.out.println("It's a metallic element ");
        } else {
            System.out.println("It's not a metallic element ");
        }
    }
}

class Elements

public class Elements {

    public String first, second;

    public Elements(String f, String s) {
        first = f;
        second = s;
    }

    public boolean isMetal(String ff) {
        if (ff == "iron" || ff == "Iron" || ff == "aluminium" || ff == "Aluminium" || ff == "sodium" || ff == "Sodium" || ff == "zinc" || ff == "Zinc") {
            return isMetal(ff) == true;
        } else {
            return false;
        }
    }

    public String toString() {
        String element = first + " " + second;
        return element;
    }
admdrew
  • 3,790
  • 4
  • 27
  • 39
totovic
  • 25
  • 2
  • 2
    Don't compare strings with `==`. See: [How do I compare strings in Java?](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java/513839) – Jesper Oct 30 '14 at 21:09

3 Answers3

2

You're calling isMetal from inside isMetal, so you're recursing indefinitely. I think what you want is simply return true;

Also, take a look at function String.equals. The == operator probably isn't doing what you expect in Java.

admdrew
  • 3,790
  • 4
  • 27
  • 39
John Lockwood
  • 3,787
  • 29
  • 27
2

To compare strings use the String API equals method. Below is an example that can be applied in your code:

ff.equals("iron") // This compares if String contain the same series of characters

ff=="iron" // this compares if the memory address of the ff variable is "iron"
Rami Del Toro
  • 1,130
  • 9
  • 24
1

Use .equals() as opposed to == when comparing objects (Strings are objects). == will compare the objects' references, whereas .equals() will check to see if they have the same values. Since two objects will very rarely have the same reference you should never use == except for comparing primitive types (int, char, but String is not a primitive type!) where it doesn't matter.

So you want

ff.equals(iron)
Zach
  • 4,652
  • 18
  • 22