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
Related
I need to write a java program reading in an indefinite amount of numbers and saves them to a collection of numbers, until an (even number) is entered in by the user. I have tried with a while loop, that when a positive number is found in it it stops. But it is not really working. Here is codes I have tried:
public static void main(String[] args) {
int programInteger = 1;
int inputtedInteger;
while (programInteger < 2) {
System.out.println("Enter a number: "); //Asks user to input a number
Scanner in = new Scanner(System.in);
inputtedInteger = Scanner(in.nextLine);
if (inputtedInteger != 0) {
System.out.println("The number "+ inputtedInteger +" that you inputted is not an even number, try again: ");
inputtedInteger=in.nextInt();
}
else if (inputtedInteger % 2 == 0){
programInteger =+1;
System.out.println("The number "+inputtedInteger+" that you entered is an even number!");
}
}
}
/* if(inputtedInteger % 2 == 0) {
System.out.println("The number "+ inmatatTal +" you entered is an even number!");
}
else {
System.out.println("Enter a number?! ");
inputtedInteger = in.nextInt();
}
Fixing a few things in the logic of the loop should work:
int inputtedInteger = 0;
Scanner in = new Scanner(System.in);
while (inputtedInteger < 1) {
System.out.println("Enter a number: "); //Asks user to input a number
inputtedInteger = in.nextInt();
if (inputtedInteger % 2 != 0) {
System.out.println("The number "+ inputtedInteger +" that you inputted is not an even number, try again: ");
}
else if (inputtedInteger % 2 == 0){
System.out.println("The number "+inputtedInteger+" that you entered is an even number!");
}
}
I would setup an outline for the code like this:
setup Scanner, create collection
while true:
userInput = scanner.nextInt()
if userInput > 0: break
collection.add(userInput)
print('user entered', collection.length(), 'numbers.')
Hope that helps. I'll leave you to fill this using actual Java syntax.
I wrote a comment on the OP on why your structure is failing to solve the issue at hand.
I'm making a very simple program that asks a user to input an age and then it will calculate a charge for admission. So far all works well but I'm wanting to add a check in so that if the user inputs anything other than an int value, it will ask them to enter an int value. I.e if they enter a character.
Here is my code:
public class CalcChargeAge {
public static void main(String[] args) {
int x;
double chargeA = 20;
double chargeB = 10;
System.out.println("Enter Users age to calculate charge for entry. ");
Scanner in = new Scanner(System.in);
x = in.nextInt();
if (x >= 18) {
System.out.println("Users age is " + x);
System.out.println("Please pay the charge for entry: £" + chargeA);
} else if (x >= 12) {
System.out.println("Users age is " + x);
System.out.println("Please pay the charge for entry: £" + chargeB);
} else {
System.out.println("Users age is " + x);
System.out.println("User entry charge is free. Print admission ticket.");
}
}
}
You can use the Scanner.hasNextInt() method to check whether the input is an integer, which I think is a lot nicer than catching an exception.
Then for the full implementation you could wrap everything in a loop, so you could do something like:
Scanner in = new Scanner(System.in);
while(in.hasNext()) {
if(in.hasNextInt()) {
int x = in.nextInt();
// Handle input
break;
}
else {
// Handle invalid input
in.next();
}
}
Something like this should work fine:
boolean isValid = false;
int validInput = 0;
while (!isValid) {
try {
validInput = scanner.nextInt();
isValid = true;
}
catch (Exception e) {
System.out.println("Please enter a valid integer.");
}
}
// ... code using validInput
One of the ways (beware, it might not be the best or even the good one) to go about it would be to replace x=in.nextInt(); with
while(true) {
String input = in.next();
try {
x = Integer.parseInt(input);
break;
} catch (Exception e) {
System.out.println("Please provide an integer!");
}
}
this will not leave the loop until user provides an integer value (evil!)
im trying to do two checks with a while loop:
1) To show "error" if the user inputs something other than an int
2) Once the user entered an int, if it is one digit, show "two digits only" and keep the loop on until a two digit int has been entered (so an IF should be used as well)
Currently I only have the first part done:
Scanner scan = new Scanner(System.in);
System.out.println("Enter a number");
while (!scan.hasNextInt()) {
System.out.println("error");
scan.next();
}
However, if possible, I would like to have both checks in one while loop.
And that's where I'm stuck...
Since you already have two answers. This seems a cleaner way to do it.
Scanner scan = new Scanner(System.in);
String number = null;
do {
//this if statement will only run after the first run.
//no real need for this if statement though.
if (number != null) {
System.out.println("Must be 2 digits");
}
System.out.print("Enter a 2 digit number: ");
number = scan.nextLine();
//to allow for "00", "01".
} while (!number.matches("[0-9]{2}"));
System.out.println("You entered " + number);
As said above you should always take the input in as string and then try
and parse it for an int
package stackManca;
import java.util.Scanner;
public class KarmaKing {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String input = null;
int inputNumber = 0;
while (scan.hasNextLine()) {
input = scan.next();
try {
inputNumber = Integer.parseInt(input);
} catch (Exception e) {
System.out.println("Please enter a number");
continue;
}
if (input.length() != 2) {
System.out.println("Please Enter a 2 digit number");
} else {
System.out.println("You entered: " + input);
}
}
}
}
First take the input as a String. If it is convertible to Int then you do your checks, else say 2 digit numbers are acceptable. If it is not convertible to a number throw an error. All this can be done in one while loop. And you would like to have a "Do you want to continue? " kind of a prompt and check if the answer is "yes" / "No." Break from the while loop accordingly.
To have it as one loop, it's a bit messier than two loops
int i = 0;
while(true)
{
if(!scan.hasNextInt())
{
System.out.println("error");
scan.next();
continue;
}
i = scan.nextInt();
if(i < 10 || >= 100)
{
System.out.println("two digits only");
continue;
}
break;
}
//do stuff with your two digit number, i
vs with two loops
int i = 0;
boolean firstRun = true;
while(i < 10 || i >= 100)
{
if(firstRun)
firstRun = false;
else
System.out.println("two digits only");
while(!scan.hasNextInt())
{
System.out.println("error");
scan.next();
}
i = scan.nextInt();
}
//do stuff with your two digit number, i
This is the output of the program
I was able to do till to get this result by doing this program below
import java.util.Scanner;
public class aLittleQuiz {
public static void main(String[] args) {
// declaring varibles
String quizStart;
int quizAns1, quizAns2, quizAns3;
Scanner input = new Scanner(System.in);
System.out.println("Are you ready for a quiz? (y / n)");
quizStart = input.next();
System.out.println("Okay, here it comes!");
// quiz answer 1
System.out.println("\nWhat is the capital of Alaska? \n1) Melbourne\n2) Anchorage\n3) Juneau");
quizAns1 = input.nextInt();
if (quizAns1 == 3) {
System.out.println("That's right");
} else {
System.out.println("Your answer is wrong, sorry!");
}
// quiz answer 2
System.out.println("Q2) Can you store the value ''cat'' in a variable of type int? \n1) yes \n2) no");
quizAns2 = input.nextInt();
if (quizAns2 == 1) {
System.out.println("Sorry, ''cat'' is a string. ints can only store numbers.");
} else if (quizAns2 == 2) {
System.out.println("Correct!");
}
// quiz answer 3
System.out.println("What is the result of 9+6/3? \n1) 5\n2) 11 \n3) 15/3");
quizAns3 = input.nextInt();
if (quizAns3 == 2) {
System.out.println("That's correct!");
} else {
System.out.println("");
}
// if (quizAns == 3 && quizAns == ) {
// }
}
}
but how I can program this part?
"Overall, you got 2 out of 3 correct.
Thanks for playing!"
Declare a variable like int marks and increment it by one inside if\else block(which made for correct answer). And at the end print
System.out.println("Overall, you got" +marks+" out of 3 correct. Thanks for playing!");
Assuming your no of question is fixed( 3 )
String quizStart;
int quizAns1, quizAns2, quizAns3;
int marks=0;
Scanner input = new Scanner(System.in);
System.out.println("Are you ready for a quiz? (y / n)");
quizStart = input.next();
System.out.println("Okay, here it comes!");
// quiz answer 1
System.out.println("\nWhat is the capital of Alaska? \n1) Melbourne\n2) Anchorage\n3) Juneau");
quizAns1 = input.nextInt();
if (quizAns1 == 3) {
System.out.println("That's right");
++marks;
} else {
System.out.println("Your answer is wrong, sorry!");
}
// quiz answer 2
System.out.println("Q2) Can you store the value ''cat'' in a variable of type int? \n1) yes \n2) no");
quizAns2 = input.nextInt();
if (quizAns2 == 1) {
System.out.println("Sorry, ''cat'' is a string. ints can only store numbers.");
} else if (quizAns2 == 2) {
System.out.println("Correct!");
++marks;
}
// quiz answer 3
System.out.println("What is the result of 9+6/3? \n1) 5\n2) 11 \n3) 15/3");
quizAns3 = input.nextInt();
if (quizAns3 == 2) {
System.out.println("That's correct!");
++marks;
} else {
System.out.println("");
}
System.out.println("Overall, you got " +marks+" out of 3 correct. Thanks for playing!");
This while loop that is suppose to prompt for a price and a y/n and end if price = 0. However, when I run the code, it asks for the price, takes it, goes to a blank line, and I have to enter the number again before asking me the next question. For the second question, I only have to enter the input once.
And when I print the price array, the value is the number I inputted the second time.
int keepGoing = 1;
while (keepGoing > 0) {
System.out.print("How much is the item? (If no more items, enter '0') ");
if (in.nextDouble() > 0) {
prices.add(in.nextDouble());
System.out.print("Is the item a pet? (Y or N) ");
String input = in.next();
if (new String("Y").equals(input) || new String("y").equals(input)) {
isPet.add(true);
}
else { isPet.add(false); }
}
else { keepGoing = 0; }
}
Help please?
That's because each time you write in.nextDouble(), the user will be need to type something into the scanner. Instead, you should store the input in a tempory variable:
Double input = in.nextDouble(); // Keep the input in this variable
if (input > 0) { // You can use it on each of these lines
prices.add(input); // so that the user doesn't have to type it twice.
System.out.print("Is the item a pet? (Y or N) ");
String input = in.next();
if (new String("Y").equals(input) || new String("y").equals(input)) {
isPet.add(true);
}
else { isPet.add(false); }
}
else { keepGoing = 0; }
A little side note: keepGoing should probably be a boolean instead of an int
Also, you can use new String("Y").equalsIgnoreCase(input) so that you don't need the ||
It asks you twice because you call the in.nextDouble() method twice, one in the if statement and another time in the following line.
Take a look at the comments on your code below:
int keepGoing = 1;
while (keepGoing > 0) {
System.out.print("How much is the item? (If no more items, enter '0') ");
if (in.nextDouble() > 0) { // <-- You are asking for the input here
prices.add(in.nextDouble()); // <-- and asking for the input here again.
System.out.print("Is the item a pet? (Y or N) ");
String input = in.next();
if (new String("Y").equals(input) || new String("y").equals(input)) {
isPet.add(true);
}
else { isPet.add(false); }
}
else { keepGoing = 0; }
}
Just change your code to be like this:
int keepGoing = 1;
double d = 0;
while (keepGoing > 0) {
System.out.print("How much is the item? (If no more items, enter '0') ");
d = in.nextDouble();
if (d > 0) {
prices.add(d);
System.out.print("Is the item a pet? (Y or N) ");
String input = in.next();
if (new String("Y").equals(input) || new String("y").equals(input)) {
isPet.add(true);
}
else { isPet.add(false); }
}
else { keepGoing = 0; }
}