Multiple Scanner Inputs: Iterative validation of current selection blocks - java

I am attempting to validate multiple scanner inputs with paired If-Else blocks in a single while loop. The behavior that I am interested in achieving is to the current validation If-Statement request the user to re-enter input or move on to the subsequent input / selection blocks.
Right now, I am using the continue keyword which returns to the beginning of the While loop. Would using a do...while loop be better suited for this? Thank you.
while (count < numCars) {
System.out.println("Enter car type");
String name = scanner.next();
if (name.matches(".*\\d")) {
System.out.println("Name entry cannot contain numbers");
continue;
} else {
// re-enter name
}
System.out.println("Enter max speed");
int maxSpeed = scanner.nextInt();
if (maxSpeed == 100 || maxSpeed > 100) {
System.out.println("Max speed is not valid. Please re-enter");
continue;
} else {
// re-enter age
count++;
}
}

The functionality you want for every block can be achieved using while instead of if-else statements. I also structured your code in a nicer/more organized way:
int count = 0, numCars = 3; // Example value
String name;
int maxSpeed;
while (count < numCars) {
System.out.print("Enter car type: ");
name = scanner.next();
scanner.nextLine(); // Cleans the buffer
while (name.matches(".*\\d")) {
System.out.println("Name entry cannot contain numbers.");
System.out.print("Enter car type: ");
name = scanner.next();
scanner.nextLine(); // Cleans the buffer
}
System.out.print("Enter max speed: ");
maxSpeed = scanner.nextInt();
while (maxSpeed >= 100) {
System.out.println("Max speed is not valid. Please re-enter.");
System.out.print("Enter max speed: ");
maxSpeed = scanner.nextInt();
}
count++;
}

Related

(JAVA) Is there a more efficient way to do this?

This part of my program asks the user to enter the number of drinks they want and it must return "Invalid amount" if the number of drinks is negative.
System.out.print("Please enter the number of each drink that you like to purchase:");
System.out.println();
System.out.print("Small Coffee: ");
int smallCoffee = scnr.nextInt();
if (smallCoffee < 0) {
System.out.println("Invalid amount")
System.exit(1);
}
System.out.print("Medium Coffee: ");
int mediumCoffee = scnr.nextInt();
System.out.print("Large Coffee: ");
int largeCoffee = scnr.nextInt();
System.out.print("Banana Berry Smoothie: ");
int berrySmoothie = scnr.nextInt();
System.out.print("Mocha Shake: ");
int mochaShake = scnr.nextInt();
System.out.print("Raspberry Green Tea: ");
int greenTea = scnr.nextInt();
Instead of putting an if-statement under each option, is there any other way I can output "invalid amount" under each option?
Methods, of course. You have a task:
Ask the user for a non-negative number.
So, write a method that encapsulates the job:
public int getAmount(Scanner scanner, String prompt) {
while (true) {
System.out.println(prompt);
int v = scanner.nextInt();
if (v >= 0) return v;
System.out.println("Please enter positive numbers only.");
}
}
note how you can now write 'if they mess up, ask again instead of outright quitting' exactly once, and reuse this as many times as you like.
#rzwitserloot's suggestion of writing a method to encapsulate the task of input, is the most straightforward, and probably most 'correct' method of doing this.
However, if you really don't want to write another function for whatever reason, you can make your variable names dynamic! Write them as a list of strings, iterate through those strings, and store them in a data structure (Map is probably the most straightforward).
Map<String, Integer> variables = new HashMap<>();
String[] variableNames = {
"Small Coffee",
"Medium Coffee",
"Large Coffee",
"Banana Berry Smoothie",
"Mocha Shake",
"Raspberry Green Tea"
};
System.out.println("Please enter the number of each drink that you like to purchase:");
for (String drinkName : variableNames) {
// ask for the amount of drink
System.out.print(drinkName + ": ");
int amount = scnr.nextInt();
// error check
if (amount < 0) {
System.out.println("Invalid amount");
System.exit(1);
}
// add to map
variables.put(drinkName, amount);
}

Where should I put the variable scanner declaration? "int figureNumber = stdin.nextInt();"

