Searching element in String array in JAVA? [duplicate] - java

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

Related

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

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?

Different output for same conditions [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
Below is the code:
package com.myprograms.test;
import java.util.Scanner;
public class MyProgram {
public static void main(String[] args) {
Scanner sIn = new Scanner(System.in);
String name = "";
System.out.print("Enter the name:");
name = sIn.next();
if (name.equals("somename")) {
System.out.println("Success - Case 1");
} else {
System.out.println("Failed - Case 1");
}
if (name == "somename") {
System.out.println("Success - Case 2");
} else {
System.out.println("Failed - Case 2");
}
sIn.close();
}
}
Below is the output:
Enter the name: somename
Success - Case 1
Failed - Case 2
Here is the question:
Why one input behaves differently for the same condition in Java? Is it Java error?
"Java Error" - Really..??
This was explained many times, anyway here is a small explanation:
While comparing string in Java, use String.equals() or String.equlasIgnoreCase() methods.
Using == operator, compares the address.
While using equals() or equalsIgnoreCase() method compares the contents of the Strings.
Here is a good explanation (read "Meet Jorman" example):
An observation: You can close the Scanner after getting the inputs, instead of last line of the program, for better resource management.

Java String not working, printing different names [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
So I wrote up a code that will make the user enter the name "Jack" but if he enters any other name it will say "That is not your name!" but i'm having trouble to make it do that. For example when I enter that name "Jack" It will say "That is not your name!" and when I enter a name like Joey for example it will say the same thing.
import java.util.Scanner;
public class WhoAreYou
{
public static void main(String[] args){
Scanner user_input = new Scanner(System.in);
String vYourName, vNotYourName;
System.out.print("Enter your name here: ");
vYourName = user_input.next();
/*
String vNotYourName;
System.out.print("Enter your name here: ");
vNotYourName = user_input.next();
*/
if(vYourName == "Jack")
System.out.println("Your name is: "+vYourName);
else{
vNotYourName = " ";
System.out.println("Thats not your name!");
}
}
}
Instead if using two Strings I tried to use one and that didn't work. Any ideas?
use .equals() when comparing strings:
if(vYourName.equals("Jack"))
System.out.println("Your name is: "+vYourName);
else{
"".equals(vYourName);
System.out.println("Thats not your name!");
}
instead of:
if(vYourName == "Jack")
use this:
if(vYourName.equals("Jack"))

While loop in Java, string comparison does not work [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How do I compare strings in Java?
I'm working on a small program that asks for your name using a Scanner. If you enter blankstring, then I would like the console to display a message.
Here's what I tried doing:
import java.util.Scanner;
public class Adventure
{
public static void main(String[] args)
{
Scanner myScan = new Scanner (System.in);
System.out.println("What's your name?");
String name = myScan.nextLine();
while (!(name == "")) //Always returns false.
{
System.out.println("That's not your name. Please try again.");
name = myScan.nextLine();
}
System.out.println("It's a pleasure to meet you, " + name + ".");
}
}
The code never enters the while loop. Why?
Change your condition to:
while(!name.equals("")) {
or as suggested below by m0skit0:
while(!name.isEmpty()) {
See also
why equals() method when we have == operator?

Categories