-1

I'm currently working on a financial planning app for class but I cant get a loop with a condition inside it to work. It just keeps looping despite the condition - it's almost as if the condition is being ignored completely.

Here's my code - please help!

while (true){
        Scanner scanVar = new Scanner(System.in);
        System.out.println("\nEnter expenditure item: ");
        String myString = scanVar.nextLine();
        Scanner scanVar2 = new Scanner(System.in);
        System.out.println("\nEnter expenditure value: ");
        double myDouble = scanVar2.nextDouble();
        expenditureMap.put(myString, myDouble);
        Scanner scanVar3 = new Scanner(System.in);
        System.out.println("\nAnother item? ");
        String myString2 = scanVar3.nextLine();
            if (myString2 == "yes") {
                continue;
            }
            else {
                break;
            }
    }

Many thanks, Dylan

  • 1
    WRONG: "string1 == string2". CORRECT: string1.equals(string2). [Java String.equals versus ==](http://stackoverflow.com/questions/767372/java-string-equals-versus) – paulsm4 Sep 18 '13 at 18:24

4 Answers4

1

You really want to be using mystring2.equals("yes") (or even better, "yes".equals(mystring2) )

The == operator on objects tests for them being the identical instance, not the same string values....

String a = new String("yes");
String b = new String("yes");

a == b => false
a.equals(b) => true
Ankit
  • 6,554
  • 6
  • 49
  • 71
rolfl
  • 17,539
  • 7
  • 42
  • 76
0

If you are using the == operater it is comparing if the object references match. You should use the equals operator

if (myString2.equals("yes"))
Chris Hinshaw
  • 6,967
  • 2
  • 39
  • 65
0

change the condition as follows and then try:

if (myString2.equals("yes")) {
Ahsan Shah
  • 3,931
  • 1
  • 34
  • 48
0

You shall use equals ... check this post

How do I compare strings in Java?

reference comparison means checking if both objects have the same address in memoery value comparison means checking the value inside the objects

Community
  • 1
  • 1
Kasparov92
  • 1,365
  • 4
  • 14
  • 39