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 ==.
Related
So recently I've switched over from python to java and was trying to recreate some of the projects that I made on python in java. The first thing that came to mind was a quiz.
Basically, to create a quiz, I define an answer variable to the answer then use the scanner method in java to detect the user's input. After that, I use an if statement to see if the input equals the answer.
ex.
class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String answer = "dog";
System.out.println("What is a common furry animal");
String input = scan.nextLine( );
if (input.equals(answer))
{
System.out.println("Correct");
}
else
{
System.out.println("Inncorect");
}
}
}
Now that all works but the user doesn't know the exact casing of the answer variable which means if the variable was "dog" and he input "Dog" it would be incorrect. So if it was possible to create an "or" condition to an if statement it would be awesome if someone let me know.
-Thanks
To or any condition in Java, use the conventional || to separate conditions. In your case it would be something like:
if (input.equals(answer) || input.equalsIgnoreCase(answer))
Although you probably just need the Java method equalsIgnoreCase as the lone condition in the first place.
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:
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.
This question already has answers here:
Can't get else if statement to work in Java
(5 answers)
Closed 10 years ago.
Help. I'm new to Java programming so I'll try to make the best of your terms.
I was wondering how to get this program to register as true. When I type in "password" as an input, it does not execute any code from the "if" body. I also pasted this code in another class and it still doesn't work, regardless.
I've worked on this program for about a half an hour, and debugging it for twice as long. Please look through the coding.
import java.util.Scanner;
public class whileloop {
public void whileloop1() {
//DEBUG THIS PROGRAM! "password" does not work for input
System.out.println("Please enter the password to continue: ");
Scanner password = new Scanner(System.in);
String passwordinput = password.nextLine();
System.out.println("This is your entered password: " + passwordinput);
if (passwordinput == "password") {
System.out.println("Startup sequence has been iniciated.");
System.out.println("System is working correctly.");
//Terminate all here ---
} else {
System.out.println("Wrong password! Terminating program. /END");
}
System.out.println("Supressing the program's scanner!");
password.close();
}
}
When comparing string content in Java you use the .equals() method.
The == operator checks for reference equality, meaning, testing if they are both references of the same object.
So, in your case:
if(passwordinput.equals("password"))
This has been said many times, but I'll say it again, when comparing Strings in java, if you want to know if they point to the same reference use the == operator. if you want to check if they are equal in value use .equals("somestringhere") In your case use passwordinput.equals("password")
Since, in Java the line:
String s; declares a reference to a String object, unlike C++, which may declare an object of String.
So, the line if (passwordinput == "password") compares the reference of "password" and reference of passwordinput, the result will be false.
So, use if(passwordinput.equals("password"), which compares the object referenced by passwordinput with "password"