-1

can some tell me what's wrong with my code? even if I'm putting right password,unable to access balance with getBalance()... :(

package home.exercises.exceptionHandling;

import java.util.InputMismatchException;
import java.util.Scanner;

public class Manager {

    private double balance = 15000.25;


        public void getBalance() throws InputMismatchException {

        @SuppressWarnings("resource")
        Scanner s = new Scanner(System.in);

        System.out.println("Enter password: ");

        String password = s.nextLine();

        if (password == "ManagerWantsTogetBalance") {

            System.out.println("Remainning balance is " + this.balance);    
        } else {
            System.out.println("Wrong password! Try Again..");
        }



    }

}



package home.exercises.exceptionHandling;

import java.util.InputMismatchException;

public class TestManager {

    public static void main(String[] args) {

        Manager branchManager = new Manager();

        try {
            branchManager.getBalance();
        }
        catch(InputMismatchException iex) {

            System.out.println("Put password in the correct form");
        }

    }

}
auth private
  • 1,318
  • 1
  • 9
  • 22
izengod
  • 1,116
  • 5
  • 17
  • 41

4 Answers4

1

The problem is here:

password == "ManagerWantsTogetBalance"

you should be using equals (or equalsIgnoreCase if you don't care about uppercase / lowercase differences) to compare two Strings, because those methods check the actual contents.

The == operator instead checks whether the references to the objects are equal (they point to the same memory area).

For more information: Java String.equals versus == [duplicate]

Warrior
  • 563
  • 1
  • 6
  • 20
0

You have to compare your Strings with .equals() function, never with ==.

if("ManagerWantsTogetBalance".equals(password)){
  //Code
}
Francisco Romero
  • 12,787
  • 22
  • 92
  • 167
0

When comparing String we use the .equals("Whatyouwanttocompare") method. So your if statement should look like if(password.equals("ManagerWantsTo GetBalance")) { } You use == to compare primitive datatype such as int and double etc.

dijam
  • 658
  • 1
  • 9
  • 21
0

The == operator compares object references. So it returns true only if the operands are the same object. In the case of strings it would return true only if the objects are the same string. If you want to compare strings use the equals method. It returns true if the content of the strings is the same which is your desired behavior:

string1.equals(string2)