scanner.next() does not stop [duplicate] - java

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
public class ElectronicCounter {
public ElectronicCounter(User user)throws IOException{
Scanner scanner = new Scanner(System.in);
boolean done = false;
loginName = user.getName();
System.out.println("--------------------------------------------------------");
System.out.println("Welcome to the Electronic-Sales Counter! ");
while(!done){
try{
System.out.print("Please enter '1' to record sales or '2' to exit:");
input = scanner.nextLine();
System.out.println("bug");
if(input=="1"){
System.out.println("Please enter a list of purchasing-product ID and number");
done = true;
}
else if(input=="2"){
System.out.println("<LOG> User " +loginName+ " has successfully logged off! ");
done = true;
}
else{
System.out.println("<LOG> Invalid command");
}
}
catch (NoSuchElementException e){
System.out.println("<LOG> No Such Element");
}
catch (IllegalStateException e){
System.out.println("<LOG> IllegalState");
}
}
scanner.close();
}
static String loginName;
static String input;
}
The scanner doesn't stop to search the token when scanner.nextLine() is computed. I would like to ask how can I stop the scanner to wait input??Thanks

NEVER compare strings using ==. When using == to compare string objects, you are not comparing it's values but it's references.
Always compare using the equals method.
input.equals("2");

Related

Java Why Scanner doesn't recognise user input [duplicate]

This question already has answers here:
String.equals versus == [duplicate]
(20 answers)
How do I compare strings in Java?
(23 answers)
Closed 11 months ago.
I wrote a function to receive user input. Can't get the correct answer back. Always Failure. I am losing my mind right now.
public String getChoice() {
Scanner SC = new Scanner(System.in);
System.out.print("Ready to play? (Y/N) ");
String playChoice = SC.next(); // Input Y or N
playChoice = playChoice.replace("\n", "");
System.out.println("Input length is: " + playChoice.length());
System.out.println(playChoice);
if (playChoice == "N") {
SC.close();
return "Success N";
}
else if (playChoice == "Y") {
SC.close();
return "Success Y";
}
SC.close();
return "Failure"; // Always this one works
}
Try this:
public String getChoice() {
Scanner SC = new Scanner(System.in);
System.out.print("Ready to play? (Y/N) ");
String playChoice = SC.next(); // Input Y or N
playChoice = playChoice.replace("\n", "");
if (playChoice.equals("N")) { // Replace operator '==' with 'equals()' method.
SC.close();
return "Success N";
} else if (playChoice.equals("Y")) { // Same here.
SC.close();
return "Success Y";
}
SC.close();
return "Failure"; // Always this one works
}
The reason why your code is not working as intended, is that the == operator compares whether the 2 compared object references are pointing to the same object. This obviously is not the case in your if-statements, and therefore those expressions will always evaluate to false.
the equals() method on the other hand actually compares the content of the given objects , thus delivering the desired result.
#Bialomazur gave an explanation already and here is a bit cleaner code and tips.
Actually, closing Scanner is not a good practice, but if you decided to, you can close it before your ifs just in one place, since you are not using scanner anymore.
Also, switch looks better here
public String getChoice() {
Scanner SC = new Scanner(System.in);
System.out.print("Ready to play? (Y/N) ");
String playChoice = SC.next(); // Input Y or N
playChoice = playChoice.replace("\n", "");
System.out.println("Input length is: " + playChoice.length());
System.out.println(playChoice);
SC.close();
switch (playChoice) {
case "Y":
return "Success Y";
case "N":
return "Success N";
default:
return "Failure";
}
}

Why can I only use 1 word in a string through input scanner? [duplicate]

This question already has answers here:
Read multiple word strings with java.util.Scanner() [duplicate]
(2 answers)
Closed 2 years ago.
Still fairly new to Java and I am having trouble with this loop. the first issue is that I can only enter a single word for newName, if I try and enter more then one word, it uses the input for the newCode as well and skips through. I just can't figure out why I cant enter a name that has more then 1 word in a string. when I try and add a string with 3 words in it it skips the newCode then throws an error.
int addAnother = 1;
while (addAnother == 1) {
System.out.print("Enter a new Subject Name: ");
String newName = input.next(); //only accepting a single word...
System.out.print("Enter a new Subject Code: ");
String newCode = input.next(); // must be entered in CAPS
Subject newSubject = new Subject(newName, newCode);//create object
if (newSubject.isValidCode(newCode) == true){
System.out.println("The code meets the requirements");
if (newSubject.codeExist(newCode, subjectList) == false){
subjectList.add(newSubject);
System.out.println("Your Subject has been added");
}
else
System.out.println("The code you entered already exists");
}
else
System.out.println("Your subject code does not "
+ "meet the requirements i.e. ITC206");
System.out.println ("\nEnter a new subject? 1=Yes 2=No");
addAnother = input.nextInt();
}
I am just not sure what I am doing wrong....
Use nextLine() method instead of next().
private String read()
{
Scanner scanner = new Scanner(System.in);
return scanner.nextLine();
}
https://www.geeksforgeeks.org/difference-between-next-and-nextline-methods-in-java/

using try catch in a while loop (java) [duplicate]

