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?
Related
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 4 years ago.
I have made a JAVA program where I have initialized a 1-D String array. I have used for loop to search any inputted String if it exists in the array(Scanner Class).
Here is the source code :-
import java.util.*;
class search
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the name to search :-");
String s=sc.nextLine();
String array[]={"Roger","John","Ford","Randy","Bacon","Francis"};
int flag=0,i;
for(i=0;i<6;i++)
{
if(s==array[i])
{
flag=1;
break;
}
}
if(flag==1)
System.out.println("The name "+s+" Exists");
else
System.out.println("The name "+s+" does not Exists");
}
}
The class even compiles successfully, but when I enter a valid string(say- Roger), the output is The name Roger does not Exists.
Please help me out with this issue, and for this I shall be grateful to you.
Thanking You,
J.K. Jha,
01.09.2018.
You are confusing == and equals
Since String is an object == just checks for if the references are same instead of actual contents
You should use String.equals() instead
Changes your if condition
for(i=0;i<6;i++)
{
if(s.equals(array[i]))
{
flag=1;
break;
}
}
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 5 years ago.
public class ex1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Please enter a series of strings each followed by the enter key. When you'd like to end thr program simply type 'quit': \n");
Scanner scan = new Scanner(System.in);
ArrayList<String> inputList = new ArrayList<String>(); // creates a list to store user input
String input = scan.nextLine(); //takes the scanner input
while(input != "quit") { //makes sure its not equal to quit
//System.out.println(input);
inputList.add(input);
input = scan.nextLine();
}
scan.close();
System.out.println("The number of strings enetered was: " + inputList.size());
System.out.println("The strings you entered were as follows");
for (String i: inputList) {
System.out.println(i);
}
}
}
I'm trying to use the preceding code to take a series of inputs from a user using the enter key and if they enter quit I end the program. However the condition is never satisfied and the while loop never ends and I can't understand why
while(!input.equals("quit")) { //makes sure its not equal to quit
//System.out.println(input);
inputList.add(input);
input = scan.nextLine();
}
You should use equals method as shown above to compare strings. Java provides equals method to compare the contents of two strings. == and != operators are used in comparing object equalities.
a == b returns true if, and only if, a points to the same object as b
The equals method should be used, as the String class implements it so that, if a contains the same characters as b, it would returns true.
while (!input.equals("quit")) { ... }
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 7 years ago.
So I have this executable jar file with a username and password and runs but value doesn't ever continue correctly.
Here is an example:
public static void main(String[] args) {
System.out.println("Hello. I am a program created by Moocow9m. What is your name?");
InputStream stream = System.in;
Scanner scanner = new Scanner(stream);
String input = scanner.next();
if (input == "armystich"){
System.out.println("Welcome CODE NAME: ArmyStich!");
scanner.close();
}
else {
System.out.println("Hello " + input + ". Nice to meet you.");
scanner.close();
}
}
}
All would work except it would always return to else. Please help.
if (input == "armystich"){
The above checks reference equality. To check for value equality, using the equals method
if ( input.equals("armystich") ){
See How do I compare strings in Java?
I'm trying to ask the user to enter a character ("y"/"n") and check whether or not that was the right answer. I'm getting the following error: "incomparable types: java.util.Scanner and java.lang.String"
Scanner userInput = new Scanner(System.in);
System.out.printf("Is this word spelled correctly?: %s", wordToCheck);
rightCheck(userInput);
public boolean rightCheck(Scanner usersAnswer)
{
if(usersAnswer == "y")
{
//"Correct!"
//Increment User's Score
}
else
{
//"Incorrect"
//Decrement User's Score
}
}
Yes, because a scanner is a way of getting input rather than the value itself. You want to fetch the next value from the input, and then compare it. Something like this:
String answer = scanner.next();
if (answer.equals("y")) {
...
} else if (answer.equals("n")) {
...
}
Note that you should usually (including this case) not compare strings with ==, as that compares whether the two operands refer to the exact same string object - you're only interested in whether they refer to equal objects. (See this question for more details.)
I have modified your code, haven't tested it but it should work:
Scanner userInput = new Scanner(System.in);
System.out.println("Is this word spelled correctly?:" + wordToCheck);
rightCheck(userInput.next());//send the string rather than the scanner
public boolean rightCheck(String usersAnswer)//convert the parameter type to String
{
if(usersAnswer == "y")
{
//"Correct!"
//Increment User's Score
}
else
{
//"Incorrect"
//Decrement User's Score
}
}
I believe you should first get the String from Scanner (through next() maybe?). Then in your method, do not use "==" as a string comparator.
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");
}
}
}