Validation for Negative numbers - java

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();
}

Related

Looping user input until a positive nonzero integer is entered

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);

Java duplicate local variable. Stumped

I am brand new to coding and trying to get my second program working. It is pretty straight forward as to what it does, but it is throwing an error on line 24 "Duplicate local variable confirm". Can't quite work out why it doesn't like what I'm doing.
Scanner userInput = new Scanner(System.in);
char confirm;
do{
System.out.println("Welcome to the story teller");
System.out.println("What is your name?");
String name = userInput.nextLine();
System.out.println("How old are you?");
int age = userInput.nextInt();
System.out.println("What country would you like to visit?");
String country = userInput.nextLine();
System.out.println("Great! So your name is" + name + ", you are" + age + "years old and you would like to visit" + country + "?");
System.out.println("Press Y to continue or N to start over");
char confirm = userInput.next().charAt(0);
if (confirm !='y' || confirm !='n'){
System.out.println("Sorry that input is not valid, please try again");
}
else {
System.out.println(name + "landed in" + country + "at the age of" + age + ".");
}
} while(confirm == 'Y'|| confirm == 'y');
You're declaring confirm twice. Change the second declaration to just assigning to it and you should be OK:
confirm = userInput.next().charAt(0);
// No datatype, so you aren't declaring confirm, just assigning to it
Because your "confirm" variable already defined in the scope (second row). If you want to assign a value, just write confirm = userInput.next().charAt(0);
Another option to fix is to remove the unnecessary declaration char confirm;
And use it only when needed
char confirm = userInput.next().charAt(0);
As #ScaryWombat suggested, you will need to change scope of the variable (currently while is in different scope than do )
It seems apart from re-declaration of the variable confirm there are one or more issue -
Issue 1:
After int age = userInput.nextInt(). It won't prompt for country input and will prompt Press Y to continue or N to start over.
Cause of this issue:
Since you are using int age = userInput.nextInt(); the scanner will only take the integer value from the input and will skip the \n newline character.
Fix
As a workaround, I've added userInput.nextLine(); after int age = userInput.nextInt(); such that it will consume the \n character after nextInt().
Issue 2:
After the 1'st iteration, this line will cause issueconfirm = userInput.next().charAt(0);.
Cause of this issue:
In 2'nd iteration you won't get a prompt to enter the name as the line String name = userInput.nextLine(); will take \n from the last iteration as input and will skip and prompt for age How old are you?.
Fix
As a workaround, I've added userInput.nextLine(); after confirm = userInput.next().charAt(0); such that it will consume the \n character after userInput.next().charAt(0) and the next iteration will go as expected.
Issue 3:
This logic if (confirm !='y' || confirm !='n') expects only y and n in lowercase but here while(confirm == 'Y'|| confirm == 'y') you are expection y and Y both.
Fix - I've added the necessary changes in the code below but would recommend you do change it to a switch case.
NOTE:
It is not recommended to do userInput.nextLine() after every input and you could simply parse it. See here for further information.
I'm not recommending it but this will get you program working
Scanner userInput = new Scanner(System.in);
char confirm;
do {
System.out.println("Welcome to the story teller");
System.out.println("What is your name?");
String name = userInput.nextLine();
System.out.println("How old are you?");
int age = userInput.nextInt();
userInput.nextLine(); //adding this to retrieve the \n from nextint()
System.out.println("What country would you like to visit?");
String country = userInput.nextLine();
System.out.println("Great! So your name is " + name + ", you are " + age
+ "years old and you would like to visit " + country + " ?");
System.out.println("Press Y to continue or N to start over");
confirm = userInput.next().charAt(0);
userInput.nextLine(); //adding this to retrieve the \n this will help in next iteration
System.out.println(name + " landed in " + country + " at the age of " + age + ".");
if (confirm == 'y' || confirm == 'Y') {
continue; // keep executing, won't break the loop
} else if (confirm == 'n' || confirm == 'N') {
break; // breaks the loop and program exits.
} else {
System.out.println("Sorry that input is not valid, please try again");
// the program will exit
}
} while (confirm == 'Y' || confirm == 'y');
}
Recommending that you use switch case instead of if comparasion of confirmation and parse the character and integer input and remove the arbitary userInput.nextLine() added as workaround.

Do while loop not printing correctly after 1st loop

