How to display error message - java

Could someone tell me how to put an error message in to the following code? If the user enters a number that is not between 0 and 12, how do I output "Invalid entry".
The program at the moment works fine and if an invalid character is entered the user is allowed to try again.
int hours;
do {
System.out.print("Enter hours: ");
hours = myscanner.nextInt();
} while (hours < 0 || hours > 12);

I would use an "infinite" while loop and break out of it when the hours figure is valid. while(true) { ... } is idiomatic Java.
Scanner scanner = new Scanner(System.in);
int hours;
while (true) {
System.out.print("Enter hours: ");
hours = scanner.nextInt();
if (hours >= 0 && hours <= 12) {
break;
}
System.err.println("Invalid entry (should be 0-12)");
}

int hours;
boolean valid;
do {
System.out.print("Enter hours: ");
hours = myscanner.nextInt();
valid = (hours >= 0 && hours <= 12);
if (!valid)
System.out.println("Invalid entry");
} while (!valid);
NOTE: I've added a variable, because otherwise, you'd have duplicate condition there
NOTE2: I've also reverted the condition because I don't like if booleans are referring to negative condition(I prefer valid over invalid)

int hours;
do {
System.out.print("Enter hours: ");
hours = myscanner.nextInt();
if (hours < 0 || hours > 12) System.out.println("Please insert a valid entry");
} while (hours < 0 || hours > 12);

Related

How to instruct my program to display error message once in Java

My project requires users to enter time in a 12-hour format only.
I believe what I did is logical-error and could not figure out what I did wrong.
When the User entered a none 12-hour format, the program should output an error message once, however, mine outputted it twice.
My Program output the following (Which is not preferred):
To exit the program, enter 'quit'.
Enter Hour:
111
Enter Minutes:
23
Enter am/pm:
pm
PROGRAM: Not a valid time, please re-enter
PROGRAM: Not a valid time, please re-enter
USER: 111:23pm
Enter 'y' to continue:
The correct output should be as follows:
PROGRAM: Not a valid time, please re-enter <--- should Only display once
USER: 111:23pm
Here's my Source code:
public void setAmm(String indicate) {
try {
if(indicate.equalsIgnoreCase("am") && getHour() < 12) {
System.out.println("PROGRAM: Good Morning!");
} else if(indicate.equalsIgnoreCase("pm") && getHour() < 6) {
System.out.println("PROGRAM: Good Afternoon!");
} else if(indicate.equalsIgnoreCase("pm") && getHour() > 6 && getHour() <= 8) {
System.out.println("PROGRAM: Good Evening!");
} else if(indicate.equalsIgnoreCase("pm") && getHour() > 8 && getHour() < 13) {
System.out.println("PROGRAM: Good Night!");
} else if(!(getHour() > 0 && getHour() < 13)) {
System.out.println("PROGRAM: Not a valid time, please re-enter");
return;
}
} catch(Exception e) {
System.out.println("PROGRAM: Not a valid time, please re-enter");
}
}
public String setTime(int hour, int minutes, String indicate) {
setHour(hour);
setMinutes(minutes);
setAmm(indicate);
return String.format("USER: %2d:%2d%s", getHour(), getMinutes(), indicate);
}
My Set and Get methods
public MyTime()
{
this.setTime(hour, minutes, indicate);
}
public void setHour(int hour)
{
this.hour = ( (hour>0 && hour <=12) ? hour : hour);
}
public int getHour()
{
return hour;
}
public void setMinutes(int minutes)
{
this.minutes = ( (minutes>0 && minutes <=60) ? minutes : minutes);
}
public int getMinutes()
{
return minutes;
}
How i Invoke it in Main:
System.out.println("Enter Hour: ");
hour = keyboard.nextInt();
System.out.println("Enter Minutes: ");
minute = keyboard.nextInt();
System.out.println("Enter am/pm: ");
indicate = keyboard.next();
MyTime time = new MyTime();
System.out.println(time.setTime(hour,minute,indicate));
System.out.println("Enter 'y' to continue:");
reply = keyboard.next();

