Conditional using a string in Java after using Scanner [duplicate] - java

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 4 years ago.
It always give the second conditional regardless of the input. Is (userName == "Charles") the correct way of doing this conditional? or do i need something else.
import java.util.Scanner;
public class Name_input {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String userName = input.next();
System.out.println(userName);
if (userName == "Charles")
{
System.out.println("Correct Name");
}
else if (userName != "Charles")
{
System.out.println("Incorrect Name");
}
}
}

Is (userName == "Charles") the correct way of doing this conditional
No You don't use "==" to compare strings.
Instead you should be using the equals(...) method:
if ( "Charles".equals( userName ) )
Note I reversed the order of the comparison. This will prevent a NPE if the username is ever null.
System.out.println(userName);
Does that display the expected value? Do you need to use the trim() method?
else if (userName != "Charles")
Also, there is no need for the "else if". The name is either "Charles" or it isn't so you don't need the additional "if" statement.

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

How to compare 2 passwords in java? [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 6 years ago.
I'm working on a project with a registration form. The form asks the user to
enter a password of their choice in a JPassword Field, and to enter it again in another JPassword Field.
I'm using a JOptionPane to prompt the user if the passwords do not match. but when i use passwordField.getPassword().toString() on the two, they don't match.
I have tried entering a basic "12345" for example on both but i still have no luck.
i know you should use .equals(), but what is the equivalent to this for "not equals" without using the "!=" operator.
here is the following code.
if(e.getSource() == submit)
{
String name = nameTextField.getText();
String address = addressTextField.getText();
String phoneNumber = numberTextField.getText();
String dob = datePicker.getDateFormatString();
String password = passwordField.getPassword().toString();
String password2 = passwordFieldTwo.getPassword().toString();
try
{
//If the user leaves the field empty
if(name == null || address == null || phoneNumber == null || dob == null
|| password == null || password2 == null)
{
//Error message appears to prompt the user to
//complete the form
JOptionPane.showMessageDialog(null, "All fields must be complete to submit.", "Woops", JOptionPane.ERROR_MESSAGE);
}
if(password != password2)
{
JOptionPane.showMessageDialog(null, "Passwords do not match.", "Woops", JOptionPane.ERROR_MESSAGE);
passwordField.setText(null);
passwordFieldTwo.setText(null);
}
Any help with this would be much appreciated.
The != related to equals() for String comparison is expressed by !x.equals(y)
As an example lets take your code, to see if the two passwords not match do the following:
if (!Arrays.equals(passwordField.getPassword(), passwordFieldTwo.getPassword())) {
JOptionPane.showMessageDialog(null, "Passwords do not match.", "Woops", JOptionPane.ERROR_MESSAGE);
}

Simple login with Java code - using conditional assignment [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 7 years ago.
I'm still newbie to java programming. And can anybody tell me what's wrong with the source code? When I run the code, the conditional assignment always outputs "login failed".
import java.util.Scanner;
public class ProgramBiodataMahasiswa {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String username, password, output;
System.out.print("Enter username : ");
username = input.nextLine();
System.out.print("Enter password : ");
password = input.nextLine();
output = (username=="kesit" && password=="ps123") ? "login successfully" : "login failed" ;
System.out.println(output);
}
}
Use .equals
output = (username.equals("kesit") && password.equals("ps123")) ? "login successfully" : "login failed" ;
With Strings ("quest" and "ps123") you shouldn't be using == to check if they equal. This will compare the pointer and due to the fact that String in Java are immutable, the pointers will always be different. Therefore use
username.equals("kesit") && password.equals("ps123").
That should work!
You can't compare strings in Java using ==. You should use equals method. e.g. username.equals("kesit") && password.equals("ps123")

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

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