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.
Related
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 3 years ago.
import java.util.Scanner;
public class main {
public static void main(String[] args) {
boolean a = true;
do {
Scanner input = new Scanner(System.in);
System.out.println("Press any on keyboard:");
String keys = input.nextLine();
System.out.println("You pressed:");
System.out.println(keys);
System.out.println("Your hash is:");
String B = "#B";
String hash = B+keys;
System.out.println(hash);
System.out.println("To end loop press f");
//End Loop
Scanner exit = new Scanner(System.in);
String end = exit.nextLine();
if (end=="f") {
a=false;
}
}
while(a);
}
}
I've been using python and I decided to start learning java since android studio requires it. I'm learning how to do loops again. I can't get this to work. I already looked this up I couldn't find it. How would I end this by pressing 'f'? My thought process was that once it was done going though the first lines of the do loop, it would go though the if statement changing the value of a ending the loop.
use break statement under if(){} body. also your == comparison will give false, use str1.equals(str2) for comparison.
Your problem is you are comparing strings with ==.You have to use equals to write correct if statement.
if (end.equals("f")){...}
You could use the below code to check
if (end.equals("f")) { // end == "f" , it check the reference.
a = false;
}
I'm trying to write a program that can decide what mechanism a organic reaction will go through using a series of if else and switch statements.
Could you guys help me figure out what I'm doing wrong here? I'm having a problem getting the first if else statement to work. The program runs on my computer(I'm using the BlueJ editor), but when I respond to the first question "Is it soluble in solution?" it defaults to the else statement. The switch statements on the inside of the if else statement works fine by itself.
Can I use switch statements inside if else statements? Is there an easier way to program this?
Could you also explain why it doesn't work, or why another method would be more efficient?
Thanks a ton :)
import java.util.Scanner;
/**
* This program will decide what mechanism a reaction will undergo given information about the reactants.
* I will also include a mechanism to give a rudimentary explanation of the decision making process to
* get the reaction mechanism.
*/
public class mechanism
{
public static void main(String[] args)
{
System.out.println("Hello, this program is designed to figure out what mechanism a reaction will under go.");
//The decision tree will be a series of if-else statements. If I find a better method, I will use that
System.out.println("Is the reactant soluble in the solvent? Answer in yes or no.");
Scanner keyboard = new Scanner(System.in);
String Solubility = keyboard.next(); //Defines if the reactant is soluble in the solvent
String functional = "unassigned";//Defines if the functional roup is primary secondary or tertiary
String Base = "unassigned";//Defines the strength of the base if needed
String Polar = "unassigned";//Defines if the reactant is polarizable
String Solvent = "unassigned"; //Defines if the solvent is protic or aprotic
if ( Solubility == "yes" )
{
System.out.println("Is the functional group attached to a primary, secondary, or tertiary carbon?");
System.out.println(" Answer in p for primary, s for secondary, and t for tertiary.");
keyboard = new Scanner(System.in);
functional = keyboard.next();
switch (functional){
case "p": System.out.println("All unimolecular reactions are ruled out, leaving E2 and Sn2.");
System.out.println("Is the reactant a strong base? Answer in y for yes or n for no");
keyboard = new Scanner(System.in);
Base = keyboard.next();
if (Base == "y" ){
System.out.println("The reaction undergoes E2");
} else{
System.out.println("The reaction undergoes Sn2");
}
break;
case "s": System.out.println("No reactions have been ruled out.");
System.out.println("Is the reactant a strong base? Answer in y or n");
keyboard = new Scanner(System.in);
Base = keyboard.next();
if( Base == "y" ){
System.out.println("yay");
} else {
System.out.println("whatever");
}
break;
case "t": System.out.println("tertiary");
break;
}
}
else{
System.out.println("No reaction will occur");
}
}
}
It's another one of those mistakes that you and I will make once in a while.
Short answer: You can't use == to compare strings!
Long answer:
In your if statements, you are comparing strings with ==. You should never EVER do that. The == compares the memory addresses of the two operands if they are not a primitive. I know you want to check if the characters of the two strings are the same. But two strings with the same characters may not have the same memory address!
What you should do is use the equals method to compare strings, like this:
if (Solubility.equals("yes"))
You can also use the equalsIgnoreCase method. It does what it says on the lid. Remember to change all the other if statements as well!
Moreover, you cannot use switch statements to switch a string. But seeing you didn't recieve any compiler error, I think you are using Java 8.
But if you are not using Java 8, the best way IMO to resolve this is to switch a Character.
char functionalChar = functional.charAt(0);
switch (functionalChar) {
case 'p': // remember to use single quotes!
...
}
Although this is not the biggest problem, it is still worth correcting:
You only need to instantiate Scanner once.
It is perfectly fine to use a switch statement for multiple input types - even within an if statement.
Your problem is that you keep re-initializing the Scanner object.
Once you have initialized the Scanner:
Scanner keyboard = new Scanner(System.in);
Then elsewhere where you would like to receive input, just re-use it:
//keyboard = new Scanner(System.in); // You don't need this line
Base = keyboard.next();
Also, the reason that you are never entering your if statement is the way you are comparing Solubility with'Yes'. For Strings, you should use either equals() or equalsIgnoreCase if case does not matter.
Change the if statement to the following line and your code will work as expected:
if ( Solubility.equalsIgnoreCase("yes"))
This question already has answers here:
Why does non-equality check of one variable against many values always return true?
(3 answers)
Closed 7 years ago.
I'm simply trying to determine if the user has entered a YES or NO value (disregarding caps though, hence equalsIgnoreCase()). However, regardless of me entering YES or NO, the do-while doesn't break E.G.
public int addInformation() {
final int YES = 1;
final int NO = 0;
String userDecision = "";
try(Scanner scanner = new Scanner(System.in)) {
System.out.println("Add Information Now? [YES/NO]");
do {
System.out.println("Please Enter YES or NO ");
userDecision = scanner.nextLine();
} while(!userDecision.equalsIgnoreCase("yes") |
!userDecision.equalsIgnoreCase("no"));
}
if(userDecision.equalsIgnoreCase("yes")) {
return YES;
}
return NO;
}
I'm looking for the behavior of "while the input value is not equal to 'yes' OR 'no', ask for the data again". However my code suggests "disregard whatever is typed, let's just keep looping for fun..." Where did I go wrong, Stack? thanks
This condition
while (!userDecision.equalsIgnoreCase("yes") |
!userDecision.equalsIgnoreCase("no"))
is always true. Any string must be EITHER not equal to "yes" OR not equal to "no".
If you mean to check that the string is not equal to either, you mean this:
while (!userDecision.equalsIgnoreCase("yes") &&
!userDecision.equalsIgnoreCase("no"))
Your condition is incorrect. You want to end the loop if either condition is false (so you need an and). Something like,
while(!userDecision.equalsIgnoreCase("yes") &&
!userDecision.equalsIgnoreCase("no"));
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).
Does a do-while loop check a value before or after it has been incremented? I can't seem to make this do-while loop escape, and can't determine if that is the mistake I am making. The point of this loop is to take input from the user and when they hit 'X', I want the loop to end. Am I using the wrong type of loop, or perhaps an incorrect statement?
int i = 0,
inputCount = 0;
char letter = 'a';
String[] coefficient = new String[MAX_LENGTH];
do{
System.out.print("What is " + letter +"? ");
coefficient[i] = keyboard.nextLine();
i++;
letter++;
inputCount++;
}while(coefficient[i] != "X");
Don't compare Strings using ==. Use the equals(...) or the equalsIgnoreCase(...) method instead. Understand that == checks if the two objects are the same which is not what you're interested in. The methods on the other hand check if the two Strings have the same characters in the same order, and that's what matters here. So instead of
if (fu == "bar") {
// do something
}
do,
if ("bar".equals(fu)) {
// do something
}
or,
if ("bar".equalsIgnoreCase(fu)) {
// do something
}
Specifically in your case, I'd change
} while(coefficient[i] != "X");
to something like:
} while(!"X".equalsIgnoreCase(coefficient[i]));
And you've got another problem in your code in that you want to test the user input which you place into coefficient[i], but then you promptly increment the i variable such that coefficient[i] no longer refers to the input.
So perhaps the test should instead be:
} while(!"X".equalsIgnoreCase(coefficient[i - 1]));
You're incrementing i between coefficient[i] = keyboard.nextLine(); and while(coefficient[i] != "X");, so in the while check coefficient[i] is null, also use .equals to compare strings.
int i = 0,
inputCount = 0;
char letter = 'a';
String[] coefficient = new String[MAX_LENGTH];
do{
System.out.print("What is " + letter +"? ");
coefficient[i] = keyboard.nextLine();
i++;
letter++;
inputCount++;
}while(!coefficient[i-1].equals("X"));
There is two problems here. First you shouldn't compare Strings using logical operators. Use .equals instead.
For example:
coefficient[i].equals("X");
Secondly you are incrementing your array index counter before you check the while condition. So you actually need to subtract one from it to check if the most recently entered String was X.
See if using this will get it working:
coefficient[i-1].equals("X");