This question already has answers here:
How do I compare strings in Java?
(23 answers)
String.equals versus == [duplicate]
(20 answers)
Closed 9 years ago.
So I'm fairly new to Java and I am trying to run a program that will display a certain number of letters from a name and ask the user for a response. The user's response should determine one of two answers ("Correct" or "I'm sorry, that's incorrect").
The problem I'm encountering is that when I run the program and put in the answer that should lead to "Correct," which is 'Billy Joel,' I get the response of "I'm sorry, that's incorrect."
I'm not actually sure what's going on, but here's a link to a picture of the CMD when I input what should lead the system to say "Correct" and instead it says "I'm sorry, that's incorrect":
And here is a copy of the relevant code:
System.out.println("\nLet's play Guess the Celebrity Name.");
String s6 = "Billy Joel";
System.out.println("\n" + s6.substring(2, 7));
Scanner kbReader3 = new Scanner(System.in);
System.out
.print("\nPlease enter a guess for the name of the above celebrity: ");
String response = kbReader3.nextLine();
System.out.println("\nYou entered: \n" + response + "\n");
if ((response == "Billy Joel")) {
// Execute the code here if Billy Joel is entered
System.out.println("\nCorrect!");
} else {
// Execute the code here if Billy Joel is not entered
System.out.println("\nI'm sorry, that's incorrect. The right answer was Billy Joel.");
}
System.out.println("\nThank you for playing!");
There's more before this that the program also does, but I'm not having a problem with any of that and it's all correct. I took out the Billy Joel part and everything else ran exactly as it was supposed to. It's just the above code in relation to what it should put out and what it is putting out that's the problem. I'm wondering if maybe I'm missing something in my code or I put something in wrong, but whatever I did, help would be much appreciated.
Your problem lies here. You are using wrong operator to compare strings
if ((response **==** "Billy Joel")) {
System.out.println("\nCorrect!");
} else { ... }
the correct should be
if ((response.equals("Billy Joel")) {
System.out.println("\nCorrect!");
} else { ... }
To compare strings in java you have to use .equals() operator. And to use '==' operator you need to have int, bool etc.
if (response!=null && response.length>0){
//trim the input to make sure there are any spaces
String trimmed=response.trim();
if (response.equals(s6))
System.out.println("\nCorrect!");
} else { ... }
Related
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 6 years ago.
I'm learning the basics of Java, and wanted to practice something. So found a page of some programing problems and I get stuck at this problem:
2) Write a program that asks the user for her name and greets her with her name.
3) Modify the previous program such that only the users Alice and Bob are greeted with their names.
I've made well the 2nd but I have trouble with 3rd one.
System.out.pritnln("Please enter your name ");
Scanner input = user new Scanner(System.in);
String user_name;
user _name = input.next();
if(user_name == "Alice"){
System.out.println("Hello " + user_name + ", sweet name.");
if(user_name=="Bob"){
System.out.println("Hello " + user_name + ", sweet name.");
}
}
Don't use == for string comparison in Java unless you're really sure that is what you are doing. Use:
user_name.equals("Bob")
I actually use equalsIgnoreCase() as my standard approach unless I'm sure it should be case-sensitive.
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 6 years ago.
i want to ask a question for a bedsize and while the answer is not what i choose it will be i want that it will ask the user to answer again
import java.util.Scanner;
public static void main(String[] args) {
String newBedType ;
Scanner sc1 = new Scanner(System.in) ;
System.out.println("you want a single bed or doublebed? ") ;
newBedType = sc1.next() ;
while (newBedType != "single" + "doublebed") {
System.out.println("please choose againe the bed size: ");
newBedType = sc1.next() ;
switch (newBedType) {
case "single" : System.out.println("i see you like sleeping alone");
break ;
case "doublebed" : System.out.println("got company ;) ");
break ;
}
}
}
}
the code kinda works it shows the cases if i write the correct string but it will continue to ask me forever.....
i just stared learning java so be easy on me i know its a stupid question but after hours of trying and searching here(though i did found in python but dont know how to "translate" it to java)
i cant figure it out... thanks to anyone willing to help :)
Your issue is with the line:
while (newBedType != "single" + "doublebed")
This doesn't do what you think it does. You are comparing the variable newBedType with the string "singledoublebed", the addition operator is concatenating those two strings. You want the line:
while (!newBedType.equals("single") && !newBedType.equals("doublebed"))
Note the use of the .equals() method, as string comparisons in Java do not act as expected with the == or != operators.
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 7 years ago.
First off, I know this might have been answered SOMEWHERE but I can't seem to search for the correct terms to get an answer. Also, I'm pretty new to coding, and obvious here, so this probably won't be the best written 'question'.
Quick backstory: I'm coding a sorting game in BlueJ(I know... shitty, but it's what we are learning in school), and for a method I'm creating for any yes/no questions I need isn't working properly. At first, I was having an issue with it allowing to to have the user input save as a String, now I'm having an issue with that String used in the if-else statement parameters. This is what I have right now:
public void userAnswer(int method) //used for yes/no questions
{
System.out.println("Please type 'y' for yes and 'n' for no.");
String answer = keyboard.next();
answer.toLowerCase();
System.out.println(answer + "worked");
if(answer == "y")
{
System.out.println("worked2");
if(method == 0)
completeOrNot();
if(method == 1)
usersMove(theArray);
}
else if(answer == "n")
{
System.out.println("worked3");
System.out.print("\n");
}
}
I'm completely stuck as to why it's not moving into the if-else statement. I test to see if it would print the String, and it will, but it won't convert it to lower case. I just don't know what to do. Any and all help would be appreciated!
When comparing Strings in Java, use the equals() method. Otherwise, you compare their memory locations if you use ==.
"hi".equals("hello") returns False
"hello".equals("hello") returns True
Don't use == to compare strings. use equals:
answer.equals("y")
Strings in Java are objects - you need to evaluate with the equals method for equality, not the == operator for reference identity:
if ("y".equals(answer)) {
// code
} else if ("n".equals(answer)) {
// code
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have an assignment where I have to attach the letters "un" to any word that the user inputs (unless the inputted word already has "un" in front of it, in which case I just return the inputted word). I'm testing my method but I encountered one problem: my program keeps returning an error if I were to test for an empty input. Here is my code:
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter: ");
String input = keyboard.nextLine();
if(input.substring(0,2).equalsIgnoreCase("un"))
{
System.out.println(input);
}
else if(input.equals(""))
{
System.out.println("un");
}
else
{
System.out.println("un" + input);
}
So I wanted to ask how I can test for an empty input/blank string since, evidently, the "" quotations do not work.
There's nothing wrong with checking input.equals("") per-se. The problem is that you have another test beforehand that throws an exception if input is shorter than 2 characters.
There are several ways to solve this, but I'd just simplify things and use startsWith. An empty string doesn't really need a special case of its own - just slap un before it, and you'll get un:
if (input.toLowerCase().startsWith("un")) {
System.out.println(input);
} else {
System.out.println("un" + input);
}
You are having this problem because you are trying to get the substring of string that doesnt have the required length. Put the empty string check first.
if(input.equals("")||input.length==1)
{
System.out.println("un");
}
else if(input.substring(0,2).equalsIgnoreCase("un"))
{
System.out.println(input);
}
else
{
System.out.println("un" + input);
}
If this weren't homework, and the library could be used for other things ( using it in this single purpose may be overkill ), you could use StringUtils.PrependIfMissing().
It does exactly this and handles nulls as well.
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
I wrote a simple program which prompts the user to enter a sentence, word, or number, and then prints input is art. I put the program on an infinite loop so that the prompt would repeat. However, now I'm trying to add a way to quit by saying if (input == "quit") break; however it does not seem to be working. It just continues the infinite loop. Here is the full code:
import java.util.Scanner;
public class Art
{
public static void main(String [] args)
{
Scanner input = new Scanner(System.in);
String a;
for ( ; ; )
{
System.out.println("Please enter something: ");
a = input.nextLine();
if (a == "quit") break;
System.out.print("\n");
System.out.println(a + " is art.");
System.out.print("\n");
}
}
}
Any help would be lovely, thanks!
Use input.equals("quit").
The == is used to check whether two objects are the exact same instance - the same thing in memory -which the typed word and the constant string "quit" are not. Two instances of "quit" were created: one typed by the user, and one constant in the program.
The equals() method is used to compare whether two objects are equal in whatever way equality is defined for them. For strings, that would mean having the same text.
The difference between == and equals() is really fundamental in Java, so you should go over it. Here's a good SO post on the topic. Once you start creating your own classes, you will probably be implementing equals() methods for them. For that reason, make sure to go over the equals() / hashCode() contract as well.
looks like the a == "quit" is the problem. Compare strings using equals()
if("quit".equals(a)) {
}