I want to make it so that a user entering the wrong data type as figureNumber will see a message from me saying "Please enter an integer" instead of the normal error message, and will be given another chance to enter an integer. I started out trying to use try and catch, but I couldn't get it to work.
Sorry if this is a dumb question. It's my second week of an intro to java class.
import java. util.*;
public class Grades {
public static void main(String args []) {
Scanner stdin = new Scanner(System.in);
System.out.println();
System.out.print(" Please enter an integer: ");
int grade = stdin.nextInt();
method2 ();
if (grade % 2 == 0) {
grade -= 1;
}
for(int i = 1; i <=(grade/2); i++) {
method1 ();
method3 ();
}
}
}
public static void main(String args[]) {
Scanner stdin = new Scanner(System.in);
System.out.println();
System.out.print(" Welcome! Please enter the number of figures for your totem pole: ");
while (!stdin.hasNextInt()) {
System.out.print("That's not a number! Please enter a number: ");
stdin.next();
}
int figureNumber = stdin.nextInt();
eagle();
if (figureNumber % 2 == 0) { //determines if input number of figures is even
figureNumber -= 1;
}
for (int i = 1; i <= (figureNumber / 2); i++) {
whale();
human();
}
}
You need to check the input. The hasNextInt() method is true if the input is an integer. So this while loop asks the user to enter a number until the input is a number. Calling next() method is important because it will remove the previous wrong input from the Scanner.
Scanner stdin = new Scanner(System.in);
try {
int figureNumber = stdin.nextInt();
eagle();
if (figureNumber % 2 == 0) { //determines if input number of figures is even
figureNumber -= 1;
}
for(int i = 1; i <=(figureNumber/2); i++) {
whale();
human();
}
}
catch (InputMismatchException e) {
System.out.print("Input must be an integer");
}
You probably want to do something like this. Don't forget to add import java.util.*; at the beginning of .java file.
You want something in the form:
Ask for input
If input incorrect, say so and go to step 1.
A good choice is:
Integer num = null; // define scope outside the loop
System.out.println("Please enter a number:"); // opening output, done once
do {
String str = scanner.nextLine(); // read anything
if (str.matches("[0-9]+")) // if it's all digits
num = Integer.parseInt(str);
else
System.out.println("That is not a number. Please try again:");
} while (num == null);
// if you get to here, num is a number for sure
A do while is a good choice because you always at least one iteration.
It's important to read the whole line as a String. If you try to read an int and one isn't there the call will explode.
You can actually test the value before you assign it. You don't need to do any matching.
...
int figureNumber = -1;
while (figureNumber < 0) {
System.out.print(" Welcome! Please enter the number of figures for your totem pole: ");
if (stdin.hasNextInt()){
figureNumber = stdin.nextInt(); //will loop again if <0
} else {
std.next(); //discard the token
System.out.println("Hey! That wasn't an integer! Try again!");
}
}
...

how do i prompt a user to re enter their input value, if the value is invalid?

public int inputNumber() {
Scanner input = new Scanner (System.in);
System.out.print("Enter the number of cookies you'd like to make ");
int number = input.nextInt();
if (number <=0) {
System.out.println(" please enter a valid number")
int number = input.nextInt();
}
input.close();
return number;
}
EDIT:
I should have used a while loop.. throwback to literally my first project.
System.out.print("Enter the number of cookies you'd like to make:");
int number = input.nextInt();
while(number<=0) //As long as number is zero or less, repeat prompting
{
System.out.println("Please enter a valid number:");
number = input.nextInt();
}
This is about data validation. It can be done with a do-while loop or a while loop. You can read up on topics of using loops.
Remarks on your codes:
You shouldn't declare number twice. That is doing int number more than once in your above codes (which is within same scope).
This way you have fewer superfluous print statements and you don't need to declare you variable multiple times.
public int inputNumber() {
Scanner input = new Scanner (System.in);
int number = 0;
do {
System.out.print("Enter the number of cookies you'd like to make ");
number = input.nextInt();
} while(number <= 0);
input.close();
return number;
}
Couple of issues:
You are missing semicolon in you println method.
You are redefining the number within if
you are using if which is for checking number instead use while so until and unless user enters correct number you dont proceed.
public int inputNumber() {
Scanner input = new Scanner (System.in);
System.out.print("Enter the number of cookies you'd like to make ");
int number = input.nextInt();
while (number <=0) {
System.out.println(" please enter a valid number");
number = input.nextInt();
}
input.close();
return number;
}
The classical way of doing that is to limit the number of retry and abort beyond that ::
static final int MAX_RETRY = 5; // what you want
...
int max_retry = MAX_RETRY;
int number;
while (--max_retry >= 0) {
System.out.print("Enter the number of cookies you'd like to make ");
number = input.nextInt();
if (number > 0) {
break;
}
System.out.println("Please enter a valid number")
}
if (max_retry == 0) {
// abort
throw new Exception("Invalid input");
}
// proceed with number ...

Loops? I need to figure out how to fix this.

