r/javahelp • • Feb 06 '16

Solved How can I write this so that the program prompts user for username and password (both predetermined) and displays a custom exception when the wrong username or password is typed?

I have basically written a try block with the prompt and the catch with the exception "Enter correct username or password". Do I have to throw and exception within the try block in an if statement? Here is what I have.

import java.util.*; public class MainDriver {

public static void main(String[] args){

	Scanner input = new Scanner(System.in);
	
	try{
		System.out.print("Enter username: ");
		String username = input.nextLine();
		System.out.print("Enter password: ");
		String password = input.nextLine();
		if(username!="admin" || password!="password"){
			throw new Exception();
		}
	}catch(Exception e){
		System.out.print("Enter correct username and password");
	}
}

}

this just asks the user to enter the username and password no matter what they enter

0 Upvotes

4 comments sorted by

7

u/zifyoip Feb 06 '16

You can't compare strings that way. Read the sidebar.

1

u/ewiethoff Feb 07 '16

Your flair thing says your problem is already solved. So? And you deleted pretty much the same post a short while ago. So?

1

u/hugthemachines Feb 07 '16

google: java compare strings

First hit is this:

http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java

That would be less work than making this post :)

1

u/desrtfx Out of Coffee error - System halted Feb 08 '16

Reading the sidebar -> "Regarding String comparison, read this!" would have been even less work than googling...