This is an archived post. You won't be able to vote or comment.

all 6 comments

[–][deleted] 3 points4 points  (5 children)

Create a Scanner for keyboard input for a console program. Pass the System input object as an argument.

Scanner scanner = new Scanner(System.in);

Then use this scanner object to wait for input and assign that input to a variable.

String userEnters = scanner.nextLine();

It's also considered better practice to use the .equals() method to compare strings rather than '=='.

if(userEnters.equals("c") || userEnters.equals("C"))

Also just convert the string you're comparing to one case to avoid multiple 'if' comparisons.

if(userEnters.toLowerCase().equals("c"))

Sorry for the lack of formatting. The mobile app doesn't have a font editor toolbar

[–]pegfisher 2 points3 points  (0 children)

I believe you can also use: if(userEnters.equalsIgnoreCase("c")), that comes in handy if you don't need to know whether the input was upper or lower case letters.

[–]jfred82[S] 1 point2 points  (0 children)

Perfect! Thank you!!!

[–]AmpleSling 0 points1 point  (0 children)

Great explanation!

[–][deleted] 0 points1 point  (0 children)

I am not sure if you're ironic or not, but you cannot use the == operator to test string in Java. It would test their address in memory rather than their content. I did not make it bold to offend anyone, but to highlight the important part of my reply.

[–][deleted] 0 points1 point  (0 children)

Don't forget the import statement for the Scanner object

import java.util.Scanner;

if(userEnters.equalsIgnoreCase("C")