[Java] Problem with checking which key a user presses.

c0rrupt

Weaksauce
Joined
Jun 25, 2004
Messages
102
I am writing a small Java console program. When I ask the user a question, they will answer with y or n. Only problem is that I can't get the program to detect which key the user pressed. Here is the code I am currently using but it isn't working. When I type y and press Enter it doesn't print anything, just another blank line and then the program exits.

Code:
System.out.println("Would you like to restart the calculator? [y/n] ");
Scanner userInput = new Scanner(System.in);
		
if (userInput.nextLine() == "y") {
	System.out.println("yes");
}
 
Heres how I would write it.
Code:
Scanner userInput = new Scanner(System.in);
String str="";
System.out.print("Would you like to restart the calculator? [y/n] ");  //not using println casue it looks weird to have prompt on next line
str=userInput.nextLine();

if (str.equalsIgnoreCase("y"))
{
System.out.println("\nyes");  // using "\n"  to move the cursor down to the next line because println wasnt used previously
}
 
Be careful with ==. When you're comparing strings, you usually want to be using foo.equals(bar), which returns a boolean. The equality operator doesn't test the contents of the string, it just checks to see if the two string references point to the same object.
 
Anyone have any idea why this won't work. The d variables are double and userInput should always be an integer.

CostOfDrivingCalc.java:56: non-static variable dMilesDrivenDaily cannot be referenced from a static context
dMilesDrivenDaily = userInput.nextInt();
^
CostOfDrivingCalc.java:59: non-static variable dPriceGallonFuel cannot be referenced from a static context
dPriceGallonFuel = userInput.nextInt();
^
CostOfDrivingCalc.java:62: non-static variable dVehicleMileage cannot be referenced from a static context
dVehicleMileage = userInput.nextInt();
^
CostOfDrivingCalc.java:66: non-static variable cCustomValues cannot be referenced from a static context
cCustomValues = userInput.nextInt();
^
 
This is one of those rare cases where the Java compiler is giving you a useful error message. You've got a static method, but your variables aren't declared as static (that is, you would have to have an instance of the class in order to use them).
 
Back
Top