java do while asked for input twice - java

why do I need to input 2 times? please help I'm new to java, can't find the error
do {
System.out.println("Enter your age: ");
age= in.nextInt();
if(!in.hasNextInt()) {
System.out.println("Please enter a valid age");
in.nextInt();
valid=false;
}
}while(valid);
I removed the do while but it still asks for the second input
System.out.println("Enter your age: ");
age= in.nextInt();
if(!in.hasNextInt()) { //Will run till an integer input is found
System.out.println("Please enter a valid age");
in.nextInt();
valid=false;
}

I have updated your code. This will work for you.
public class Example
{
public static void main(String[] args) {
boolean valid = true;
do {
Scanner in = new Scanner(System.in);
System.out.println("Enter your age: ");
while(!in.hasNextInt()) {
System.out.println("Please enter a valid age");
in.next();
valid = false;
}
int age = in.nextInt();
} while(valid);
}
}
Output :
Enter your age:
2
Enter your age:
seven
Please enter a valid age
seven
Please enter a valid age
3
Explanation : If you are giving valid data, then the loop will continue to take inputs (not taking inputs twice). As soon as, you give invalid data, then, the code will prompt you to enter the valid data and loop will stop executing as you made valid = false.

The reason why it asks you for input twice is due to you in.hasNextInt() which will check your scanner for input from the system. Since your system does not have any input due to you calling age = in.nextInt(); which will move the scanner to the next word before your in.hasNextInt(), The function in.hasNextInt() will require you to input something so that it can validate if it is an Int or not.
what we want to do, is to first check the current scanner's input if it has an integer before we either store it inside age or loop again and ask for new input.
A better way of checking would be to do something like this.
import java.util.*;
class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int age = 0;
System.out.println("Enter your age: ");
while(!in.hasNextInt()){// checks if scanner's next input is an int, return true if next input is not an Int and the while loop continues till the next input is an Int
System.out.println("Please enter a valid age: ");
in.nextLine();//move the scanner to receive the next nextLine
//this is important so the hasNextInt() wont keep checking the same thing
}
//it will only exit the while loop when user have successfully enter an interger for the first word they inputted.
age = in.nextInt();
System.out.println("Your age is: " + age);
}
}
Output:
Enter your age:
boy
Please enter a valid age:
boy girl
Please enter a valid age:
5
Your age is: 5

Hi : D there is becuase of the !in.hasNextInt() it will cause you need to do the input again but you can change it to other condition like if the age is bigger than certain value.
public class stackTest {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int age =0 ;
boolean valid = false;
do {
System.out.println("Enter your age: ");
age= in.nextInt();
if(age>90) {
System.out.println("Please enter a valid age");
valid=true;
}
else valid=false;
}while(valid);
System.out.println("Age: " + age);
}
}

You should move the System.out.println("Enter your age: "); statement outside the do-while loop.

Related

Scanner keyboard not working on one of the values in my ParkingCarSimulator Java program [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 1 year ago.
I am working in the ParkingCarSimulator programming challenges of the starting out with java book but I found a problem and I can't really see what is wrong, it seems right and the same than all the other ones. So I am getting the user to input values for officer name, officer badge, car make, car model, etc. The program is compiling good and seems fine but when you run it and start entering the info, you will notice that entering the info for the officer name is good, same for the officer badge but next should be car's make but it just skips that and goes into car's model and I can't really see why, any ideas? here is the code(check 3rd println):
public class ParkingCarSimulator {
public static void main(String[] arsg)
{
String officerName, Make, carModel, carColor, carLicense;
int badgeNumber, minOnCar, minPurchased;
double fine = 0;
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the officer's name");
officerName = keyboard.nextLine();
System.out.println("Enter officer's badge number");
badgeNumber = keyboard.nextInt();
System.out.println("Enter the car's make");
Make = keyboard.nextLine();
System.out.println("Enter the car's model");
carModel = keyboard.nextLine();
System.out.println("Enter the car's color");
carColor = keyboard.nextLine();
System.out.println("Enter the car's liscence number");
carLicense = keyboard.nextLine();
System.out.println("Enter minutes on car");
minOnCar = keyboard.nextInt();
if(minOnCar <= 0) {
System.out.println("Invalid Entry. Please try again.");
minOnCar = keyboard.nextInt();
}
System.out.println("Enter the number of minutes purchased");
minPurchased = keyboard.nextInt();
if(minPurchased <= 0) {
System.out.println("Invalid Entry. Please try again.");
minPurchased = keyboard.nextInt();
}
if(minOnCar > minPurchased) {
fine = 25.0;
}
if(minPurchased < minOnCar) {
System.out.println("Car parking time has expired");
System.out.println("\nTicket Data:");
System.out.println("\nMake: " + Make);
System.out.println("\nModel: " + carModel);
System.out.println("\nColor: " + carColor);
System.out.println("\nLiscence Number: " + carLicense);
System.out.println("\nOfficer Name: " + officerName);
System.out.println("\nBadge Number: " + badgeNumber);
System.out.println("\nFine: " + fine);
} else {
System.out.println("The car parking minutes are valid");
}
}
}
.nextLine() reads the "enter" you hit once you enter the value of badgeNumber. In order to fix this, you can do this in your code:
System.out.println("Enter officer's badge number");
badgeNumber = keyboard.nextInt();
System.out.println("Enter the car's make");
Make = keyboard.nextLine(); //this takes up the enter value when it is pressed
Make = keyboard.nextLine(); //changing the value of Make to the string the user enters.
Here's another link that could help you: Scanner is skipping nextLine() after using next() or nextFoo()?

Scanner doesnt read input in else statement

Im trying to ask the user for two numbers. I want to check if those inputs are in fact numbers but the code I have so far does not let me enter a second value if the first input is a string.
So the scanner does not read anything the else statement.
How could I make it work?
import java.util.Scanner;
public class calculations {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.print("Please enter your first name: ");
String fname = console.nextLine();
System.out.print("Please enter your last name: ");
String lname = console.nextLine();
System.out.print("Please enter your first number: ");
if (console.hasNextInt()) {
int number1 = console.nextInt();
System.out.print("Please enter your second number: ");
if (console.hasNextInt()) {
int number2 = console.nextInt();
}
} else
System.out.print("Please enter your second number: ");
if (console.hasNextInt()) {
int number2 = console.nextInt();
// this part does not work
}
}
}
You just need to add console.nextLine(); after your else statement, because the Scanner.hasNextInt method does not move cursor past your previous input (if it is a string).

