Java input failure [duplicate] - java

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How do I compare strings in Java?
What am I doing wrong? After I compile and run the program, I type in my input and no matter what it is, the program always takes it as an incorrect input and says I'm wrong, here:
import java.util.Scanner;
public class mena3 {
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
String Capitol;
System.out.print("Enter the capitol of Morocco: ");
Capitol = user_input.next();
if(Capitol == "Rabat") {
System.out.println("Good Job!");
}
else {
System.out.println("That is incorrect");
}
}
}
And after I put in Rabat, it says That is incorrect. If I put in l, it says That is incorrect. Why can't I win?

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
}
Voting to close this question as it's only been asked and answered umpteen million times on this site.

One of the most common mistakes in java. String require a .equals() rather than an ==.
Wrong:
if (str == "foo") {
}
Right:
if ("foo".equals(str)) { // done in this order to avoid NPE
}

Your code is perfect, only your comparison method is wrong. All other languages treats == as comparison operator. But in case of Java it is little bit tricky. Here in Java == is taken as comparison operator for objects, not a string variable.
So, to compare two Strings you have a method called `.equals() which is from String class it self.
hence you need to change your code accordingly,
import java.util.Scanner;
public class mena3
{
public static void main(String[] args)
{
Scanner user_input = new Scanner(System.in);
String Capitol;
System.out.print("Enter the capitol of Morocco: ");
Capitol = user_input.next();
// if(Capitol == "Rabat") // your previous code
if(Capitol .equals ( "Rabat") ) // new updated comparison code
{
System.out.println("Good Job!");
}
else
{
System.out.println("That is incorrect");
}
}
}

Related

How to end do while loop with user input with if statement [duplicate]

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;
}

Beginner here - java IF ELSE used with text [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
How can I read input from the console using the Scanner class in Java?
(17 answers)
Closed 5 years ago.
I just started reading about JAVA and I want to make a little program that when using Scanner is I type "yes", "no" or just something random I will get different messages.The problem if with the lines:
if (LEAVE == "yes") {
System.out.println("ok, lets go");
if (LEAVE == "no") {
System.out.println("you dont have a choice");
} else {
System.out.println("it's a yes or no question");
I receive the error : Operator "==" cannot be applied to "java.util.scanner", "java.lang.String". I saw on a site that it would be better if I replaced "==" with .equals,but I still get an error..
Help please :S
Code below:
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner LEAVE = new Scanner(System.in);
System.out.println("do you want to answer this test?");
LEAVE.next();
System.out.println("first q: would you leave the hotel?");
LEAVE.next();
if (LEAVE == "yes") {
System.out.println("ok, lets go");
}
LEAVE.nextLine();
if (LEAVE == "no") {
System.out.println("you dont have a choice");
LEAVE.nextLine();
} else {
System.out.println("it's a yes or no question");
}
}}
Scanner LEAVE = new Scanner(System.in);
Implies that LEAVE is Scanner class object. Right.
if (LEAVE == "yes")
You are comparing the Scanner type object with String type object and hence you are getting
Operator "==" cannot be applied to "java.util.scanner", "java.lang.String"
Now consider
LEAVE.next();
you are calling next() which belongs to LEAVE object. That next function is suppose to read a value and return that to you. So what you do is receive this value in another String type object and then further compare it to 'YES' or 'NO' or whatever.
String response = LEAVE.next()
if(response.equalsIgnoreCase("yes")){
// do something
}else if(response.equalsIgnoreCase("no")){
// do something else
}
More about Scanner class
GeeksForGeeks

i keep getting the good bye response no matter if i input yes or no, how would i change that so responses are correct [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 5 years ago.
I keep getting the 'good bye' response no matter what I enter, 'yes' or 'no'. How would I change that so responses are correct.
import java.util.Scanner;
public class SimpleQuiz1 {
public static void main(String[] args){
Scanner userInputScanner = new Scanner (System.in);
System.out.println("Are you ready to take this NBA quiz?");
String answer = userInputScanner.nextLine();
if(
answer == ("yes")){
System.out.println("Then lets get started!!!");
} else{
answer = ("no");
System.out.println("Goodbye, come again soon!");
}
}
}
Use String.equals(Object obj) rather than == as "==" will check for reference equality whereas .equals compares only the content not the reference.
Scanner userInputScanner = new Scanner(System.in);
System.out.println("Are you ready to take this NBA quiz?");
String answer = userInputScanner.nextLine();
if (answer.equals("yes")) {
System.out.println("Then lets get started!!!");
} else {
this should work fine.

Can somebody spot the error in this java program [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
My program should check whether the input is a palindrome or not. The given program compiles and runs successfully. Program prints reverse string correctly but gives wrong output. Please help!
class Palindrome
{
public static void main(String[] args)
{
String str,revStr="";
System.out.println("Enter something to check if it is a palindrome");
Scanner sn = new Scanner(System.in);
str = sn.nextLine();
for(int i=str.length()-1;i>=0;i--)
{
revStr+=Character.toString(str.charAt(i));
}
if(revStr==str)
{
System.out.println("The string "+str+" is a Palindrome");
System.out.println(revStr);
}
else
{
System.out.println("The string "+str+" is not a Palindrome");
System.out.println(revStr);
}
}
}
output:
Enter something to check if it is a palindrome
nitin
The string nitin is not a Palindrome
nitin
Here change this line
if(revStr==str)
To
If ( revStr.equals(str))
The thing is == checks reference equality
Object.equals is the method given in java to define your object equality
String class overrides that and check if two Strings represent same char array
Your answer here:
import java.util.Scanner;
class Palindrome
{
public static void main(String[] args)
{
String str,revStr="";
System.out.println("Enter something to check if it is a palindrome");
Scanner sn = new Scanner(System.in);
str = sn.nextLine();
for(int i=str.length()-1;i>=0;i--)
{
revStr+=Character.toString(str.charAt(i));
System.out.println("revStr" + revStr);
}
if(revStr.equals(str))//Don't use ==
{
System.out.println("The string "+str+" is a Palindrome");
System.out.println(revStr);
}
else
{
System.out.println("The string "+str+" is not a Palindrome");
System.out.println(revStr);
}
}
}
The “==” operator
In Java, when the “==” operator is used to compare 2 objects, it checks to see if the objects refer to the same place in memory. In other words, it checks to see if the 2 object names are basically references to the same memory location.
Equals() method is defined in Object class in Java and used for checking equality of two object defined by business logic
your if condition should be like this
if(revStr.equals(str)){
System.out.println("The string "+str+" is a Palindrome");
System.out.println(revStr);
}
Because in java == check the address of object not content
for more details check below thread
What is the difference between == vs equals() in Java?

Why does it skip the If statement inside the While loop? It prints out "no work", why? [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
This is the program
import java.util.Scanner; //imports class
public class blank2 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
boolean valid = true;
String ans;
ans = in.next(); //answer is a string
If you type in "y", it goes right to the else statement.
while (valid == true)
{
it always skips this statement
if (ans == "y")
{
System.out.println("it works");
valid = false;
{
else
{
System.out.println("no work");
valid = false;
{
}
}
}
It just wont work
if (ans == "y")
Don't compare strings with ==. That compares object references(the same string). Use:
if ("y".equals(answer))
instead. It will compare strings for equality(check if they are identical as opposed to the same one). I do not use answer.equals("y") due to the risk of a null pointer exception if answer was null for any reason.
In strings, don't use the ==, you can use compareTo instead.
if ("y".comprateTo(answer))
With this method you can check if they are the same, or if one is greater than the other.
let us know if you have questions

Categories