Input String check [duplicate] - java

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I am writing an ATM program and when the user inputs one of the string values the program should check it an do a method accordingly. The problem code is here:
System.out.println("PRESS");
System.out.println("(D)eposit");
System.out.println("(W)ithdraw");
System.out.println("(C)heck Account Balance");
System.out.println("(Q)uit");
System.out.println("Enter Choice: ");
String choice = scanner.nextLine();
scanner.nextLine();
if(choice == "D"){
currentCustomer.deposit();
}
else if(choice == "W"){
currentCustomer.withdraw();
}
else if(choice == "C"){
currentCustomer.checkBalance();
}
else if(choice == "Q"){
currentCustomer.quit();
}
else{
System.out.println("Invalid choice please reenter: ");
}
If a user enters in "D" the program skips to the else statement. I know when using .nextLine you have to use two because of the return character but I'm not sure if that is true with this case. Either way if I have the extra .nextLine statement or not it still skips ahead. Any help would be much appreciated!

In Java we compare strings with String#equals.
I'll not write the difference between equals and ==, google for more information. You'll get around 100 results.

You would be better off using if(choice.equals("D")) in your code. You can't compare strings with == because you are just checking the memory and not the actual contents.

Instead of using String in comparison part:
else if(choice == "C"){
currentCustomer.checkBalance();
}
you could use char comparison instead
else if(choice[0] == 'C'){
currentCustomer.checkBalance();
}

You shouldn't be using the == operator to compare strings, use the String equals method instead. The operator checks to see if both strings are stored at the same location in memory while the method checks if they have the same content.
If you're using Java 7, you might want to switch out that if-elseif-then block with a switch statement. Java 7 introduced the ability to use strings in switch statements.

Related

using Or in if/else statement issue [duplicate]

This question already has answers here:
Why does non-equality check of one variable against many values always return true?
(3 answers)
Closed 5 months ago.
Beginner to java. Trying to make it so that my code only takes a certain letter grade input or otherwise exits the system. When I put in this code,
System.out.print("What letter grade do you want to achieve for the course? ");
char desiredGrade = keyboard.next().toUpperCase().charAt(0);
if (desiredGrade != 'A') {
System.out.println("Invalid input");
System.exit(0);
}
it works fine and reads that any other input other than 'A' is an invalid input. However, when I add an OR such as
System.out.print("What letter grade do you want to achieve for the course? ");
char desiredGrade = keyboard.next().toUpperCase().charAt(0);
if (desiredGrade != 'A' || desiredGrade != 'B') {
System.out.println("Invalid input");
System.exit(0);
}
it runs through the if statement even though the user inputs A or B. Is this a simple writing error that I am missing? Thanks!
Use:
desiredGrade != 'A' && desiredGrade != 'B'

How to check if one out of four strings have been entered?

