This question already has answers here:
Can't get else if statement to work in Java
(5 answers)
Closed 10 years ago.
Help. I'm new to Java programming so I'll try to make the best of your terms.
I was wondering how to get this program to register as true. When I type in "password" as an input, it does not execute any code from the "if" body. I also pasted this code in another class and it still doesn't work, regardless.
I've worked on this program for about a half an hour, and debugging it for twice as long. Please look through the coding.
import java.util.Scanner;
public class whileloop {
public void whileloop1() {
//DEBUG THIS PROGRAM! "password" does not work for input
System.out.println("Please enter the password to continue: ");
Scanner password = new Scanner(System.in);
String passwordinput = password.nextLine();
System.out.println("This is your entered password: " + passwordinput);
if (passwordinput == "password") {
System.out.println("Startup sequence has been iniciated.");
System.out.println("System is working correctly.");
//Terminate all here ---
} else {
System.out.println("Wrong password! Terminating program. /END");
}
System.out.println("Supressing the program's scanner!");
password.close();
}
}
When comparing string content in Java you use the .equals() method.
The == operator checks for reference equality, meaning, testing if they are both references of the same object.
So, in your case:
if(passwordinput.equals("password"))
This has been said many times, but I'll say it again, when comparing Strings in java, if you want to know if they point to the same reference use the == operator. if you want to check if they are equal in value use .equals("somestringhere") In your case use passwordinput.equals("password")
Since, in Java the line:
String s; declares a reference to a String object, unlike C++, which may declare an object of String.
So, the line if (passwordinput == "password") compares the reference of "password" and reference of passwordinput, the result will be false.
So, use if(passwordinput.equals("password"), which compares the object referenced by passwordinput with "password"
Related
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;
}
Here is the problem I was given:
Write a program that takes website names as keyboard input until the user types the word 'stop'. The program m just also count how many of the website names are commercial website names (i.e., end with .com), and output that count.
The problem that keeps occurring is even if I type the word stop as input, it is still saying to "enter the next site." I'm not sure where I went wrong.
Can anyone help? Here is my code.
import java.util.Scanner;
public class NewClass
{
public static void main( String [] args)
{
int numberOfComSites = 0;
String commercialNames = "com";
final String SENTINEL = "stop";
String website;
Scanner scan = new Scanner(System.in);
System.out.print("Enter a website, or 'stop' to stop > ");
website = scan.next();
String substring = website.substring(website.length()-3);
while (website != SENTINEL)
{
if(substring == commercialNames)
{ numberOfComSites++;
}
System.out.print( "Enter the next site > ");
website = scan.next();
}
System.out.println( "You entered" + numberOfComSites + "commercial websites.");
}
}
Thanks!
You are using reference equality == to compare strings. You strings are from different sources. SENTINEL comes from constant pool, while website comes from user input. They are always different as references.
To compare strings by value, the equals method should be used. In your case you, should replace
while (website != SENTINEL)
by
while (!SENTINEL.equals(website))
Notice that we compares constant with user input. This address a problem when website is null. This is not the case in your code, but it is a sign of good style.
See What is the difference between == vs equals() in Java? for more information.
replace
while (website != SENTINEL)
with
while(!website.equals(SENTINEL))
website is of String type and is not a primitive type. So you need to use equals method to compare String. == is used for reference comparison.
Refer this for more details What is the difference between == vs equals() in Java?
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")
import java.util.*;
public class StudentWelcome
{
public static void main(String[]args)
{
Scanner in = new Scanner(System.in);
System.out.print("Please enter your student login");
char ident = in.next().charAt(0,1);
if (ident == '19')
{
System.out.println("Welcome Freshman")
}
else if (ident == '18')
{
System.out.println("Welcome Sophomore")
}
else if (ident.equals(17))
{
System.out.println("Welcome Sophomore")
}
else if (ident.equals)
}
}
I am basically trying to determine what year someone is by input"19johndo" or "17daquanra" and print the correct welcome statement. eclipse shows an error on line 13 that says invalid character constant. What should I do?
#VGR is right in the comment above, this is basic "introduction to Java" stuff. But since StackOverflow is a Q&A resource, and this is a Q, I'll provide an A.
There is no charAt(int, int) method on a String, so that line won't even compile. If you're really interested in the first 2 characters of the input String, then use substring(0, 2). That will return a String, not a char so you'll need to change the type of your ident variable. You'll also have to update how you compare ident in the if statements, since you're trying to compare against a (invalid) char literal. But chars can't be more than one character, so you need to compare against String literals, for example:
if (ident.equals("19")) {
That will get your code to compile and maybe even work correctly, but it's still not the best way to do what it seems like you're trying to do. But trying to discuss better implementations is beyond the scope of this question.
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I had a similar code to this using numbers, and it worked perfectly. This however keeps underlining the word else and I don't know why. I am just playing around with java trying to understand a few principles.
I want to program to reply one of two statements depending on input. Also, where it says if (input1 == "Hello");, I wanted to put if (input1 == "Hello" || "hello"); to accept lowercase too, but that showed errors too.
Just to be clear, if i remove the else clause, my program runs and both statements are printed!
import java.util.Scanner;
public class Input
{
public static void main(String[] args)
{
System.out.println("Hello there!");
Scanner Scan = new Scanner (System.in);
String input1 = Scan.nextLine();
Scan.close();
if (input1 == "Hello");
{
System.out.println("How are you?");
}
else
System.out.println("How rude, you didn't even say Hello!");
break;
}
}
}
Never use == to compare strings.
use .equals instead.
if (input1.equals("Hello"))
or
if (input1.equalsIgnoreCase("Hello"))
Delete the semicolon at the end of
if (input1 == "Hello");
EDIT:- As seen in your comments regarding OR.
You can try this:-
if(input1.equalsIgnoreCase("hello") || input1.equalsIgnoreCase("hey") || input1.equalsIgnoreCase("hi"))
Remove the ; at the end of your if statement. And use .equals() to compare strings.
The semicolon causes the compile error, while the == will cause a logical error once it does run.
You probably don't want the semicolon on the line
if (input1 == "Hello");
You also probably do not actually want to compare using == (read the linked question about comparing strings).
Third, why is there a break statement in your else clause?
You're looking for equalsIgnoreCase(). This compares two Strings without any regard to case.
Remove the ; after your if statement condition and add a { after else. Also, it is good practice to to use the equals(Object) method when comparing objects because you might get unexpected results when using ==.