"Incompatible operand types int and string" - java

I just started learning code (Java specifically), and i'm testing out a password system where when you type the password it becomes the variable "password" and it checks to see if it equals password2, the actual password. Here's the code:
import java.util.Scanner;
public class LogicalOperators {
public static void main(String args[]){
Scanner test = new Scanner(System.in);
int age;
int password;
String password2;
password2 = "Call of Duty";
System.out.println("Please enter your age:");
age = test.nextInt();
if (age >=18) {
System.out.println("You are old enough.");
System.out.println("Please enter the password:");
password = test.nextInt();
if (password == password2) {
System.out.println("Welcome back!");
}else{
System.out.println("The password you typed was incorrect.");
}
}else{
System.out.println("You are too young.");
}
}
}
I'm trying to check in the nested if statement whether the password I typed in matched password2, "Call of Duty"; but the problem is that it doesn't work with strings. The title of this question is the error that comes up. Can someone please help me?

I try to give a hint instead of providing the full answer:
Check the data types of password and password2. Why are they different?

when comparing strings you should use equals instead of ==
So use
if(password.equals(password2){
do something
}

You have to make a couple of changes.
First password should be of type String since you want to store a string here and compare it with another string.
Next, just after age = test.nextInt();, you should do a test.nextLine() to consume the newline at the end of the input. We don't want to read this when we read the password.
Next, you should use password = test.nextLine(); to read the password entered by the user.
Lastly, you should compare it using: if (password.equals(password2)). == compares whether both the String objects have the same references, i.e., whether they are the same String objects as known to Java. You want .equals() here because it would compare whether the content of the two String objects are equal. In this case, password and password2 refer to two different String objects which may have the same content.

Related

How do I fix the problem about name-password correspondence?

I am new at programming. I want to make a program that checks the input name and password are same or not, if it is, the program must say "Your name and your password cannot be same".My code is like below but even both of two input are same or different, result is same. What am i doing wrong?
import java.util.Scanner;
public class project {
public static void main(String[]args) {
Scanner scan = new Scanner(System.in);
System.out.println("Please Enter Your Name ");
String name =scan.nextLine();
System.out.println("Please Enter Yout Password for register");
String password=scan.nextLine();
if(name.equals(password.startsWith(password))) {
System.out.println("Your name and your password cannot be same");}
else {
System.out.println("Register is successful");
}
}
}
You should change this line:
if(name.equals(password.startsWith(password))) {
To:
if (name.equals(password)) {
Why it fails
It seems that you inadvertently added .startsWith(password) into the condition.
Explanation about what's happening
The expression password.startsWith(password) returns the boolean value true. Which causes the condition for the if statement to be: if(name.equals(true)) which always returns false because a String never equals() a boolean.

Taking websites as keyboard input?

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?

Is it possible to only check the first four letters of a string during: input.equals("USER test"); JAVA POP3

I'm trying to make a mail system with POP3 commands using java.
When a user logs in, they enter "USER" followed by their username e.g "USER ben"
in order to send them along their way I was wondering if here:
import java.util.Scanner;
public class TestingPart1 {
public static void main(String[]args){
int on = 1;
while (on == 1){
System.out.println("+OK POP3 server ready");
Scanner answer = new Scanner(System.in);
String Input = answer.nextLine();
**if (Input.equals.("USER test")){
CommandInterpreter.handleUser(Input);
}**
I would be able to only check the first four characters USER so that when it gets passed through to CommandInterpreter it still reads USER test, but passes this stage
thanks :)
if (Input.startsWith("USER ")) { ...
You can use a split with a space into a string array. Then evaluate whether the first element of the array is equal to "USER"
Input is unchanged by the split operation.

Comparing a Scanner to a String

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.

I Cannot Get If/Else Statement to Prove True with Scanner [duplicate]

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"

Categories