I am looking for a statement that checks if the input is either: yes, y, no, n.
It should also ignore whether or not there are big or small letters. I have been searching here for a while but couldn't find an answer I understood. Is there a way to add more then just "yes" to the if statement?
String result;
do {
System.out.print("Bigger the better");
result = scanner.nextLine();
if (!("yes".equals(result))) {
System.out.println("Invalid answer, try again");
}
} while(!result.matches("[A-ZÅÄÖa-zåäö]+"));
You could use
if (result.matches("(?i)Y(es)?|N(o)?")) {
...
You can OR your conditions using double pipes ||, like so:
if (result.equals("yes") || result.equals("no") || result.equals("y") || result.equals("n"))
Make your result a lower case by:
result.toLowerCase()
And then you can compare to any of the strings ("yes","no","y","n") by using equals() as you did, and using 'or' (||).
result.toLowerCase();
if(result.length()>1 && !result.equals("yes") &&!result.equals("no")){
System.out.println("wrong input");
} else if(result.charAt(0)=='y') {
System.out.println("good answer");
}else if(result.charAt(0)=='n') {
System.out.println("Invalid answer, try again");
}
it will check ether the user will type "yes" or plain "y", or "no" or plain "n"

Loop until valid input is reached [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed last year.
It executes correctly the first time, but:
It keeps printing "Please try again (Y/N)?" no matter what the
input is after asking to continue.
I am unsure if != is appropriate to use for String comparison. I want to say while
loopChoice "is not" Y or N, keep asking.
while(isLoop) {
// Ask for user input
System.out.print("Enter hours worked: ");
hoursWorked = scn.nextInt();
System.out.print("Enter rate per hour: ");
payRate = scn.nextInt();
scn.nextLine();
// Call functions to compute stuff
...
// Print results
...
System.out.print("\nDo you want to continue (Y/N)? ");
loopChoice = scn.nextLine().toUpperCase();
while(loopChoice != "Y" || loopChoice != "N") {
System.out.print("\nPlease try again (Y/N)? ");
loopChoice = scn.nextLine().toUpperCase();
}
switch(loopChoice) {
case "Y":
isLoop = true;
System.out.print("\n");
break;
case "N":
isLoop = false;
System.out.println("Terminating program...");
scn.close();
System.exit(0);
break;
default:
System.out.println("Your input is invalid!");
isLoop = false;
System.out.println("Terminating program...");
scn.close();
System.exit(0);
break;
}
}
You should compare with String equals
while (!loopChoice.equals("Y") && !loopChoice.equals("N"))
Also, replace the or operator with and operator
That's not how you compare strings in Java.
There is also a logical error in your code, as the string can't be both Y and N at the same time, you have to use && instead of ||. As long as the choice is neither Y or N, you want to continue the loop. If it is any of them, you want to stop. So && is the correct choice here.
To check if two strings are equal, you have to use .equals(obj)
while (!loopChoice.equals("Y") && !loopChoice.equals("N")) {
The reason for this is that == compares object references, and two Strings are most often not the same object reference. (Technically, they can be the same object reference, but that's not something you need to worry about now) To be safe, use .equals to compare Strings.
To avoid a possible NullPointerException in other situations, you can also use:
while (!"Y".equals(loopChoice) && !"N".equals(loopChoice)) {
You cannot use loopChoice != "Y", since "Y" is a String. Either use:
loopChoice != 'Y', or
"Y".equals(loopChoice)
Alternatively, use "Y".equalsIgnoreCase(loopChoice).
Case switching is also not possible for Strings if you use Java 1.6 or earlier. Be careful.
You need to know that OR Operation will return true if one of the two condition is true , so logically if you Enter Y , so you ask if the input is not equal Y so the answer is false then you will go to the next part in your condition if the input not equal N so the answer is True , so your finally result will be (True || False = True ) and then you will entered to while loop again
so the true condition is (the input not equal Y && not equal N)
You have fallen into the common early gap between checking equality of objects versus the values of objects. (You can see a quick list of string comparison information [here]
(http://docs.oracle.com/javase/tutorial/java/data/comparestrings.html)
What you wrote asks whether the object loopChoice is the same object as the string constant "Y" or the string constant "N" which will always return false. You want to ask whether the value of object loopChoice is the same as the value of string constant "Y".
You could rewrite your code as follows:
System.out.print("\nDo you want to continue (Y/N)? ");
// get value of next line, and trim whitespace in case use hit the spacebar
loopChoice = scn.nextLine().trim();
while (!("Y".equalsIgnoreCase(loopChoice) || "N".equalsIgnoreCase(loopChoice)) {
System.out.print("\nPlease try again (Y/N)? ");
loopChoice = scn.nextLine().toUpperCase();
}
Note, I like to put the constant value first for clarity. The general form for determining whether the value of two strings is the same is String1.equalsIgnoreCase(String2).

Detecting Numbers in a String Variable (In Java) [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
So, normally for detecting user input, I use int and double variable types.
Example:
Scanner in = new Scanner(System.in);
int selection;
System.out.println("Welcome to RPG! (prototype name)\nIn this game, you do stuff.\nChoose a class:\n1. Soldier\n2. Knight\n3. Paladin\n4. Heavy");
selection = in.nextInt();
if(selection == 1){
System.out.print("you are a soldier");
}
else{
System.out.print(selection);
}
}
This technique usually works fine for me, but I noticed that if the user inputs a letter into the int variable, the game will crash because integers can't store letters. (right?) So I tried using a String variable in its place, like this:
Scanner in = new Scanner(System.in);
String selection;
System.out.println("Welcome to RPG! (prototype name)\nIn this game, you do stuff.\nChoose a class:\n1. Soldier\n2. Knight\n3. Paladin\n4. Heavy");
selection = in.next();
if(selection == "1"){
System.out.print("you are a soldier");
}
else{
System.out.print(selection);
}
}
This seemed to work at first, but as you can see, I have it set so that if the variable "selection" is equal to 1, that it will print "you are a soldier", yet this did not work, instead it printed out the "selection" variables value (1). Did I do something wrong or should I use a different type of variable?
you can use something la this :
try{
int type = Integer.parseInt(selection);
switch(type){
case 1:{
//do soldier stuff
}
case 2:{
// do knight stuff
}
default:{
//do other stuff
}
}
}catch(NumberFormatException exc ){
System.out.println(selection + "is not a number, try again!!!");
}
selection == "1"
Compare strings with String#equals.
"1".equals(selection)
There are lots of ways to do this. A quick point I'd like to make is if you're comparing strings you should use:
var.equals("string");
Since you're only taking one character you could use a character in which case the correct syntax would be:
var == '1'
If you want to be fancy you can do a try catch around your read statement and just read in an string and parse it to an integer, but that is a bit more advanced.
change selection == "1" to "1".equals(selection)
use .equals() for comparing the string "1" and selection and read this A simple explanation would be
x == y returns true only when both x and y refer to same object which is not in your case. equals check if contents are equal meaning if contents of memory location that x and y are referring to are equal or not.

Compilation error executing basic if else statements [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I had a similar code to this using numbers, and it worked perfectly. This however keeps underlining the word else and I don't know why. I am just playing around with java trying to understand a few principles.
I want to program to reply one of two statements depending on input. Also, where it says if (input1 == "Hello");, I wanted to put if (input1 == "Hello" || "hello"); to accept lowercase too, but that showed errors too.
Just to be clear, if i remove the else clause, my program runs and both statements are printed!
import java.util.Scanner;
public class Input
{
public static void main(String[] args)
{
System.out.println("Hello there!");
Scanner Scan = new Scanner (System.in);
String input1 = Scan.nextLine();
Scan.close();
if (input1 == "Hello");
{
System.out.println("How are you?");
}
else
System.out.println("How rude, you didn't even say Hello!");
break;
}
}
}
Never use == to compare strings.
use .equals instead.
if (input1.equals("Hello"))
or
if (input1.equalsIgnoreCase("Hello"))
Delete the semicolon at the end of
if (input1 == "Hello");
EDIT:- As seen in your comments regarding OR.
You can try this:-
if(input1.equalsIgnoreCase("hello") || input1.equalsIgnoreCase("hey") || input1.equalsIgnoreCase("hi"))
Remove the ; at the end of your if statement. And use .equals() to compare strings.
The semicolon causes the compile error, while the == will cause a logical error once it does run.
You probably don't want the semicolon on the line
if (input1 == "Hello");
You also probably do not actually want to compare using == (read the linked question about comparing strings).
Third, why is there a break statement in your else clause?
You're looking for equalsIgnoreCase(). This compares two Strings without any regard to case.
Remove the ; after your if statement condition and add a { after else. Also, it is good practice to to use the equals(Object) method when comparing objects because you might get unexpected results when using ==.

Categories