How I stop the While loop after the 3rd invalid attempt?

So I have a big problem about stop looping. The main problem is I have to stop the while looping after user input invalid 3 times. However, I don't know how to do that.
How I can stop the while looping after 3rd invalid attempt?
And What code that I should use?
import java.text.DecimalFormat;
import java.util.Scanner;
public class CalculatePay {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
String Name = " ";
int hours;
double payRate;
char F;
char P;
char T;
char repeat;
String input = " ";
double grossPay;
System.out.print("What is your name? ");
Name = reader.nextLine();
System.out.print("How many hours did you work? ");
hours = reader.nextInt();
while (hours < 0 || hours > 280)
{
System.out.println("That's not possible, try again!");
hours = reader.nextInt();
attempt++;
if(attempt == 3)
System.out.println("You are Fired!");
{
return;
}
}
System.out.print("What is your pay rate? ");
payRate = reader.nextDouble();
System.out.print("What type of employee are you? ");
F = reader.next().charAt(0);
grossPay = hours * payRate;
DecimalFormat decFor = new DecimalFormat("0.00");
switch (F){
// irrelevant for the question
}
}
}
Like Adam suggested, you'll need a counter, such as:
int attempt = 0;
while (hours < 0 || hours > 280) {
System.out.println("That's not possible, try again!");
hours = reader.nextInt();
attempt++;
// do something if you reach the limit. The >= comparison is
// useless before attempt will never go over 4.
if(attempt == 3){
// notify the user that something wrong happened
System.out.println("Your error message here");
// exit the main function, further code is not processed
return;
}
}
I suggested a message print and returning. For your information, other options can be:
throw an exception with throw new MaxAttemptReachedException();
exit the while loop but keep processing the following code with the break; instruction.
Im assuming this is what you want to do...
int attempt = 0;
while (hours < 0 || hours > 280)
{
System.out.println("That's not possible, try again!");
hours = reader.nextInt();
attempt++;
if(attempt >= 3)
{
break;
}
}

While loop with iteration

