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;
}
}
Related
Design an application that picks a random number 1 through 100, and then prompt the user to guess the number, warning the user they only have 5 tries remaining to guess correctly. After each guess, report to the user whether he or she is correct or guess was too high or too low. If guesses correctly, print out congratulatory message. If guess 5 times unsuccessfully, print a message saying the game is over. At the end of the game, prompt hte user to indicate whether or not he/she wishes to play again.
I specifically need help with the ending, and I guess also the layout of the code... I run it and it continually runs, I've tried using several websites and my textbook but no luck, thank you in advance!!
Java, Net beans 8.2
import java.util.Random;
import java.util.Scanner;
public class GuessingGame
{
public static void main (String[]args)
{
int answer, guess,attemptsNum = 0;
final int maxAttempts = 5;
String str, another = "y";
Scanner scan = new Scanner(System.in);
Random generator = new Random();
answer = generator.nextInt(101)+1;
System.out.println("Guess a number between 1 and 100");
System.out.println("Enter your guess (0 to quit):");
{
guess = scan.nextInt();
while (guess != 0)
{
if(guess==answer)
System.out.println("Right!");
else if (guess<answer)
System.out.println("Your guess was too LOW.");
else if (guess>answer)
System.out.println("Your guess was too HIGH.");
}
System.out.println("Want to Play again?(y/n)");
another = scan.next();
while (guess != answer && ++attemptsNum < maxAttempts)
if (attemptsNum == maxAttempts)
System.out.println ("The number was " + answer);
}
}
}
Enter your guess (0 to quit): 20
Your guess was too LOW
Enter your guess (0 to quit): 35
Your guess was too LOW
Enter your guess (0 to quit): 80
Your guess was too HIGH
Enter your guess (0 to quit): 74
Your guess was too HIGH
Enter your guess (0 to quit): 56
Right! Guesses:5
Play again (y/n)?
Couple of comments:
You need to work on your formatting of the code. This makes it a lot more readable.
Your generator generates a value between 1 and 101. It should just be answer = generator.nextInt(100)+1;
Your loops and some of your logic is wrong
I would suggest always creating a separate method outside public static void main. This is common practice, and this also allows you to call the method it self again.
This is how i would solve it:
import java.util.Random; import java.util.Scanner;
class Main {
public static Scanner scan = new Scanner(System.in);
public static void main (String[]args) {
runGame();
}
public static void runGame() {
String another = "";
int answer, guess,attemptsNum = 0;
final int maxAttempts = 5;
Random generator = new Random();
answer = generator.nextInt(100)+1;
System.out.println("Guess a number between 1 and 100");
System.out.println("Enter your guess (0 to quit):");
guess = scan.nextInt();
while (guess != answer && attemptsNum < maxAttempts-1 && guess != 0 ) {
if(guess==answer)
System.out.println("Right!");
else if (guess<answer) {
System.out.println("Your guess was too LOW.");
attemptsNum++;
guess = scan.nextInt();
}
else {
System.out.println("Your guess was too HIGH.");
attemptsNum++;
guess = scan.nextInt();
}
}
System.out.println ("The number was " + answer);
System.out.println("Want to Play again?(y/n)");
another = scan.next();
System.out.println("another = " + another);
if(another.equals("y")) {
runGame();
} else {
System.out.println("Goodbye!");
}
}
}
But either way, just continue to practice. You will get the hang of it!
I see the outer while loop needs to be restructured and some of the logic is misplaced. Try the revised version, hope this helps. Comment me if you have any questions.
import java.util.Random;
import java.util.Scanner;
public class GuessingGame {
public static void main(String[] args) {
int answer, guess, attemptsNum = 0;
final int maxAttempts = 5;
String str, another = "y";
Scanner scan = new Scanner(System.in);
Random generator = new Random();
answer = generator.nextInt(101) + 1;
while (another.equals("y") || another.equals("Y")) {
System.out.println("Guess a number between 1 and 100");
System.out.println("Enter your guess (0 to quit):");
guess = scan.nextInt();
attemptsNum = 0;
while (guess != 0)
{
attemptsNum++;
if (guess == answer) {
System.out.println("Right!");
break;
} else if (guess < answer)
System.out.println("Your guess was too LOW.");
else if (guess > answer)
System.out.println("Your guess was too HIGH.");
if (attemptsNum == maxAttempts) {
System.out.println("The number was " + answer);
break;
}
System.out.println("Enter your guess (0 to quit):");
guess = scan.nextInt();
}
System.out.println("Want to Play again?(y/n)");
another = scan.next();
}
System.out.println("Thanks for playing");
}
}
I can see that javapedia.net has answered first, but I have come up with this answer independently. I have added brackets for readability. attemptsNum++ is added to the if statements for a guess being too high or low.
import java.util.Random;
import java.util.Scanner;
public class GuessingGame {
public static void main(String[] args) {
int answer, guess, attemptsNum = 0;
final int maxAttempts = 5;
String str, another = "y";
Scanner scan = new Scanner(System.in);
Random generator = new Random();
answer = generator.nextInt(101) + 1;
System.out.println("Guess a number between 1 and 100");
System.out.println("Enter your guess (0 to quit):");
guess = scan.nextInt();
while (guess != 0) {
if (guess == answer) {
System.out.println("Right!");
guess = 0;
} else if (guess < answer) {
System.out.println("Your guess was too LOW.");
attemptsNum++;
guess = scan.nextInt();
} else {
System.out.println("Your guess was too HIGH.");
attemptsNum++;
guess = scan.nextInt();
}
if (attemptsNum >= (maxAttempts-1)) {
System.out.println("The number was " + answer);
}
}
}
}
I am working on a project that involves creating a rental car calculator.
What I am trying to do is make it to where when asked: "What vehicle would you like to rent??". If a number that is not between 1-3 is entered when the user is prompted this, then I want the program to loop back to the point of being asked vehicle type again.
Similarly, when prompted for 'Please enter the number of days rented. (Example; 3) : ' I want to only allow the user to input whole positive numbers. for instance, not allowing input of 3.1, 2.35, 0.35 -2 and, etc...
here is what I have written and my attempt at these questions :
package inter;
import java.util.Scanner;
public class Inter {
public static void main(String []args){
int count=0;
int days;
double DailyFee=0, NontaxTotal, CarType, Total,FullTotal=0;
Scanner in=new Scanner(System.in);
System.out.println("If there are any customer press 1 else press 0");
int cus=in.nextInt();
while(cus!=0){
count++;
System.out.print("What vehical would you like to rent?\n");
System.out.println("Enter 1 for an economy car\n");
System.out.println("Enter 2 for a sedan car\n");
System.out.println("Enter 3 for an SUV");
CarType = in.nextInt();
if (CarType == 1) {
DailyFee=31.76;
}
else if(CarType == 2) {
DailyFee=40.32;
}
else if(CarType == 3) {
DailyFee=47.56;
}
else if(CarType <= 0) {
System.out.println("input is not a positive Integer ");
System.out.println("Please enter a positive integer value: ");
cus = 0; }
else if(CarType > 4) {
System.out.println("input is not a positive Integer ");
System.out.println("Please enter a positive integer value: ");
cus = 0; }
System.out.print("Please enter the number of days rented. (Example; 3) : ");
days = Integer.valueOf(in.nextLine());
double x=days;
NontaxTotal = (DailyFee * x);
Total = (NontaxTotal * 1.06);
FullTotal+=Total;
System.out.printf("The total amount due is $ %.2f \n",Total);
System.out.println("If there are any customer press 1 else press 0");
cus=in.nextInt();
}
System.out.println("Count of customers : "+count);
System.out.printf("Total of the Day : $ %.2f",FullTotal);
}
}
Let me help you with this,
I made this code for you, i tried it and it worked
this will check if both answers were whole numbers (integers) and more than zero and will also check if the answer was numeric in the first place so that if the user answered with letters he will be prompted to try again
This is my suggestion:
basically i used the try-catch block with InputMismatchException to detect if the answer was not an integer (whole number ) or was not numeric at all, every time a mistake is detected i flip a boolean to false and keep looping as long as this boolean is false (i flip the boolean back to true before checking otherwise once the user gives a wrong answer he will always be prompted to answer even if he gave a correct answer after)
int vehicleType;
int numberOfDays;
double dailyFee;
boolean validAnswer1 = false;
boolean validAnswer2 = false;
Scanner scan = new Scanner(System.in);
while (validAnswer1 == false) {
validAnswer1 = true;
System.out.println("Choose Vehicle Type");
try {
vehicleType = scan.nextInt();
if (vehicleType <= 0) {
System.out.println("Number must be more than zero");
validAnswer1 = false;
} else if (vehicleType >= 4) {
System.out.println("Number should be from 1 to 3");
validAnswer1 = false;
} else {
if (vehicleType == 1) {
dailyFee=31.76;
} else if(vehicleType == 2) {
dailyFee=40.32;
}else if(vehicleType == 3) {
dailyFee=47.56;
}
while (validAnswer2 == false) {
validAnswer2 = true;
try {
System.out.println("Enter number of days rented ?");
numberOfDays = scan.nextInt();
if (numberOfDays <= 0) {
System.out.println("Number of days must be more than zero");
validAnswer2 = false;
} else {
// calculate your rent total here
}
} catch(InputMismatchException ex) {
System.out.println("Answer must be an Integer");
validAnswer2 = false;
scan.next();
}
}
}
} catch (InputMismatchException ex) {
validAnswer1 = false;
System.out.println("Answer must be an Integer");
scan.next();
}
}
Hope this was useful, do let me know if you still need help
Hello my purpose is this:
Write a method that can accept values only between 10 and 50.Sample execution:Enter a number between 10 and 50Enter a number: 5Enter a number between 10 and 50Enter a number: 12Number Entered: 12.Enter a number: 0Good ByeSo as you can see it only finishes when user enters 0.And it says different things when number is between 10 and 50 or not.I deleted again my code and started but i got stuck on some points and i gave up.My final code was:
import java.util.Scanner;
public class A{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter case number: ");
int caseVal = scan.nextInt();
switch(caseVal){
case 1:
System.out.println("Enter a number between 10 and 50");
System.out.println("Enter a number: ");
int num = scan.nextInt();
betweenMethod(num);
if(num == 0){
System.out.println("Good Bye");
break;
}
while(num != 0){
betweenMethod(num);
}
break;
case 2:
System.out.println("Enter a number to display its divisors: ");
int x = scan.nextInt();
System.out.println("The divisors of " + x + " are:");
divisorsMethod(x);
break;
}
scan.close();
}
public static void divisorsMethod(int a){
if(a <= 0)
System.out.println("The number should be greater than 0");
else{
for(int b = 1; b <= a; b++){
if(a % b == 0 && b != a)
System.out.print(b + ", ");
else if(b == a)
System.out.println(b);
}
}
}
public static void betweenMethod(int a){
Scanner inputscan = new Scanner(System.in);
if(a >= 10 && a <= 50){
System.out.println("Enter a number:");
a = inputscan.nextInt();
}
else if((a < 10 || a > 50) && a != 0){
System.out.println("Enter a number between 10 and 50");
System.out.println("Enter a number:");
a = inputscan.nextInt();
}
else{
System.out.println("Good Bye");
}
inputscan.close();
}
}
Sorry for uncut version.It is case 1.Every time i tried it didnt work fully.If anyone can help i would appreciate it.I'm sorry if i didnt write this question in rules.(Sorry for the grammar as well)THIS IS WHERE I AM STUCK= When i type 0 it doesnt say GoodBye and end the loop.Thats where i need help.TO EVERYONE THAT NEEDS ANSWER TOO:I figured out what to do.Basically we say while its not equal to zero right?I wrote a new method that (after last inputscan for variable)checks if the number is zero and prints good bye.So with this way it prints good bye and it goes to starting.But it cannot do anythink else because we said while not equal to 0.Anyway thats one solution.
Don't close() System.in
When you call inputscan.close() that closes the underlying InputStream, which is System.in.
Return the Value
Your method should be prompting for input between two values and returning a single value. Also, you could move your Scanner to a static (or class) field. Something like
private static Scanner inputscan = new Scanner(System.in);
public static int betweenMethod(final int a, final int b) {
int min = Math.min(a, b);
int max = Math.max(a, b);
while (true) {
System.out.printf("Please enter a number between %d and %d%n", min, max);
int in = inputscan.nextInt();
if ((in == 0) || (in >= min && in <= max)) {
return in;
}
}
}
Primitives1 are Passed-By Value
You need to assign the result of the call back to your value when you loop. Something like,
int num = betweenMethod(10, 50);
while (num != 0) {
System.out.printf("Number Entered: %d.%n", num);
num = betweenMethod(num);
}
System.out.println("Good Bye");
break;
1and Everything Else in Java.
Yes, this is a homework problem. I am a beginner in programming. I am good at using if/else with for loops, since my professor asked us to while loop. I am confused.This is the question...
Q1) Suppose you are writing a game-playing program that involves 2-digit numbers, each number being composed of 2 different digits. Test if whether numbers entered in a sequence are accepted to be used in this game. Test for errors in input (including type).
My while loop to check the data type works fine at first, but after an int has been entered and I can't check the data type. Can anyone explain the problem to me please? Thank you...
public static void main(String[] args){
int num = 0;
Scanner input = new Scanner(System.in);
System.out.println("Enter a 2-digit number. The digits should be different. zero to stop");
while(!input.hasNextInt()){
System.out.println("Not an integer,try again " + num);
input.next();
}
num = input.nextInt();
while(num != 0){
while(num < 10 || num >= 99){
System.out.println("NOT good for your game! " + num );
System.out.println("Enter a 2-digit number. The digits should be different. Zero to stop");
num = input.nextInt();
}
System.out.println("Good for your game! Play! " + num);
num = input.nextInt();
}
}
}
The while loop in the first checked the System.in is entering a digit (int) or not: while(!input.hasNextInt()), but when you first input a digit, the loop exit and it enter into the next 2 loops:
while(num != 0){
while(num < 10 || num >= 99){
and then in the end of the inner loop you have:
num = input.nextInt();
This means you already assume the next input would be an int. So if you enter a non-digit input, program will throw an exception.
I would suggest you to change the whole loop into:
public static void main(String[] args) {
int num = 1;
Scanner input = new Scanner(System.in);
do {
System.out.println("Enter a 2-digit number. The digits should be different. zero to stop");
if (!input.hasNextInt()) {
System.out.println("Not an integer,try again " + num);
} else {
num = input.nextInt();
if (num < 10 || num >= 99) {
System.out.println("NOT good for your game! " + num);
} else {
System.out.println("Good for your game! Play! " + num);
}
}
} while(num != 0);
input.close();
System.out.println("game stop");
}
import java.util.Scanner;
public class Number1 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String prompt = "Enter a 2-digit number. The digits should be different. Zero to stop:";
getInt(sc,prompt);
}
public static void getInt(Scanner sc,String prompt) {
System.out.println(prompt);
int num;
while (!sc.hasNextInt())
{
System.out.println("Not an integer, Try again");
sc.next();
}
num = sc.nextInt();
while(num != 0) {
if (num < 10 || num >= 99 || num == 0)
{
System.out.println("Not good for your game!");
}
else
{
System.out.println("Good for your game! Play!");
}
System.out.println(prompt);
num = sc.nextInt();
}
}
}
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.