Array list scanner loop quit functionality

import java.util.ArrayList;
import java.util.Scanner;
public class test {
public static void main(String[] args) {
ArrayList<String> name = new ArrayList<String>();
ArrayList<String> game = new ArrayList<String>();
ArrayList<Integer> score = new ArrayList<Integer>();
ArrayList<Integer> time = new ArrayList<Integer>();
Scanner scanner = new Scanner(System.in);
String answer = "yes";
{
do {
System.out.print("Please enter your username: ");
name.add(scanner.nextLine());
System.out.println("Please enter the game: ");
game.add(scanner.nextLine());
System.out.println("Please Enter Achievement Score: ");
score.add(scanner.nextInt());
System.out.println("Please Enter Playtime: ");
time.add(scanner.nextInt());
System.out.print("Any letter to continue alternatively type quit to Quit.");
answer = scanner.next();
} while (!answer.equals("quit"));
if (answer.equals("quit")); //want it to go back to start another direcotry here
else {
System.out.println("Thanks for adding to the database.");
for (int i = 0; i < name.size(); i++) {
System.out.print("Username:" +name.get(i)+"\n");
System.out.print("~~~~~~~~~~~~" +"\n");
System.out.print("Game:" +game.get(i)+"\t");
System.out.print("Score:" +score.get(i)+"\n");
System.out.print("Minutes played:"+time.get(i));
System.out.println("");
}
}
}
}
}
The problem with this is that the program is not quitting upon typing Quit but it is continuing and placing two questions on one line, shown below. how can I solve this problem?
Please enter your username: abc123
Please enter the game:
GTA V
Please Enter Achievement Score:
1200
Please Enter Playtime:
120
Any letter to continue alternatively type quit to Quit.Quit
Please enter your username: Please enter the game:
The issue is that you are comparing upper and lower case values of quit. You need to set them to the same case type for them to be equal and quit the program.
change your check to
while (!answer.toLowerCase().equals("quit"));
if (answer.toLowerCase().equals("quit"));
and that will change your input to lowercase which is what your are comparing it to.
I don't see any problem except that you have not closed the scanner. You can run this and you can see that the scanner is closed and go to normal execution after word quit.
import java.util.ArrayList;
import java.util.Scanner;
public class ScannerTest {
public static void main(String[] args) {
ArrayList<String> name = new ArrayList<String>();
ArrayList<String> game = new ArrayList<String>();
ArrayList<Integer> score = new ArrayList<Integer>();
ArrayList<Integer> time = new ArrayList<Integer>();
Scanner scanner = new Scanner(System.in);
String answer = "yes";
{
do {
System.out.print("Please enter your username: ");
name.add(scanner.nextLine());
System.out.println("Please enter the game: ");
game.add(scanner.nextLine());
System.out.println("Please Enter Achievement Score: ");
score.add(scanner.nextInt());
System.out.println("Please Enter Playtime: ");
time.add(scanner.nextInt());
System.out.print("Any letter to continue alternatively type quit to Quit.");
answer = scanner.next();
} while (!answer.equals("quit"));
if(answer.equals("quit")){
System.out.println("you have just quit");
scanner.close();
} //want it to go back to start another direcotry here
else {
System.out.println("Thanks for adding to the database.");
for (int i = 0; i < name.size(); i++) {
System.out.print("Username:" +name.get(i)+"\n");
System.out.print("~~~~~~~~~~~~" +"\n");
System.out.print("Game:" +game.get(i)+"\t");
System.out.print("Score:" +score.get(i)+"\n");
System.out.print("Minutes played:"+time.get(i));
System.out.println("");
}
}
System.out.print("You are done with scanner");
}
}
}
I just tried your program and it does quit if you type "quit" (all lowercase) like your command line instruction suggest:
System.out.print("Any letter to continue alternatively type quit to Quit.");
If you want your quit instruction to be case-insensitive you should replace this line:
} while (!answer.equals("quit"));
with this:
} while (!answer.equalsIgnoreCase("quit"));
I hope that helped!
Your quit information System.out.print("Any letter to continue alternatively type quit to Quit."); says that you need to put quit all lowercase word to end.
Also change answer = scanner.next(); to answer = scanner.nextLine();
EDIT:
As you don't have any error control you can consider this code:
do {
System.out.print("Please enter your username: ");
name.add(scanner.nextLine());
System.out.println("Please enter the game: ");
game.add(scanner.nextLine());
System.out.println("Please Enter Achievement Score: ");
score.add(Integer.valueOf(scanner.nextLine()));
System.out.println("Please Enter Playtime: ");
time.add(Integer.valueOf(scanner.nextLine()));
System.out.print("Any letter to continue alternatively type quit to Quit.");
answer = scanner.nextLine();
} while (!answer.equals("quit"));
I changed scanner.nextInt() to Integer.valueOf(scanner.nextLine()). Using nextLine() helps scanner to flush all data before your code goes to the next line.