I am trying to create a while loop where the user has a total of three tries to enter a valid number. I'm not understanding how the system recognizes that 3 invalid attempts have been made before displaying the message.
Classes, variables, and scanner objects are made. After the three attempts, I want to say "No more tries". I already have the program written to use the user's input for quantity if its valid. This is just if they input three invalid attempts.
Updated code:
int quantity = 0;
// Get user's desired amount of lemonade cups
System.out.print("Hello " + name + ". How many cups of lemonade can I get you? ");
quantity = keyboard.nextInt(); // Store amount of cups wanted
int attempts = 0;
int maxAttempts = 3;
double subTotal = quantity * lemonadeCost;
double totalTax = subTotal * 0.08;
double totalPrice = subTotal + totalTax;
while (attempts < maxAttempts) {
if (quantity < 1 || quantity >= 20) {
System.out.println("That is an invalid amount, please try again");
quantity = keyboard.nextInt(); }
else {
System.out.println("Subtotal: " + defaultFormat.format(subTotal));
System.out.println("Tax: " + defaultFormat.format(totalTax));
System.out.println("Total: " + defaultFormat.format(totalPrice));
}
attempts++;
if (attempts >= 3) {
System.out.print ("No lemonade for you");
break;
}
// Ask for user's payment method
Scanner method = new Scanner(System.in);
System.out.println("How would you like to pay? Enter 'm' for money, 'c' for credit or 'g' for gold. ");
String payment = method.nextLine();
dxdy is correct about the braces required for making the while() loop function.
Once the while loop has ended (either quantity is between 1 and 20, or attempts > maxAttempts), you just need to have an if statement like the following:
if (attempts > maxAttempts) {
System.out.println("No more tries);
return -1; // or something else to break out of your code
}
and then continue on with the rest of your code working with the quantity variable.
You seem to be missing the opening and closing brackets for the loop. As it is, your code reads
while (quantity < 1 || quantity >= 20 && attempts <= maxAttempts)
System.out.println("That is an invalid amount, please try again");
// these below are not part of the loop
quantity = keyboard.nextInt();
attempts++;
Instead you should do
while (quantity < 1 || quantity >= 20 && attempts <= maxAttempts){
System.out.println("That is an invalid amount, please try again");
quantity = keyboard.nextInt();
attempts++;
}
try this code:
//start with 1 since the user will attempt it at least one time.
int attempts = 1;
int maxAttempts = 3;
int quantity=0;
Scanner keyboard = new Scanner(System.in);
//LESS THAN OR EQUAL TO 3...
while(attempts<=maxAttempts){
System.out.print("Enter amount: ");
quantity = keyboard.nextInt();
//check if valid
if(quantity < 1 || quantity >= 20){
//check if it's 1st and 2nd trial.
if(attempts<maxAttempts){
System.out.println("That is an invalid amount, please try again");
}else{
//third trial and still invalid
System.out.print("No more tries");
}
}else{
//user entered a valid amount so let's break the loops.
System.out.println("The amount is valid. Value of amount: "+ quantity);
break;
}
//increment attempts
attempts++;
}
//never forget to close the scanner
keyboard.close();
}
}
Though I could have turned this into methods if it's allowed
EDIT: As you updated the question, so it was necessary to update the answer too. Here it is what you actually want.
public static void main(String[] args) {
// Get user's desired amount of lemonade cups
String name = "Jimmy Nguyen";
Scanner keyboard = new Scanner(System.in);
int quantity;// Store amount of cups wanted
int lemonadeCost = 4; // Suppose
int attempts = 0;
int maxAttempts = 3;
System.out.print("Hello " + name + ". How many cups of lemonade can I get you? ");
while (attempts < maxAttempts) {
quantity = keyboard.nextInt();
if (quantity < 1 || quantity >= 20) {
System.out.println("That is an invalid amount, please try again\n");
++attempts;
} else {
double subTotal = quantity * lemonadeCost;
double totalTax = subTotal * 0.08;
double totalPrice = subTotal + totalTax;
System.out.println("Subtotal: " + subTotal);
System.out.println("Tax: " + totalTax);
System.out.println("Total: " + totalPrice);
// Ask for user's payment method
System.out.println("How would you like to pay? Enter 'm' for money, 'c' for credit or 'g' for gold. ");
keyboard.nextLine();
String payment = keyboard.nextLine();
break;
}
if (attempts >= 3) {
System.out.print("No lemonade for you");
break;
}
}
}

Cant figure out how to exit the loop of my program

I am writing a program for class that is a leap year checker. I have the loop working from what I understand however it goes into an infinite loop still? Zero wont terminate the program. I've tried using else if, if, while, what have I done wrong? This is my third go at rewriting this and am completely lost now -_-. Any help or tips would be appreciated.
import java.util.Scanner;
public class LeapYearChecker {
public static void main(String[] args){
System.out.println("Please enter a date to find out if the year is a leap year.");
Scanner userInput = new Scanner(System.in);
int year = userInput.nextInt();
while(year == 0)
{
System.out.println();
}
if (year < 1582){
System.out.println("Please enter a date after 1582. The date you entered was" + year + ".");
}if((year % 4 == 0) && (year % 100 !=0) || (year % 400 == 0)){
System.out.println("That is a leap year");
}else{
System.out.println(year +" is not a leap year.");
}
}
}
while (year == 0)
{
System.out.println();
}
There's your problem, if the year is 0, your program will infinitely output a new line.
Furthermore, your ifs for checking if it is a leap year isn't inside the loop body, so even if you enter a non-zero number, the code will only run once.
Try the following code, be sure to read the comments to understand what's going on:
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int year = -1; //Give your int a default value so the main loop will execute
while (year != 0) //-1 not equal to zero, so your code will start
{
System.out.print("Please enter a year: "); //Now we get the value of the year
year = in.nextInt(); //Put it into our variable
if (year < 1582) //And if it's less than 1582
{
if (year != 0)
System.out.println("Year must not be less than 1582!"); //Notify the user, unless they are exiting the program
continue; //restart the while loop, this is quite a useful statement!
}
if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) //Check if it's a leap year
System.out.println("That is a leap year!\n");
else
System.out.println("That is not a leap year :(\n");
//End of the loop, so it goes back to the beginning, which asks the user again for the year
//So if you enter 0 next the program will close
}
}
The first loop is infinite. You forgot to read the user input inside.
Your loop will only run if a user enters 0. And once they do, your program will be stuck in an infinite loop since you haven't changed the value of year inside your while.
I'm assuming that you want to keep prompting the user to keep entering numbers until they enter 0? Then I would restructure your main method so that it surrounds the code where you retrieve and process input. Like so:
System.out.println("Please enter a date to find out if the year is a leap year.");
Scanner userInput = new Scanner(System.in);
int year;
do {
year = userInput.nextInt();
/**
* Print some message based input.
*/
} while (year != 0); // Loop until user enters 0

