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.
Related
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 5 years ago.
I keep getting the 'good bye' response no matter what I enter, 'yes' or 'no'. How would I change that so responses are correct.
import java.util.Scanner;
public class SimpleQuiz1 {
public static void main(String[] args){
Scanner userInputScanner = new Scanner (System.in);
System.out.println("Are you ready to take this NBA quiz?");
String answer = userInputScanner.nextLine();
if(
answer == ("yes")){
System.out.println("Then lets get started!!!");
} else{
answer = ("no");
System.out.println("Goodbye, come again soon!");
}
}
}
Use String.equals(Object obj) rather than == as "==" will check for reference equality whereas .equals compares only the content not the reference.
Scanner userInputScanner = new Scanner(System.in);
System.out.println("Are you ready to take this NBA quiz?");
String answer = userInputScanner.nextLine();
if (answer.equals("yes")) {
System.out.println("Then lets get started!!!");
} else {
this should work fine.
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 5 years ago.
public class ex1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Please enter a series of strings each followed by the enter key. When you'd like to end thr program simply type 'quit': \n");
Scanner scan = new Scanner(System.in);
ArrayList<String> inputList = new ArrayList<String>(); // creates a list to store user input
String input = scan.nextLine(); //takes the scanner input
while(input != "quit") { //makes sure its not equal to quit
//System.out.println(input);
inputList.add(input);
input = scan.nextLine();
}
scan.close();
System.out.println("The number of strings enetered was: " + inputList.size());
System.out.println("The strings you entered were as follows");
for (String i: inputList) {
System.out.println(i);
}
}
}
I'm trying to use the preceding code to take a series of inputs from a user using the enter key and if they enter quit I end the program. However the condition is never satisfied and the while loop never ends and I can't understand why
while(!input.equals("quit")) { //makes sure its not equal to quit
//System.out.println(input);
inputList.add(input);
input = scan.nextLine();
}
You should use equals method as shown above to compare strings. Java provides equals method to compare the contents of two strings. == and != operators are used in comparing object equalities.
a == b returns true if, and only if, a points to the same object as b
The equals method should be used, as the String class implements it so that, if a contains the same characters as b, it would returns true.
while (!input.equals("quit")) { ... }
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 6 years ago.
I've got a problem with looping a scanner, wich should return EVERY string given as an input unless String != "end". Here is what I've done so far
private static String fetchString() {
Scanner scanner = new Scanner(System.in);
String stringElement = "";
System.out.println("Write a string");
while(scanner.hasNextLine()) {
stringElement = scanner.next();
if(stringElement == "end") {
break;
}
}
return stringElement;
}
result:
Write a string
abc
abc
abc
end
end
Loop, somehow, doesn't understand if(stringElement == "end"), it still wants new word. I can't get it. Where am I making a mistake?
First change, stringElement = scanner.next(); to stringElement = scanner.nextLine();, second change if(stringElement == "end") to if(stringElement.equals("end"))
This question already has answers here:
How can I read input from the console using the Scanner class in Java?
(17 answers)
Closed 7 years ago.
I'm trying to make it so when the user writes Start the program does something, but I'm unsure of how to what the user actually wrote.
This was my first attempt at it:
import java.util.Scanner;
public class Suhwag {
public static void main (String args[]){
Scanner scanNer = new Scanner (System.in);
System.out.println("Please write \"Start\" to begin.");
String stinky = "Start";
if (stinky == scanNer);
But with this, I got the error message:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Incompatible operand types String and Scanner
After I saw the error, I tried to convert scanNer to a string as seen here:
import java.util.Scanner;
public class Suhwag {
public static void main (String args[]){
Scanner scanNer = new Scanner (System.in);
System.out.println("Please write \"Start\" to begin.");
String stinky = "Start";
String input = scanNer.nextLine();
if (stinky == scanNer);
But the same error message still appears. Anyone know what I could do to make it work?
You're trying to compare a Scanner object with a String object. First, you could input the string with the following line:
String myString = scanNer.next()
Then, compare it with "Start":
if ( myString.equals( "Start" ) )
{
...
}
You are comparing a String to a Scanner object.
You should use the equals method to compare String's
No need for the semi-colon after the if (see below)
In reference to your last code snippet:
if (stinky.equals(input)){
//do something
}
in the latter code area you said in your if statement:
stinky == scaNer
it should be
stinky.equals(input)
in your if statement, you compared still your scanner with ur stinky
change your if statment to this
if (input.equals(stinky)){<code here>}
your previous code didnt work because you compare a scanner with a string
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?