How do I let the user input the variable again after doing an error?

import java.util.Scanner;
public class LeapYear {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
System.out.println("Please enter a year on the Gregorian calendar. (After 1583)");
int yearEntered = scan.nextInt();
if (yearEntered < 1583){
System.out.println("Please enter an integer greater than 1582");
System.out.println("Try again");
}else{
int yearEntered = scan.nextInt();
//this is where I'm messing up
Before I show you can make the user enter the variable again, I want to point out that you are declaring yearEntered again in the else, which is illegal in Java. Simply removing the int there will fix that.
Now, if you had an error from the user entering the wrong input (i.e. 2015 instead of 1580), you can do this:
Scanner scan = new Scanner(System.in);
System.out.println("Please enter a year on the Gregorian calendar. (After 1583)");
int yearEntered = 0; //initialize the variable with a default number
while (scan.hasNext()) { //keep scanning for the user input
yearEntered = scan.nextInt(); //scan for the next int assuming the user only enters ints
if (yearEntered < 1583) { //if the user entered less than 1583, then do another iteration till the user finally enters a number greater than or equal to 1582
System.out.println("Please enter an integer greater than 1582");
System.out.println("Try again");
} else {
break; //exits the loop
}
}
//code for what you want to do with the correct yearEntered

Scanner loop doesn't cycle when hitting enter twice

boolean loop = false;
double numberOfStudents;
System.out.print("Enter a number: ");
if ((scnr.nextLine().trim().isEmpty()) ) {
loop = true;
}
while (loop) {
System.out.println("Enter a number");
if (scnr.hasNextDouble() ){
System.out.println("Loop has stopped");
numberOfStudents = scnr.nextDouble();
loop = false;
}
}
System.out.println("You're outside the loop!");
I'm trying to get the program to say "Enter a number" until the user has entered an actual number (no white spaces or letters or signs). When the user has entered a number, it sets numberOfStudents equal to that number and breaks out of the loop.
But if you hit enter twice, it doesn't iterate. It only displays "Enter a number" once.
What is wrong with the loop logic? Why isn't it looping until valid input is taken?
For the actual answer to your question of "Why doesn't 'Enter a number' display more than once?" see Tom's comment (update: Tom's answer).
I've rewritten your loop in a way which preserves your code, but also makes it a little easier to handle format exceptions (though at the risk of silently swallowing an exception -- should be acceptable for this use case).
Can be up to you to use this design, here is an SO post on why empty catch blocks can be a bad practice.
public static void main(String args[])
{
boolean loop = true;
double numberOfStudents;
Scanner scnr = new Scanner(System.in);
while(loop){
System.out.print("Enter a number: ");
String input = scnr.nextLine();
try{
numberOfStudents = Double.parseDouble(input);
loop = false;
}catch(NumberFormatException e){
}
}
System.out.println("You're outside the loop!");
}
Output:
Enter a number:
Enter a number:
Enter a number:
Enter a number: 50
You're outside the loop!
First of all: Since you're reading from System.in a call to the input stream will block until the user entered a valid token.
So let's check first scan using your scnr variable:
scnr.nextLine()
nextLine() reads everything til the next line delimiter. So if you just press return, then it will successfully read it and will perform the next stuff.
The next call is:
scnr.hasNextDouble()
This call expects a "real" token and ignores white spaces, except as a delimiter between tokens. So if you just press return again it doesn't actually read that input. So it still waits for more (for the first token). That is why it stucks in your loop and you won't get another "Enter a number" output.
You can fix that by either enter a real token, like a number, or by changing the loop like trobbins said.
I hope you now understand your program flow a bit more :).
While trobbins code basically solves your problem, it's bad practice to use exceptions for flow control.
I used a small regexp to check if the value is a number. But this example is not complete, it will still crash it the user enters for example two decimal points. So you would need to create a proper number check or just use integers where the check is much easier.
Someone in the comments pointed out that people may want to enter scientific notation like 5e10, so this would also be another case to check for. If this is just some code you need as a proof of concept or something quick and dirty, you can go with the exception handling method but in production code you should avoid using exceptions this way.
double numberOfStudents;
Scanner scnr = new Scanner(System.in);
while(true) {
System.out.print("Enter a number: ");
String input = scnr.nextLine().trim();
if(input.matches("^[0-9\\.]{1,}$")) {
System.out.println("Loop has stopped");
numberOfStudents = Double.parseDouble(input);
break;
}
}
System.out.println("You're outside the loop!");
The following code should help you:
double numberOfStudents = 0;
Scanner scnr = new Scanner(System.in);
boolean readValue = false; //Check if the valid input is received
boolean shouldAskForNumber = true; //Need to ask for number again? Case for Enter
do {
if (shouldAskForNumber) {
System.out.print("Enter a number:");
shouldAskForNumber = false;
}
if (scnr.hasNextDouble()) {
numberOfStudents = scnr.nextDouble();
readValue = true;
} else {
String token = scnr.next();
if (!"".equals(token.trim())) { //Check for Enter or space
shouldAskForNumber = true;
}
}
} while (!readValue);
System.out.printf("Value read is %.0f\n", numberOfStudents);
System.out.println("You're outside the loop!");
Update
Understood the following statement in question different way:
But if you hit enter twice, it doesn't loop back. It only displays
"Enter a number" once.
The code is set to print "Enter a number" only once if the user hits RETURN/ENTER or enters space character. You may remove the special check and use the code if needed.
import java.util.Scanner;
public class Testing {
public static boolean checkInt(String s)
{
try
{
Integer.parseInt(s);
return true;
} catch (NumberFormatException ex)
{
return false;
}
}
public static void main(String[] args) {
boolean loop = false;
double numberOfStudents;
Scanner scnr = new Scanner(System.in);
String input = "";
while (!(checkInt(input))) {
System.out.println("Enter a number");
input = scnr.nextLine();
}
numberOfStudents = Integer.parseInt(input);
System.out.println("Number of students: " + numberOfStudents );
}
}
//this code is working fine, if you want you check it out.
//In your code your taking another input if the first is an int/double; if the first input is not a number then you have mentioned to take input again..
Use a debugger to see what the code is actually doing. Here's a guide on debugging in Eclipse. After you have finished debugging your code, you will probably know what the problem is.
Below code will help you
boolean loop = true;
double numberOfStudents;
Scanner scnr = new Scanner(System.in);
System.out.print("Enter a number: ");
String input = scnr.nextLine();
while(!scnr.hasNextDouble()){
System.out.print("Enter a number: ");
try{
numberOfStudents = Double.parseDouble(input);
break;
}catch(NumberFormatException e){
}
input = scnr.nextLine();
}
System.out.println("You're outside the loop!");
The following code is working,
boolean loop = true;
double numberOfStudents;
Scanner scnr=new Scanner(System.in);
while(loop) {
System.out.println("Enter a number");
if ((scnr.nextLine().trim().isEmpty()) ) {
loop = true;
}
if (scnr.hasNextDouble() ){
System.out.println("Loop has stopped");
numberOfStudents = scnr.nextDouble();
loop = false;
}
}
System.out.println("You're outside the loop!");
The output is,
run:
Enter a number
hj
po
Enter a number
lhf
Enter a number
o
Enter a number
p
Enter a number
a
Enter a number
34
Loop has stopped
You're outside the loop!
You have to scan the next line if you want to get more values form the scanner again. The code should be like:
while (loop) {
System.out.println("Enter a number");
if(!(scnr.nextLine().trim().isEmpty())){
if (scnr.hasNextDouble() ){
System.out.println("Loop has stopped");
numberOfStudents = scnr.nextDouble();
loop = false;
}
}
}

Categories

Resources