Can you return a string from a while loop without using the return command?

I am learning java in the internet in sites like "oracle academy" and using Google to search how to do somethings, i wanted to make a simple java program that takes an number(day) a number or word(month) and another number(year), so if you input something like
"3" "1" and "1993"
it outputs
"January 1st, 1993"
and if you input something like
"2" "July" and "1992"
it outputs
"7/2/1992"
I kind of already know how to make it using "case" and while loops to tell you if you input something incorrectly, but on the "day" part i tried using a while loop to keep asking you to input something if the input wasn't a number between 1 and 31 but i can't make it return the number from the while loop using the return command, is there any way to return the number without using the return command or not?
the code:
public static void main(String[] args) {
String x;
Scanner scan = new Scanner(System.in);
//day
System.out.println("Insert Day");
while (1 < 2){
x = scan.nextLine();
if (x.matches(".*\\d.*")){
q = Integer.parseInt(x);
if ((0 < q) && (q < 32)){
return q;
}
else {
System.out.println("please use a valid number");
}
}
else {
System.out.println("please use a number");
}
}
System.out.println(q);
You can use return if you refactor this into a separate function:
public static int getDay() {
Scanner scan = new Scanner(System.in);
System.out.println("Insert Day");
while (true){
line = scan.nextLine();
if (line.matches(".*\\d.*")){
int day = Integer.parseInt(line);
if (0 < day && day < 32){
return day;
} else {
System.out.println("please use a valid number");
}
} else {
System.out.println("please use a number");
}
}
}
public static void main(String[] args) {
int day = getDay();
System.out.println(day);
}
Or you could use a break:
Scanner scan = new Scanner(System.in);
System.out.println("Insert Day");
int day = -1;
while (true){
line = scan.nextLine();
if (line.matches(".*\\d.*")){
day = Integer.parseInt(line);
if (0 < day && day < 32){
break;
} else {
System.out.println("please use a valid number");
}
} else {
System.out.println("please use a number");
}
}
Or you could use your while condition:
int day = -1;
Scanner scan = new Scanner(System.in);
System.out.println("Insert Day");
while (day < 1 || day > 31){
line = scan.nextLine();
if (line.matches(".*\\d.*")){
day = Integer.parseInt(line);
if (day < 1 || day > 31){
System.out.println("please use a valid number");
}
} else {
System.out.println("please use a number");
}
}
Also, you can simplify your code by using the NumberFormatException parseInt throws, instead of trying to validate it yourself with a regular expression:
int day = -1;
Scanner scan = new Scanner(System.in);
System.out.println("Insert Day");
while (day < 1 || day > 31){
line = scan.nextLine();
try {
day = Integer.parseInt(line);
if (day < 1 || day > 31){
System.out.println("please use a valid number");
}
} catch (NumberFormatException e) {
System.out.println("please use a number");
}
}
The return statement returns a value from the entire method you're in. But you're in main, which can't return a value (it's void).
If you want to end the while loop when you have a good value, then use the break statement to break out of the while loop. Control then passes to the next statement following the end of the loop.

Categories