If you do enter a value that isn't correct it prompts you to enter the right amount but after entering the right or wrong amount it simply ends the program. Sorry I should have mentioned earlier that the program goes on for 12 months. My problem is that once I've been prompted to enter the right amount for any given month after I've entered the wrong amount, the program takes my answer and ends, rather than taking the correct answer and moving on to the next month.
System.out.print("Please enter monthly kWh usage for month 1: ");
month1 = scan.nextInt();
do {
System.out.print(" Please enter a valid amount: ");
month1 = scan.nextInt();
} while (month1>10000 || month1<0);
System.out.print("Please enter monthly kWh usage for month 2: ");
month2 = scan.nextInt();
do {
System.out.print(" Please enter a valid amount: ");
month2 = scan.nextInt();
} while (month2>10000 || month2<0);
Your code is totally correct to "simply end the program" because there are no other lines of code to execute!
The first do while loop will take an input and store it in the variable month1 and then check if it is between 0 and 10000. If so, it will go out of the loop, otherwise it will run the loop again and again till you enter the value between 0 and 10000. Then the second loop will do the same with month2 variable.
After storing both the variables, the program will exit without doing anything, because there are no lines of code to execute. You will need to write some lines of code after this to do something.
P.S. Also, it is good practice to surround the nextInt() with try-catch block because entering a non-numeric value will cause the program to crash.
Edit:
Also, you need to remove the month1 = scan.nextInt(); and month2 = scan.nextInt(); lines because the do-while loop takes care of initialising the variables for the first time.
Maybe something like this is what you want. The do is what's messing you up, because if the first input meets your condition, the loops will still occur at least once. Just use a while loop
System.out.print("Please enter monthly kWh usage for month 1: ");
month1 = scan.nextInt();
while (month1 > 10000 || month1 < 0) {
System.out.print(" Please enter a valid amount: ");
month1 = scan.nextInt();
}
System.out.print("Please enter monthly kWh usage for month 2: ");
month2 = scan.nextInt();
while (month2 > 10000 || month2 < 0) {
System.out.print(" Please enter a valid amount: ");
month2 = scan.nextInt();
}
Edit: Running code
import java.util.Scanner;
public class Month {
public static void main(String[] args) {
int month1;
int month2;
Scanner scan = new Scanner(System.in);
System.out.print("Please enter monthly kWh usage for month 1: ");
month1 = scan.nextInt();
while (month1 > 10000 || month1 < 0) {
System.out.print(" Please enter a valid amount: ");
month1 = scan.nextInt();
}
System.out.print("Please enter monthly kWh usage for month 2: ");
month2 = scan.nextInt();
while (month2 > 10000 || month2 < 0) {
System.out.print(" Please enter a valid amount: ");
month2 = scan.nextInt();
}
}
}
nextint() will throw an exception if the next characters aren't ints:
InputMismatchException - if the next token does not match the Integer regular expression, or is out of range
Try using an exception block:
try {
...
}
catch( InputMismatchException e ) {
System.out.println( e.getMessage() );
e.printStackTrace();
}
First of all, when do you use do..while, you would not need to capture input outside the loop. This force you to enter the input twice, you can remove redundant statement.
Secondly, do you have any statement to executed after second do..while?
I suggest you to provide more details what do you want to achieve here?
Related
I'm a complete beginner and I'm trying to trying to create a while loop that keeps asking the user for input until it gets a positive nonzero integer, and then moves on to the next part. Here's what I've got so far:
System.out.println("Enter the speed of the vehicle in "
+ "miles per hour: ");
while (keyboard.hasNext())
{
if (keyboard.hasNextInt())
{
speed = keyboard.nextInt();
while (speed <= 0)
{
System.out.println("Please enter a positive nonzero number: ");
speed = keyboard.nextInt();
}
}
else
{
System.out.println("Please enter a number: ");
speed = keyboard.nextInt();
}
}
Right now, when I run it and enter anything other than an integer, it prints out the line "Please enter a number," but then I immediately get an InputMatchException error and the build fails. If I enter a negative number or zero, it does prompt me to enter a positive number until I do, but then the code just stops executing and keeps running while doing nothing indefinitely, instead of moving on to the part after the loop, which just starts with another system.Output. Thanks in advance for any help.
You need to consume the previously entered non-int, and then attempt to read the following input:
else
{
System.out.println("Please enter a number: ");
// consume and ignore the previous non-int input
keyboard.next();
}
You could do it this way. By asking for a string representation of a numerical value using the Scanner#nextLine() method then applying the String#matches() method with a small Regular Expression (regex) that validates the fact that a positive numerical value was supplied (the "\\d+" expression), for example:
String speedString = "";
while (speedString.isEmpty()) {
System.out.println("Enter the speed of the vehicle in miles per hour: ");
speedString = keyboard.nextLine().trim();
if (!speedString.matches("\\d+") || Integer.valueOf(speedString) < 1) {
System.err.println("Invalid speed value supplied!\n"
+ "Please enter a 'positive' non-zero number.\n");
speedString = "";
}
}
int speed = Integer.parseInt(speedString);
The instructions read:
Write a program that prompts the user to input a student first name followed by a space and an integer test grade, then the user will press enter and you will prompt them again for a name and a test grade; for a total of 10 students and 10 grades. (Ex: Dawn 100 ) ; You must check that the user enters a grade that is >= 0 and <= 100. If not, you must prompt the user with an error message and the user must input the grade again.
I can't figure out how to do this without getting a java.util.InputMismatchException error message.
Scanner input = new Scanner(System.in);
String[] students = new String[10];
int[] grades = new int[10];
for(int i = 0; i < students.length; )
{
System.out.println("Enter a student name and grade(between 0 and 100): ");
if(input.nextInt() > 0 && input.nextInt() <= 100)
{
students[i] = input.next();
grades[i] = input.nextInt();
i++;
}
else
{
System.out.println("*Error* Grade value must be between 0 and 100. Please Try again");
}
}
Let's take a closer look...
if(input.nextInt() > 0 && input.nextInt() <= 100)
You check the input for nextInt, twice, so you're no longer actually comparing the same value, but also, you've asked for a String and an int value, but you've not checked for the String first...
Assume I entered something like 500 -1, then you're if statement would pass successfully, because 500 is > 0 and -1 is <= 100
And if by some miracle, that worked, you're reading another String and another int from the stream...
students[i] = input.next();
grades[i] = input.nextInt();
So, for this to work, the input would have to be something like 1 2 John 50 ... which would just be completely weird and completely void what you're trying to do.
Instead, ask for one piece of information at a time and process it, for example...
Scanner input = new Scanner(System.in);
System.out.print("User name: ");
String name = input.nextLine();
System.out.print("Grade: ");
String gradeValue = input.nextLine();
Scanner parser = new Scanner(gradeValue);
if (parser.hasNextInt()) {
int grade = parser.nextInt();
if (grade >= 0 && grade <= 100) {
// Good grade
} else {
System.out.println("!! " + grade + " is not a valid grade");
}
} else {
System.out.println("!! " + gradeValue + " is not a valid integer value");
}
Don't keep reading from the Scanner when you're not expecting a value, extract the value you need and process it. Here I've used nextLine to get the grade and a second Scanner to parse it, it's safer and avoids the oddities where the new line is left in the buffer. It also gives you better control to process errors ;)
This is the main culprit:
if(input.nextInt() > 0 && input.nextInt() <= 100)
Your if condition contains two (2) calls to input.nextInt(), so at this point — before reading the name — your program will attempt to read two numbers from input and see if the first is greater than 0 and the second less than or equal to 100. And if it succeeded, it would not store the numbers read into any variables.
Instead you need to read the name into students[i] first. Then read the grade into grades[i]. Then check if the grade read is in the interval. I suggest you use a while loop so that as long as the grade is outside the interval, you print the error message and read the grade anew. If the first grade read was OK, you while loop won’t execute at all, so this is fine.
I can't figure out how to do this without getting a
java.util.InputMismatchException error message.
The first mistake you've made is reading user input incorrectly input.nextInt() > 0 && input.nextInt() this is requiring the user to enter an integer value twice whereas what you want is name (string) & grade (int).
the solution below takes that mistake into consideration, however personally I would use a while loop, but since you're using a for loop already I have decided to incorporate with that.
full solution:
Scanner input = new Scanner(System.in);
String[] students = new String[10];
int[] grades = new int[10];
for(int i = 0; i < students.length; i++)
{
System.out.println("Enter a student name and grade(between 0 and 100): ");
String getInput = input.nextLine();
if(Integer.parseInt(getInput.split(" ")[1]) < 0 || Integer.parseInt(getInput.split(" ")[1]) > 100)
{
System.out.println("*Error* Grade value must be between 0 and 100. Please Try again");
i--;
}
else {
students[i] = getInput.split(" ")[0];
grades[i] = Integer.parseInt(getInput.split(" ")[1]);
}
}
note - the solution given only takes into consideration what you've mentioned within your question i.e it is expecting input as such Ousmane 20, Brendon 23 , jack 30 etc, also you can make the program a bit more robust by adding more validations if needed maybe NumberFormatException, Scanner#hasNextInt() and so forth.
System.out.print("Price of the book? ");
while (!keyboard.hasNextDouble() || priceOfBook <=0)
{
System.err.print("Invalid input - Price of " + bookTitle + "? ");
keyboard.nextLine();
}
priceOfBook = keyboard.nextDouble();
I am trying to validate the above code basically so that user can't enter negative numbers or letters or empty doubles but it's not working and I can't see where I'm going wrong. Can someone please help me?
So how i understand you need to real line until the user didint enter negative or letter.
Scanner sc = new Scanner(System.in);
double x = 0;
System.out.println("Enter price");
while (true) {
if (!sc.hasNextDouble()) {
System.out.println("Sorry price cant be negative or be letter");
break;
}
System.out.println("Enter price");
x = sc.nextDouble();
}
Hope it helps!
You put
priceOfBook = keyboard.nextDouble();
outside of your while loop :) Try like this:
while (priceOfBook <= 0)
{
System.err.print("Invalid input - Price of " + bookTitle + "? ");
priceOfBook = keyboard.nextDouble();
}
So that it will keep asking the user if he enters a number < 0.
You don't assign the user's input to priceOfBook until after the while loop. So, when your loop checks if priceOfBook is negative, it doesn't check the user's input, but the previously stored value (if there is one). This allows the user's input (even if it's negative) to pass the while loop, and then get saved as priceOfBook.
Try instead:
while (!keyboard.hasNextDouble() || priceOfBook = keyboard.nextDouble() <=0) {
System.err.print("Invalid input - Price of " + bookTitle + "? ");
keyboard.nextLine();
}
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();
}
public static void date1() {
int x = 0 ; //integer for looping
do // process to follow if length == 5
{
Scanner scanner = new Scanner(System.in);
try {
System.out.println("Please enter the first date ");
System.out.println("Please enter the year: ");
y1 = scanner.nextInt();
System.out.println("Please enter the month: ");
m1 = scanner.nextInt();
System.out.println("Please enter the day: ");
d1 = scanner.nextInt();
} catch (InputMismatchException inputMismatchException) {
scanner.nextLine();
System.err.println("You must enter intergers. Please try again. ");
}
x = x + 1 ; // set loop to three attempts
} while (x < 3) ; //do process occurs while attempts are under < 4
}
i want to break the loop if the all the inputs are proper (integers entered). I am not too sure what command to use to break the loop i created.
thanks in advance everybody!
Put a break command before you close your try{} block. If no exception is thrown, the break command will be executed and exit the loop.
A better way to do it, though, is to make a separate method that accepts a single input from the user, then call it three times. This way, you don't have to make the user input the first two numbers again if only the third one wasn't valid:
private static int getIntInput(){
while(true){
try{
return scanner.nextInt();
} catch(InputMismatchException e){
System.out.println("You must enter integers. Please try again.");
}
}
}
public static void date1(){
int x=0;
System.out.println("Please enter the first date ");
System.out.println("Please enter the year: ");
y1 = getIntInput();
System.out.println("Please enter the month: ");
m1 = getIntInput();
System.out.println("Please enter the day: ");
d1 = getIntInput();
}
You could, of course, make things more fancy... we could add a String input to the getIntInput() method, and then print that string every time we are accepting an input, so the user doesn't forget what he's trying to enter. Or you could clean up the syntax so it works (I think the compiler will complain that getIntInput needs to return an int, the way I typed it up right now...)
You could add a variable boolean stop = false and then modify your while to be while( x < 3 || stop == true). Then add some code to set stop = true once you are satisfied with your inputs.
Here's a hint: "break" out of the loop when all the inputs are proper.