How do Java scanner read string correctly [duplicate] - java

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 1 year ago.
String command = "";
Scanner sc = new Scanner(System.in);
while (command!="exit")
{
System.out.println("Please enter command: ");
command = sc.nextLine();
System.out.println("You enter: "+command);
if (command == "exit")
{
System.out.println("Exit program.");
}
}
sc.close();
Haven't written java in a year and I forgot how scanner work. The code would never enter the if part when I enter exit. I tried next() and nextLine().

Because operator == compares the address memory not the value for String variable. You need to use equals() method.
command.equals("exit")

Related

Why can't I type multiple inputs inside try/catch? [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
How do I compare strings in Java?
(23 answers)
Closed 2 years ago.
I'm having difficulties trying to get multiple inputs inside a do-while loop, inside a try/catch statement:
FileOutputStream file;
PrintStream pen;
String name;
char exitInput;
try {
file = new FileOutputStream("names.txt");
pen = new PrintStream(file);
do {
System.out.print("Enter a name: ");
name = input.nextLine();
pen.print(name + "\n");
System.out.println("Would you like to enter more names?");
System.out.print("Option(y/n): ");
exitInput = input.next().charAt(0);
} while(exitInput != 'n');
pen.close();
} catch(IOException exc) {
System.out.println("<INPUT ERROR>");
}
When I run this code, it ask me for a name, then ask me if I want to enter more names. If I choose YES, then it just skips the "name = input.nextLine();" line and display:
Enter a name: Would you like to enter more names?
Option(y/n):
Issue appears to solve when typing two "name = input.nextLine();", however, that's not a great solution.
input.next() consume only one token, not entire line. when you call input.nextLine() it consume rest of that line.
To fix that replace input.next() with input.nextLine().

Do while loop in java not working [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
java.util.NoSuchElementException - Scanner reading user input
(5 answers)
Closed 5 years ago.
I'm pretty new to coding, and I understand how to do a do while for a yes or no answer in C++. But java is giving me a hard time. This code doesn't give me any errors until I run it. When it asks for the yes or no answer it will say:
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at midterm.main(midterm.java:40)
Line 40 is the:
ans = s.next();
Maybe I'm doing something wrong with String, I've tried char but had no luck either. Here is my code:
public class midterm
{
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
String ans;
do
{
System.out.println("Welcome to the Menu!\nA)Guessing Game\nB)Calculator\n"
+ "\nEnter Letter: ");
String letter = s.next();
s.nextLine();
if ((letter.equals("A")) || (letter.equals("a")))
{
guessingGame();
}
else
{
calcDecide();
}
System.out.println("\nWould you like to go back to the menu or exit?\n"
+ "Press 'Y' yes or 'E' for exit: ");
ans = s.next();
s.nextLine();
}while (ans == "y" || ans == "y");
s.close();
}
Not sure why this was marked as a duplicate. I feel that people don't read the entire thing and like to assume this. This WAS NOT a simple String mess-up(That's part of the mistake,) but there's a bigger issue here, which I believe to be the scanner

How to keep asking for user input until the input is empty? [duplicate]

This question already has answers here:
Validating input using java.util.Scanner [duplicate]
(6 answers)
Closed 7 years ago.
I want to make a while loop so that whenever a user inputs a blank input, it will re-ask the question until it is not empty. So far, I have this:
Scanner scn = new Scanner(System.in);
while (//user input is not blank) {
System.out.print("Enter id: ");
int id = scn.nextInt();
System.out.print("Enter name: ");
String last_name = scn.next();
System.out.print("Enter phone: ");
String first_name = scn.next();
scn.close();
break;
}
i'm pretty sure i'm over thinking this but i'm not sure of the syntax or the functions.
You should expect user to type say Quit/quit to quit rather than empty string.
You should close scanner out of loop without break.
You should use do...while loop instead if while loop. Something like:
do {
...
exit = scn.next();
} while (!exit.equalsIgnoreCase("quit"));
scn.close();

Comparing console input from executable jar [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 7 years ago.
So I have this executable jar file with a username and password and runs but value doesn't ever continue correctly.
Here is an example:
public static void main(String[] args) {
System.out.println("Hello. I am a program created by Moocow9m. What is your name?");
InputStream stream = System.in;
Scanner scanner = new Scanner(stream);
String input = scanner.next();
if (input == "armystich"){
System.out.println("Welcome CODE NAME: ArmyStich!");
scanner.close();
}
else {
System.out.println("Hello " + input + ". Nice to meet you.");
scanner.close();
}
}
}
All would work except it would always return to else. Please help.
if (input == "armystich"){
The above checks reference equality. To check for value equality, using the equals method
if ( input.equals("armystich") ){
See How do I compare strings in Java?

While loop in Java, string comparison does not work [duplicate]

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?

Categories