This question already has an answer here:
How to use java.util.Scanner to correctly read user input from System.in and act on it?
(1 answer)
Closed 5 years ago.
how can I give a condition on an input from "system.in" that will halt the program until the right value is inserted?
for exemple, I'm waiting for an INT from the user, 1,2,3,4 or 5
the user inputs "hello"
how can i give the user a message of "Invalid input, try again"
and keep the program at halt until he does give the right one?
update: I didnt came so you can write my code, right now it looks something like this:
int j=UserIn.nextInt();
switch (j) {
case 1:
break;
case 2:
writetoDic(word, "dict.txt");
break;
case 3:
word = correction;
break;
i'm asking that, if im getiing something else than an int from the user, how can i ask the user to give a valid argument instead of just getting an error?
You need to use a loop. I don't think you actually mean halt the program, but actually preventing to program to proceed until valid input. You can do something like this
Scanner scanner = new Scanner(System.in);
int num;
while (true) {
try {
System.out.println("Enter a number: ");
num = scanner.nextInt();
if (num >= 1 && num <= 5) {
break;
}
} catch (InputMistmatchException ex){
System.err.println("Input needs to be a number between 1 and 5, dummy.");
}
}
Program will run if not between 1 and 5 and not an integer
Related
This question already has answers here:
How would I use a while loop to keep requesting user input
(3 answers)
Closed 2 years ago.
I have looked at other StackOverflow questions on this topic but being a new developer I am extremely confused. I am trying to write a program that asks the user riddles and restarts after the user gets three wrong answers on one specific riddle. The code that needs the restart is:
if (wrongAnswer == 3){
System.out.println("You have failed three times.");
restartApp();
The code where I need to restart should go right where the restartApp() is right now.
Thanks in advance!
So, as Turing85 mentioned, restarting the whole program probably isn't the way to go. Generally, you use what's called a state machine. For this example, a simple one can be implemented with a while loop. Here's an example:
import java.util.Scanner;
public class foo
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
boolean running = true;
while(running){
System.out.println("enter a value, enter -1 to exit...");
int value = scan.nextInt();
if(value == -1){
System.out.println("exiting");
break;
}else{
System.out.println("do stuff with the value");
}
}
}
}
and here's the output:
enter a value, enter -1 to exit...
1
do stuff with the value
enter a value, enter -1 to exit...
2
do stuff with the value
enter a value, enter -1 to exit...
4
do stuff with the value
enter a value, enter -1 to exit...
-1
exiting
This question already has answers here:
java.util.NoSuchElementException - Scanner reading user input
(5 answers)
Closed 3 years ago.
I m new, please have patience with me :)
I m not figure out why this method it s not working properly. It is creating me the account but, when the account was successfully created, it s not running well on the same method mainMenu(). I used a recursive call of the same method....
In the debug seems that it s not something well with my scanner from the second call of the method.
I m a Student
public void mainMenu() {
System.out.println("Select your option: ");
System.out.println("1. Open a new account");
System.out.println("2. Display all accounts");
System.out.println("If you want to logout press 9");
Scanner sc = new Scanner(System.in);
int option = 0;
do {
try {
option = sc.nextInt();
System.out.println();
switch (option) {
case 1:
accountUtil.openNewAccount(userConsoleUtil.getUser().getUserName());
mainMenu();
break;
case 9:
userConsoleUtil.logout();
displayLoginMenu();
break;
default:
System.out.println("Invalid option! Try again");
}
} catch (InputMismatchException e) {
System.out.println("Invalid option! Try again");
}
sc.nextLine();
} while (option != 9);
sc.close();
}
if the object account was created, it should return to beginning of the method, allowing to create a new account or exit with logout
It feels like you mistakenly wrote sc.nextLine() which takes an input from the user.
After the the end of catch block the line sc.nextLine() might give you unexpected output
Given your current code and the comments, it looks like you're creating scanners in your other methods and closing them. Don't do that. When you close the scanner, you also close System.in, leading to a NoSuchElementException.
Read this
If I run this code
Scanner sc = new Scanner();
while (true) {
if (sc.next().equals("1"))
System.out.println("--1--");
else if (sc.next().equals("2"))
System.out.println("--2--");
else if (sc.next().equals("3"))
System.out.println("--3--");
else if (sc.next().equals("4"))
System.out.println("--4--");
else if (sc.next().equals("help"))
System.out.println("--help--");
}
It will not read the first time I type enter. I have to type 2-4 times before it reads the input. A session could look like this:
1
1
1
1
--1--
3
3
--3--
help
2
1
help
--help--
No matter what I type, it will only read the last input of the four inputs.
Sometimes it reads after two inputs. I'm really confused about this.
Should I instead use multiple scanners?
Your concepts are wrong here.
Each time you ask for sc.next() it will wait for the input. If that input is equal to what you want it to be, then the code is executed.
You can correct this by storing sc.next() in a String variable, and then comparing it.
Here:
if (sc.next().equals("1"))
it asks for an input.
If that input is 1 then the code is executed and --1-- is printed out. Else, it jumps to this: if (sc.next().equals("2")). Now if the input is 2 then the code to print --2-- is executed. Else, it jumps to if (sc.next().equals("3")) and so on.
You can correct this by:
storing sc.next() in a String variable, and then comparing it.
using a switch-case block to compare the input.
You're calling sc.next() multiple times - so if the input isn't 1, it's going to wait for more input to see whether the next input is 2, etc. Each call to sc.next() will wait for more input. It doesn't have any idea of "that isn't the input you were looking for, so I'll return the same value next time you call".
Use a local variable to store the result of sc.next()
while (true) {
String next = sc.next();
if (next.equals("1"))
System.out.println("--1--");
else if (next.equals("2"))
System.out.println("--2--");
else if (next.equals("3"))
System.out.println("--3--");
else if (next.equals("4"))
System.out.println("--4--");
else if (next.equals("help"))
System.out.println("--help--");
}
Also consider using a switch statement instead...
You are calling sc.next() multiple times
Solution code :
Scanner scanner = new Scanner(System.in);
while(true){
switch (scanner.next()) {
case "1":
System.out.println("--1--");
break;
case "2":
System.out.println("--2--");
break;
case "3":
System.out.println("--3--");
break;
case "4":
System.out.println("--4--");
break;
case "help":
System.out.println("--help--");
break;
default:
break;
}
}
I wasn't sure how to give a title for this problem, but basically this is part of my blackjack program. Also, since I did not know how to title this, I wasn't sure how to look it up, which is why I am asking here. So I am saying that when the user enters either 1 or 11 for the ace value, if they enter something other than 1 or 11, it asks the user again to put in 1 or 11. In my program everything works fine except when the user enters 1, then it just asks the question again. The program should only asks again if the input is not equal to 1 or 11. Here is my code as I made sure it always gives an ace for testing purposes:
String card1="A";
int total=0;
Scanner input_var=new Scanner(System.in);
if (card1=="A"){
System.out.println("Do you want a 1 or 11 for the Ace?: ");
int player_ace_selection=input_var.nextInt();
if ((1|11)!=(player_ace_selection)){
System.out.println("Please enter a 1 or 11: ");
int new_selection=input_var.nextInt();
total=total + new_selection;
}
else {
total=total + player_ace_selection;
}
}
System.out.println(total);
Thanks in advance.
The expression (1|11) uses binary OR, which produces 11:
11 = 01001
1 = 00001
(11|1) = 01001
Hence, the comparison is the same as 11!=player_ace_selection
You should change the code to use logical OR, i.e.
if (1!=player_ace_selection && 11!=player_ace_selection) {
...
}
In addition, you need to fix card1 == "A" comparison for card1.equals("A")
Instead of an If statement, try a while loop. A while loop ensures that your program waits for your user to pick the right answer. You also made a mistake with your logical operations. The correct way to use "OR" in this context is to compare your user input to both '1' and '11' separately using '||'.
String card1="A";
int total=0;
Scanner input_var=new Scanner(System.in);
if (card1.equals("A")){
System.out.println("Do you want a 1 or 11 for the Ace?: ");
int player_ace_selection=input_var.nextInt();
while(player_ace_selection != 1 && player_ace_selection != 11){
System.out.println("Do you want a 1 or 11 for the Ace?: ");
player_ace_selection = input_var.nextInt();
}
total += player_ace_selection;
}
System.out.println(total);
There are some problems in your code, please consider this example and compare it with yours.
String card1="A";
int total=0;
Scanner input_var=new Scanner(System.in);
if (card1.equals("A")){ // compare the content not the reference (==)
System.out.println("Do you want a 1 or 11 for the Ace?: ");
try{ // wrap with try-catch block
int player_ace_selection = Integer.parseInt(input_var.nextLine()); //read the entire line and parse the input
if ((player_ace_selection!=1)&&(player_ace_selection!=11)){
System.out.println("Please enter a 1 or 11: ");
try{
int new_selection = Integer.parseInt(input_var.nextLine()); //again read the entire line and parse the input
total=total + new_selection;
}catch(NumberFormatException e){
// do something to catch the error
}
}
else {
total=total + player_ace_selection;
}
}catch(NumberFormatException e){
// do something to catch the error
}
System.out.println(total);
}
Now I know that there is a thread called "Validating input using java.util.Scanner". I already looked there and that thread only answered 1/2 of my problems. The other half is when someone enters a number greater than 2 I get Array Index Out of Bounds Exception. I just need help on if someone enters a 3 for either row or column, the console should prompt something like this:
"Enter the coordinates to place an 'X'. Row then Column."
//enters 3 and 3
"Please enter a valid input"
It would keep and asking the user for a valid number until he gives one.
Would I need to do something like the !keyboard.hasNextInt() but for integers? And that would run smoothly with the rest of my code?
You could use a do-while loop. Something like
do {
//prompt
//input
} while (input not valid);
Where prompt and input should be replaced by code to prompt the user and accept input. In the while section, check if input is valid.
You're question isn't too clear but I'll try to make sense of it.
I'm assuming you've named your scanner "keyboard"
Before I try running this code, the first problem I can see is this (Note that I grabbed this from your code before you edited the question):
while (board[row][col] != ' ')
{
System.out.println("Already occupied space");
System.out.println("Choose again");
row = keyboard.nextInt();
col = keyboard.nextInt();
}
Earlier, you made sure that the user enters integers. However, you have abandoned that completely in this case.
Assuming you're trying to avoid an error if the user enters something other than an integer, this is what I would do:
while(true){
boolean valid = true;
if(!keyboard.hasNextInt()){
valid = false;
keyboard.next();
}
else{
row = keyboard.nextInt();
}
if(!keyboard.hasNextInt()){
valid = false;
keyboard.next();
}
else{
col = keyboard.nextInt();
}
if (valid && (row > 2 || col > 2)){
System.out.println("Please enter a valid input");
continue;
}
else if(!valid){
System.out.println("Please enter a valid input");
continue;
}
else
break;
}
There are a couple reasons this code might seem a bit long. First off, we're trying to test if the input is an integer before we attempt to store it as an int. Secondly, we want to compare the input after we store it successfully to see if it's less than 3. If the input isn't an integer, the boolean "valid" will be false. The way a compiler works, if valid is false in the if statement it will ignore anything to the right of the &&, avoiding an error.
I admit, this is using some commands that I haven't learned before, so this might not be the most efficient way. But you get the idea :)
P.S. You should probably throw the above code into a method.