This is part of a code that I am running and when the code runs it lets me enter a number but will not let me move on, it will just continue to print "Enter a student's total quiz score : " even though i have entered a value less than the perfect quiz score help!
while (perfectQuizScore > quizScore ) {
System.out.print("Enter a student's total quiz score : ");
quizScore = Integer.parseInt(keyboard.nextLine()); // 6
if (quizScore > perfectQuizScore) {
System.out.println("Invalid value! Score must not be greater than perfect score.");
}
else if (quizScore < 0) {
System.out.println("Invalid value! Value must be greater than 0.");
}
}
OUTPUT:
enter image description here
REVERSING THE SIGNS
enter image description here
If I'm understanding your question correctly... you want to exit the loop when the supplied quiz score is less than (or equal to) the perfect score? If so, you just need to change the sign in your while loop conditional (it is currently checking greater than).
Before:
while (perfectQuizScore > quizScore ) {
After:
while (perfectQuizScore < quizScore ) {
Now this is assuming that you initially set quizScore to a huge value (if you initialize it to 0 then the conditional will evaluate to false before entering the loop). A better solution is probably to use a do-while loop.
int quizScore = 0;
do {
System.out.print("Enter a student's total quiz score : ");
quizScore = Integer.parseInt(keyboard.nextLine()); // 6
if (quizScore > perfectQuizScore) {
System.out.println("Invalid value! Score must not be greater than perfect score.");
}
else if (quizScore < 0) {
System.out.println("Invalid value! Value must be greater than 0.");
}
} while (perfectQuizScore < quizScore or quizScore < 0);
Although I would personally probably structure this differently, to avoid writing your "bad" conditions down twice:
int quizScore = 0;
while (True) {
System.out.print("Enter a student's total quiz score : ");
quizScore = Integer.parseInt(keyboard.nextLine()); // 6
if (quizScore > perfectQuizScore) {
System.out.println("Invalid value! Score must not be greater than perfect score.");
}
else if (quizScore < 0) {
System.out.println("Invalid value! Value must be greater than 0.");
}
else {
// good input, exit the loop with a break statement
break;
}
}
Maybe the following is what you searching:
do {
System.out.print("Enter a student's total quiz score : ");
quizScore = scnr.nextInt();
if (quizScore > perfectQuizScore) {
System.out.println("Invalid value! Score must not be greater than perfect score.");
}
else if (quizScore <= 0) {
System.out.println("Invalid value! Value must be greater than 0.");
} else {
break; // get out of the loop
}
} while ( quizScore <= 0 || quizScore > perfectQuizScore );
Do the check (while) after getting the first time, also change the checks to stay on the loop until the user write a valid value.
The do {...} will let the code inside run one time before the while checks.
Related
Sorry for the newbish question, am quite new with Java.
So I want to display an error message when user input is outside of the bounds (Lesser than 0, greater than 100) which I've managed to do but I also want that the user can try again but my current code only continues with the execution of the program.
This is what I have now:
import java.util.Scanner;
public class storeQuota {
public static void main(String [] args) {
Scanner input = new Scanner (System.in);
int quotas [] = new int [100];
int NumberOfWorkers = 100;
for (int i = 0; i<numberOfWorkers; i++) {
if (i == 0) {
System.out.print("Enter the quota for the 1st student: ");
}
else if (i == 1) {
System.out.print("Enter the quota for the 2nd student: ");
}
else if (i == 2) {
System.out.print("Enter the quota for the 3rd student: ");
}
else if (i >= 3) {
System.out.print("Enter the quota for the " + (i+1) + "th student: ");
}
while (true) {
quotas[i] = input.nextInt();
if (quotas[i] > 100 || quotas[i] < 0)
System.out.println("Error - Can only be between 0 and 100.");
break;
}
}
//Printing all quotas.
System.out.println("Thank you for your input. Your entered quotas are: ");
for (int i=0; i<numberOfWorkers; i++)
{
System.out.print(quotas[i] + ", ");
}
input.close();
}
}
With this code, the error message is correctly displayed when a user inputs an int that isn't between 0 and 100 but the user will be unable to try again, the program continues to ask for the next quoata.
I think the problem is located in this line
break;
after
System.out.println("Error - Can only be between 0 and 100.");
which always breaks the while loop. Instead you only want to break the while loop if the input is in valid range. I would not use while(true) but some sort of conditional variable which is set to false in the while loop if the input is in valid range, also because while(true) is not a good programming practice from my point of view.
Your problem is using Break;
rather than using that, you should change the while(true) to while(false), you've also forgot to add curly brackets around the if statement.
boolean x = true;
while (x){
quotas[i] = input.nextInt();
if (quotas[i] > 100 || quotas[i] < 0){
System.out.println("Error - Can only be between 0 and 100.");
x = false;
}
}
also I suggest learning exceptions as they would make this 10x easier.
When executed, "break" breaks the loop you are currently in. In your code, break is executed irrespective of what the input is resulting in the unwanted result.
Simplest solution would be (closest to your original code):
while(true) {
quotas[i] = input.nextInt();
if (quotas[i] > 100 || quotas[i] < 0) {
System.out.println("Error - Can only be between 0 and 100.");
} else {
break;
}
}
Here, the loop will break only if correct input is entered.
You haven't used curly braces in if condition.
while (true) {
quotas[i] = input.nextInt();
if (quotas[i] > 100 || quotas[i] < 0) {
System.out.println("Error - Can only be between 0 and 100.");
break;
}
}
I'm trying to have my loop only occur three times. So if the user doesn't guess the correct number after their third guess then the loop ends which I have but it doesn't display what the number was. I need the number displayed after the third guess but not sure why it's not displaying the correct number.
import java.util.Scanner;
public class GuessNumberDoWhileA {
public static void main(String[] args) {
//Generate random number from 1-10
int number = (int) (Math.random()*9 + 1);
int count = 0;
//Auto Generated Method stub
Scanner Input = new Scanner(System.in);
//Tell the user to guess a number
System.out.println("Guess a number between 1 and 10");
//int guess = -1;
//while (guess != number) {
while (count < 3) {
count++;
System.out.print("\nEnter your guess: ");
int guess = Input.nextInt();
if (guess == number)
System.out.println("Correct the number was " + number);
else if (guess > number)
System.out.println("Your guess is to high try again!");
else if (guess < number)
System.out.println("Your guess is to low try again!");
else
System.out.println("The correct number is " + number);
}
System.out.println("The number was " + number);
}
}
You need a boolean variable that can be used to check whether user was able to guess the number correctly or not. Initial value of this boolean variable should be false.
You don't need the last else statement in the loop. If user guesses the number correctly, set the boolean variable to true and break out of the loop. After the loop, check if the boolean variable is false or not. If it is false, that means user was not able to guess the number, so display the correct number to the user.
If user is able to guess the number then the first if statement in the loop will print the correct number on the console and break out of the loop. It will also set the boolean variable to true, so correct number will be printed only once on the console.
boolean guessed = false;
while (count < 3) {
count++;
System.out.print("\nEnter your guess: ");
int guess = Input.nextInt();
if (guess == number) {
System.out.println("Correct the number was " + number);
guessed = true;
break;
}
else if (guess > number)
System.out.println("Your guess is to high try again!");
else if (guess < number)
System.out.println("Your guess is to low try again!");
}
if (!guessed) System.out.println("Number was: " + number);
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
**Thanks Adi219 & Charles Spencer for helping with my part 1.
Now i'm trying a different approach, by validating the input before it store into an array, it look fine most of the time, but the exception only run once.
This is what i input to test the validating
1) I input "a", it returned "enter number between 0 to 100" which is correct.
2) I input 1000, and it returned "Invalid age" which i can tell that my IF conditions works.
3) No issue when i input the correct value for User no.1
Problem happens when i try to run the same test on User no.2. After I input correct value for User no.1, I type in "A" again and the programs just bypass all those conditions and captured no integer value.
import java.util.Scanner;
public class test2
{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int i = 0;
double x = 0;
double Total = 0;
double Average = 0;
int Users = 2; //I fixed a number for testing purpose
boolean isNumber =false;
double ages[] = new double[Users];
for(int counter =0; counter < Users; counter++){
System.out.print("Enter the age for users "+(counter+1)+ ": ");
do{
try {
x =input.nextDouble();
if(x<0 || x>100){
System.out.print("Invalid age.. try again.. ");
}else if(x>0 || x<100){isNumber=true;}
}catch(Exception e){
System.out.print("Please enter number between 0 to 100 ");
input.next();
}
}while(!(isNumber));
System.out.println("User Age is "+ x); //Just to check input user's age
}
}
}
Because your entire do/while loop is based on whether isNumber is false, if you enter a valid number for user1, the isNumber variable is set to true, and the do/while loop will never run again because you never set isNumber back to false. There are two places were I set isNumber back to false, I've marked them. But I'm pretty sure this whole thing should be rewritten. For example there's no need to do:
else if(x > 0 || x < 100)
because you've already done:
if(x<0 || x>100)
If you do the first condition as x <= 0 || x >= 100 there's no need to do an else if statement.
for(int counter = 0; counter < Users; counter++)
{
System.out.print("Enter the age for users "+(counter+1)+ ": ");
do{
try {
x = input.nextDouble();
if(x<0 || x>100)
{
isNumber = false; // Set to false if invalid number
System.out.print("Invalid age.. try again.. ");
}
else if(x > 0 || x < 100)
{isNumber = true;} // If the age for user1 is valid, isNumber is set
// to true
}catch(Exception e)
{
isNumber = false; // Set to false if number invalid
System.out.print("Please enter number between 0 to 100 ");
input.next();
}
}while(!(isNumber));
I want the while loop to execute when the user's input is a non-integer value, an integer value less than 1, or an integer value greater than 3. Once the input is valid, I will use it. However, the loop only works when the user inputs a non-integer value. I have gone through the logic and I am still not sure what's wrong.
Code:
Scanner scnr = new Scanner(System.in);
do {
System.out.println("Please enter an integer value 1-3 for the row.");
while((scnr.hasNextInt() && (scnr.nextInt() > 3)) || (scnr.hasNextInt() && (scnr.nextInt() < 1)) || (!scnr.hasNextInt()))
{
System.out.println("Your input is not valid.");
System.out.println("Please enter an integer value 1-3 for the row.");
scnr.next();
}
row = scnr.nextInt() - 1;
"while" works fine by itself. No "do" is required in this case. Here is your code:
Scanner scnr = new Scanner(System.in);
System.out.println("Please enter an integer value 1-3 for the row.");
while((scnr.hasNextInt() && (scnr.nextInt() > 3)) || (scnr.hasNextInt() && (scnr.nextInt() < 1)) || (!scnr.hasNextInt()))
{
System.out.println("Your input is not valid.");
System.out.println("Please enter an integer value 1-3 for the row.");
scnr.next();
}
int row = scnr.nextInt() - 1;
You need "do" when you want to execute code at least once and then check "while" condition.
Also each call for nextInt actually requires next int in the input. So, better use it only once like this:
int i;
while((i=scnr.hasNextInt() && (i > 3)) || (scnr.hasNextInt() && (i < 1)) || (!scnr.hasNextInt()))
I am not completly sure about this, but an issue might be calling scnr.nextInt() several times (hence you might give the value to a field to avoid this).
An easy to read solution would be introducing a tester-variable as #Vikrant mentioned in his comment, as example:
System.out.println("Please enter an integer value 1-3 for the row.");
boolean invalid=true;
int input=-1;
while(invalid)
{
invalid=false;
if(scnr.hasNextInt())
input=scnr.nextInt();
else
invalid=true;
if(input>3||input<1)
invalid=true;
if(!invalid)
break;
System.out.println("Your input is not valid.");
System.out.println("Please enter an integer value 1-3 for the row.");
scnr.next();
}