I am trying to do a do-while loop that makes the program iterate again after the user inputs "y" or "Y", but everytime i run the program, It prints out something like this:
Would you like to try again?
Enter Y for yes or N for no: [DrJava Input Box] (I enter y)
Are you a student? (no input box is shown, and it skips it)
Are you a member of staff or faculty? [DrJava Input Box] (i enter yes or no)
How many tickets do you need? [DrJava Input Box] (I enter an int, but it doesnt complete that part where it shows how many tickets sold or how much it costs)
Would you like to try again?
Enter Y for yes or N for no: [DrJava Input Box]
this is what my program looks like:
import java.util.Scanner;
public class Ticket
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
double ticketprice = 12.00;
double result;
double result2;
double result3;
char repeat;
String input;
String student;
String staff;
int ticket;
do
{
System.out.println("Are you a student?");
student = keyboard.nextLine();
System.out.println("Are you a member of staff or faculty?");
staff = keyboard.nextLine();
System.out.println("How many tickets do you need?");
ticket = keyboard.nextInt();
if(student.equals("yes"))
{
System.out.println("Here is your " + ticket + " tickets for $0.00");
}
if(staff.equals("yes"))
{
result = ticketprice * .85;
result2 = ticket * result;
System.out.printf("Here are your " + ticket + " tickets for $%.2f\n", result2);
}
if(student.equals("no") && staff.equals("no"))
{
result3 = ticket * ticketprice;
System.out.printf("Here are your " + ticket + " tickets, for $%.2f\n", result3);
}
System.out.println("Would you like to try again?");
System.out.print("Enter Y for yes or N for no: ");
input = keyboard.next();
repeat = input.charAt(0);
}
while(repeat == 'y' || repeat == 'Y');
}
}
i am a beginner to programming, so any help would be good. Thank you.
At the end of the loop you call next() to read the "try again" response. This reads the next token, but still leaves the line ending on the input stream.
Next time through the loop, when you call nextLine() to read the "are you a student" response, it simply reads the remainder of that line immediately.
The easiest solution is:
Use nextLine() instead of next() for your "try again" prompt, but then this means you'll have to take care of the line ending left by nextInt() in the "tickets" question, so then you'll also have to...
Use nextLine() instead of nextInt() for your "tickets" question, then use Integer.parseInt() to parse the string into an int.
An alternate option, since all your responses seem to be just single-word responses, is to use next()/nextInt() everywhere and not use nextLine() at all. The point is, when you mix the two, you have to be aware of how they interact.
The issue lies in this block of code:
System.out.println("Would you like to try again?");
System.out.print("Enter Y for yes or N for no: ");
input = keyboard.next();
repeat = input.charAt(0);
When you call keyboard.next(), it doesn't read the entire line, so when your program loops again, the next time you call keyboard.nextLine(), it takes in part of what you entered previously in the loop and it gets ahead of itself.
The best solution would be to add a keyboard.nextLine() after you call keyboard.next() so that the remainder of the line will be consumed and won't be left over to mess up future iterations of the loop.
So for example you could change it like this:
System.out.println("Would you like to try again?");
System.out.print("Enter Y for yes or N for no: ");
input = keyboard.next();
keyboard.nextLine();
repeat = input.charAt(0);

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();
}

'Exception in thread Main....' error in Java

I am really a novice at Java but I'm giving it a shot with this program. This is a program to perform basic mathematical calculations, but with input from user.
import java.io.*;
import java.util.Scanner;
public class Math
{
public static void main(String[] args)
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
Scanner in = new Scanner(System.in);
int sa1, sa2, ss1, ss2, sm1, sm2, s;
boolean c = false;
double sd1, sd2;
while(c==false)
{
System.out.print("Do you want to: \n[1] Add. \n[2] Subtract. \n[3] Multiply. \n[4] Divide. \n[5] Exit \nPlease insert an option number below and press enter: ");
s = in.nextInt();
if (s==1)
{
System.out.print("You have chosen option 1 \nPlease enter your first number: ");
sa1 = in.nextInt();
System.out.print("Please enter your second number: ");
sa2 = in.nextInt();
System.out.print(sa1+ " + " +sa2+ " = " +(sa1+sa2));
}
if (s==2)
{
System.out.print("You have chosen option 2 \nPlease enter your first number: ");
ss1 = in.nextInt();
System.out.print("Please enter your second number: ");
ss2 = in.nextInt();
System.out.println(ss1+ " - " +ss2+ " = " +(ss1-ss2));
}
if (s==3)
{
System.out.print("You have chosen option 3 \nPlease enter your first number: ");
sm1 = in.nextInt();
System.out.print("Please enter your second number: ");
sm2 = in.nextInt();
System.out.println(sm1+ " x " +sm2+ " = " +(sm1*sm2));
}
if (s==4)
{
System.out.print("You have chosen option 4 \nPlease enter your first number: ");
sd1 = in.nextDouble();
System.out.print("Please enter your second number: ");
sd2 = in.nextDouble();
System.out.println(sd1+ " divided by " +sd2+ " = " +(sd1/sd2));
}
if(s>=6)
{
System.out.println("You have entered an incorrect option");
}
System.out.print("Would you like to try again? (Y/N): ");
String ans = in.nextLine();//prob with this line
char ans1 = ans.charAt(0);//or this line
if (ans1=='N' || ans1=='n')
{
c = true;
}
if(s==5)
{
c = true;
}
}
}
}
When I complile it I get an error: Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.lang.String.charAt(Unknown Source)
at Math.main(Math.java:58)
I've tried searching everywhere for an answer. Can anyone help me with this? It needs to be able to read either a 'Y' or a 'N' from the user.
You get the exception when you run it. Not when you compile it. And the error message says:
you're trying to get the char at index 0 of a string, but the String has no index 0. This exception happens at line 58 of Main.java.
A String which doesn't have a char at index 0 is an empty string.
This probably happens because the last thing you read from SYstem.in() is a number, and reading a number doesn't consume the end-of-line that comes after. Add a call to readLine() before reading Yes or No from the user. And don't assume that the user will do what you tell him to do. That's almost never true. Validate the inputs you read.

Categories