This question already has answers here:
How to handle infinite loop caused by invalid input (InputMismatchException) using Scanner
(5 answers)
Closed 2 years ago.
I wanted to write a simple program that asks for a number, if the user inputs a number it will end, otherwise it will print an error and ask again for a number. The problem is that my program just keeps printing the error message ("Not a valid input. Error :null") and never asks for a number again.
import java.util.InputMismatchException;
import java.util.Scanner;
public class Numbers {
public static void main(String[] args){
number();
}
public static int number() {
System.out.print("Enter a number: ");
Scanner readLine = new Scanner(System.in);
boolean isInteger = false;
while (!isInteger) {
try {
int numbers = readLine.nextInt();
System.out.println(numbers);
isInteger = true;
} catch (InputMismatchException e) {
System.err.println("Not a valid input. Error :" + e.getMessage());
}
}
return 0;
}
}
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
if (sc.hasNextInt()) {
int number = sc.nextInt();
System.out.println(number);
} else {
System.err.println("Not a valid input. Error :" + sc.next());
}
}

Java: Terminating the while loop after pressing "Q" key [duplicate]

This question already has answers here:
How to read a single char from the console in Java (as the user types it)?
(7 answers)
Closed 5 years ago.
I have this following java program which is working fine without while loop, but I want to run the execution until user pressed Q key from the keyboard.
So What condition should be put in while loop which breaks the loop?
import java.awt.event.KeyEvent;
import java.util.Scanner;
import static javafx.scene.input.KeyCode.Q;
public class BinaryToDecimal {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while(kbhit() != Q){
System.out.print("Input first binary number: ");
try{
String n = in.nextLine();
System.out.println(Integer.parseInt(n,2));
}
catch(Exception e){
System.out.println("Not a binary number");
}
}
}
}
Any help would be great.
Thank You.
I don't think you can use KeyEvent within a console application as there's no keyboard listener defined.
Try a do-while loop to watch for an input of the letter q. And you should compare strings using equals method
Scanner in = new Scanner(System.in);
String n;
System.out.print("Input first binary number: ");
do {
try{
n = in.nextLine();
// break early
if (n.equalsIgnoreCase("q")) break;
System.out.println(Integer.parseInt(n,2));
}
catch(Exception e){
System.out.println("Not a binary number");
}
// Prompt again
System.out.print("Input binary number: ");
} while(!n.equalsIgnoreCase("q"));
What about this?
public class BinaryToDecimal {
public static void main(String[] args) {
System.out.print("Input first binary number: ");
Scanner in = new Scanner(System.in);
String line = in.nextLine();
while(!"q".equalsIgnoreCase(line.trim())){
try{
System.out.println(Integer.parseInt(line,2));
System.out.print("Input next binary number: ");
line = in.nextLine();
}
catch(Exception e){
System.out.println("Not a binary number");
}
}
}
}

Java incorrect input [duplicate]

This question already has answers here:
Validating input using java.util.Scanner [duplicate]
(6 answers)
Closed 6 years ago.
public static void main(String[] args) {
{
Scanner reader = new Scanner(System.in);
System.out.println("Enter your name: ");
String n = reader.nextLine();
System.out.println("You chose: " + n);
}
{
Scanner reader = new Scanner(System.in);
System.out.println("Enter your age: ");
int n = reader.nextInt();
System.out.println("You chose: " + n);
}
{
Scanner reader = new Scanner(System.in);
System.out.println("Enter your email: ");
String n = reader.nextLine();
System.out.println("You chose: " + n);
}
}
If a user places anything else under Enter your age other than a number, how do I make it say that the input is not correct and ask again?
You can get the line provided by the user, then parse it using Integer.parseInt(String) in a do/while loop as next:
Scanner reader = new Scanner(System.in);
Integer i = null;
// Loop as long as i is null
do {
System.out.println("Enter your age: ");
// Get the input from the user
String n = reader.nextLine();
try {
// Parse the input if it is successful, it will set a non null value to i
i = Integer.parseInt(n);
} catch (NumberFormatException e) {
// The input value was not an integer so i remains null
System.out.println("That's not a number!");
}
} while (i == null);
System.out.println("You chose: " + i);
A better approach that avoids catching an Exception based on https://stackoverflow.com/a/3059367/1997376.
Scanner reader = new Scanner(System.in);
System.out.println("Enter your age: ");
// Iterate as long as the provided token is not a number
while (!reader.hasNextInt()) {
System.out.println("That's not a number!");
reader.next();
System.out.println("Enter your age: ");
}
// Here we know that the token is a number so we can read it without
// taking the risk to get a InputMismatchException
int i = reader.nextInt();
System.out.println("You chose: " + i);
No need to declare a variable scanner so often, simply once
care with nextLine(); for strings; presents problems with blanks, advise a .next();
use do-while
do
{
//input
}
while(condition);//if it is true the condition returns to do otherwise leaves the cycle
use blocks try{ .. }catch(Exception){..}
to catch exceptions mismatch-input-type exception is when the input is not what I expected in the example enter a letter when a number expected
Scanner reader = new Scanner(System.in);
int n=0;
do
{
System.out.println("Enter your age: ");
try {
n = reader.nextInt();
}
catch (InputMismatchException e) {
System.out.print("ERROR NOT NUMBER");
}
}
while(n<0 && n>100);//in this case if the entered value is less than 0 or greater than 100 returns to do
System.out.println("You chose: " + n);

Categories