If statement is ignored [duplicate] - java

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I am making a simple matchmaker as a learning project in JAVA. My program so far just asks a few questions, but I wanted to do gender specific questions, so I asked for their sex (m or f) and then attempted to add a message that only showed if sex was m. The dialog should say "well done, you are male!". Else it restarts method. Every time, no matter what I type it restarts the program.
Here is my code:
import javax.swing.JOptionPane;
public class Main {
public static void main(String[] args){
setVars();
}
public static void setVars(){
String name = JOptionPane.showInputDialog(null, "What is your name?");
String sAge = JOptionPane.showInputDialog(null, "What is your age?");
String sex = JOptionPane.showInputDialog(null, "What is your sex?\n(Enter m or f)");
if (sex == "m"){
JOptionPane.showMessageDialog(null, "Well done, you are male.\nKeep Going!");
}
int age = Integer.parseInt(sAge);
String chars = JOptionPane.showInputDialog(null, "Name three charectaristics");
}
}

try
if ( "m".equalIgnoreCase(sex))
you should use equals for comparing string value and == for checking their references

In Java, you dont' compare strings with ==, you have to compare them with the equals() method on String. String has two variants of this method: equals() which is case sensitive, and equalsIgnoreCase(), which is case insensitive. In the examples below, you can use either one.
Try this:
if(sex.equalsIgnoreCase("m") {
...
}
Or to guard against nulls...
if("m".equalsIgnoreCase(sex)) {
...
}

Your code should be:
if ("m".equals(sex)) {
//
}
== compares objects' addresses / references
.equals compares objects' values

because String is an object not a data type like int when it comes to compare two Strings it is done by .equals() method:
package example;
import javax.swing.JOptionPane;
public class Main {
public static void main(String[] args){
setVars();
}
public static void setVars(){
String name = JOptionPane.showInputDialog(null, "What is your name?");
String sAge = JOptionPane.showInputDialog(null, "What is your age?");
String sex = JOptionPane.showInputDialog(null, "What is your sex?\n(Enter m or f)");
if (sex.equals("m")){
JOptionPane.showMessageDialog(null, "Well done, you are male.\nKeep Going!");
}
int age = Integer.parseInt(sAge);
String chars = JOptionPane.showInputDialog(null, "Name three charectaristics");
}
}

Related

How to check whether the user entered the appropriate string? (Java) [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 2 years ago.
package com.company;
import java.lang.String;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
String str = "";
do{
Scanner input = new Scanner(System.in);
System.out.print("Input: ");
str = input.nextLine();
}while(str != "key123");
System.out.print("Good!");
}
}
The user must enter the correct key, but the code doesn't work and I can't figure out why?
Screen shot:
enter image description here
The == operator works correctly all the time for primitives only. That's char, boolean, int double, float, byte, long, short. It does not work for classes like String or Object.
Instead use: object.equals(anotherObject); like so
String str = "";
Scanner input = new Scanner(System.in);
do {
System.out.print("Input: ");
str = input.nextLine();
} while (!str.equals("key123"));
System.out.println("Good!");
System.out.println(str == "key123"); // false
System.out.println(str.equals("key123")); // true
And avoid creating a new object in a loop every time it iterates unless you absolutely have to. Object creation takes memory.

Searching element in String array in JAVA? [duplicate]

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

Scanner method and string pool

The script below will compare two string to see if they are equal. In this case one string is declared and the other string is input from the scanner. I understand why these two string are not equal when compared (say aName = test and anotherName= test) because they will contain different references addresses.
This next paragraph will lead into my question. The nextLine() method returns a string. I know normally if two strings contain the same text they would have the same address in the string pool. So my question is, why isn't the string returned from the nextLine() method to the anotherName variable assigned to the string pool and given the same address as aName, since they have the same text? *
import java.util.Scanner;
public class TryToCompareString
{
public static void main(String[] args)
{
String aName = "test";
String anotherName;
Scanner input = new Scanner(System.in);
System.out.println("Enter your name");
anotherName = input.nextLine();
if (aName == anotherName)
{
System.out.println(aName + " equals " + anotherName);
}
else
{
System.out.println(aName + " does not equal " + anotherName);
}
}
}

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?

Java input failure [duplicate]

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

Categories