When i run my program and try to add a input. It keeps saying invalid input. Enter again. I know why it did that b/c i added a while loop but that was for inputs less than 1. How can I fix this? I need to display the occupancy rate and the amount of vacant rooms. I am a beginner so I think I have made a stupid mistake. Can somebody help me?
import java.util.Scanner;
public class hotelOccupancy
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int floors, numFloors, rooms,totalRoomsOccupied,roomsOccupied, vacant;
double totalRooms;
System.out.println("Enter number of floors");
floors = input.nextInt();
while(floors < 1);
{
System.out.println("Invalid input. Enter again");
}
floors = input.nextInt();
numFloors = input.nextInt();
for(floors = 1; floors <= numFloors; floors++)
{
System.out.println("Enter number of rooms in floor");
rooms = input.nextInt();
while(rooms < 1);
{
System.out.println("Invalid entry. Enter again");
}
System.out.println("Enter number of rooms occupied for floor" + floors);
roomsOccupied = input.nextInt();
totalRoomsOccupied = input.nextInt();
totalRoomsOccupied = totalRoomsOccupied + roomsOccupied;
}
rooms = input.nextInt();
totalRoomsOccupied = input.nextInt();
vacant = rooms - totalRoomsOccupied;
totalRooms = input.nextDouble();
double occupancyRate = totalRoomsOccupied/totalRooms;
System.out.println("The number of rooms vacant are" + vacant);
System.out.println("Then occupancy rate is" + occupancyRate);
You have to move the rooms = input.nextInt(); into the while(rooms < 1) loop.
while(floors < 1); is equivalent to while(floors < 1){} so if you enter a number inferior than one, the loop will never end.
You have to take a new input in the while loop (and remove the ; after the while).
while(floors < 1){
System.out.println("Invalid input. Enter again");
floors = input.nextInt();
}
You have to do the same thing for the other while loop (don't forget to remove the ; after the while too) :
while(rooms < 1){
System.out.println("Invalid entry. Enter again");
rooms = input.nextInt();
}

Multiple Scanner Input In For Loop

I've just begun to learn how to program with Java and I had a question with regard to the scanner input. I'm building a little program that simply asks the user for input to create a numerical array. I was wondering if there was a way to check for the numerical input encompassing the for loop, instead of putting a while check on each of my cases in the for loop.
As well, any other comments or suggestions on my code to help me improve and understand what I am doing would be greatly appreciated!
Thank you!
Edit: I'm calling this class from a 'Main' class where I run the program.
import java.util.Scanner; //Import the use of the Java Scanner
public class ArrayBuild { // Open Application
private static Scanner input;
public Double[] anArray;
public static int arrayCount = 0;
public ArrayBuild() { // Constructor for ArrayBuild object
input = new Scanner(System.in);
arrayCount++;
System.out.println("This will be Array: " + arrayCount);
// Array Size Declaration
System.out.println("Enter Array Size: ");
while (!input.hasNextInt()) {
System.out.println("Please enter an integer for Array size!");
input.next();
}
int n = input.nextInt();
anArray = new Double[n]; // Create 'anArray' of size n
//
for (int i = 0; i < n; i++) { // Begin For Loop
if (i == 0) {
System.out.println("Enter First Number: ");
while (!input.hasNextDouble()) {
System.out.println("Please enter a number for array data!");
input.next();
}
Double D = input.nextDouble();
anArray[i] = D;
}
else if (i > 0 && i < (n - 1)) {
System.out.println("Enter Next Number: \n");
while (!input.hasNextDouble()) {
System.out.println("Please enter a number for array data!");
input.next();
}
Double D = input.nextDouble();
anArray[i] = D;
}
else if (i == (n - 1)) {
System.out.println("Enter Final Number: ");
while (!input.hasNextDouble()) {
System.out.println("Please enter a number for array data!");
input.next();
}
Double D = input.nextDouble();
anArray[i] = D;
}
} // End For Loop
}
} // Close Class
One thing you can do to simplify and write clean code is to always separate the repeating code. In your case, inside the for loop, you are only changing the print statement inside the if condition. Take the other code outside like this--
for (int i = 0; i < n; i++) { // Begin For Loop
if (i == 0)
System.out.println("Enter First Number: ");
else if (i > 0 && i < (n - 1))
System.out.println("Enter Next Number: \n");
else if (i == (n - 1))
System.out.println("Enter Final Number: ");
while (!input.hasNextDouble()) {
System.out.println("Please enter a number for array data!");
input.next();
}
Double D = input.nextDouble();
anArray[i] = D;
} // End For Loop

Categories