I don't know how to say
if money(); < 1000 and house(); is == small print your poor
or
if money(); >=1000 and < 5000 and house(); is == to normal to print your ok, your too rich
package ArrayTest;
import java.util.Scanner;
/**
* Created by quwi on 02/12/2017.
*/`enter code here`
public class Happyness {
private static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
// house();
// money();
comparison();
}
private static void house() {
// getting user input and using the switch statement to see the size
// of their house
System.out.println("Please enter the size of your house ");
String cap = scanner.next();
switch (cap) {
case "small":
System.out.println("you have a small house it means your poor");
break;
case "normal":
System.out.println("your house normal, it mean your not poor nor rich");
break;
case "large":
System.out.println("your house is big it means your rich");
break;
default:
System.out.println("please choose between: small, normal or large");
break;
}
}
private static void money() {
System.out.println("please enter a number");
int wage = scanner.nextInt();
if (wage < 1000) {
System.out.println("your poor");
} else if (wage >= 1000 && wage < 5000) {
System.out.println("your not poor, your OK");
} else if (wage > 5000) {
System.out.println("your rich, Give me money");
} else {
System.out.println("please enter a number nothing else");
}
}
private static void comparison() {
System.out.println("please enter a number");
int decision = scanner.nextInt();
switch (decision) {
case 1:
money();
break;
case 2:
house();
break;
case 3:
money();
house();
break;
default:
System.out.println("Please choose 1, 2 or 3");
}
}
}
Use return value from both to compare.
private static String money() {
System.out.println("please enter a number");
int wage = scanner.nextInt();
if (wage < 1000) {
return "poor";
} else if (wage >= 1000 && wage < 5000) {
return "ok";
} else if (wage > 5000) {
return "rich";
} else {
//ask for input again or exit, whatever
}
}
Do same for the house(). Then, compare the return values from both in another method.
Related
My program runs but when I need it to calculate what I need it to do (add, subtract, multiply, divide) it just puts in the value that I typed in and won't do the operation I tell it to do, it just displays the menu again. How do I fix it so it can do the function it needs to do and also loop back to the menu to do another function? (ex. I want to add 2 and 2 together then turn around and multiply 3 and 2)
public static void main(String[] args) {
Testt calc = new Testt();
calc.getCurrentValue();
displayMenu();
}
public static int displayMenu() {
Scanner input = new Scanner(System.in);
Testt calc = new Testt();
int choice;
do {
System.out.println("Hello, welcome to the menu");
System.out.println("Select one of the following items from the menu:");
System.out.println("1) Add ");
System.out.println("2) Subtract ");
System.out.println("3) Multiply ");
System.out.println("4) Divide ");
System.out.println("5) Clear ");
System.out.println("6.Quit");
System.out.println ("Please choice an option from the menu:");
choice = input.nextInt();
if (choice > 6 || choice < 1) {
System.out.println("Sorry," + choice + " was not an option");
return displayMenu();
}
} while (choice > 6 && choice < 1);
if (choice == 5) {
calc.clear();
return 0;
} else if (choice == 6) {
System.out.println("Goodbye! ");
System.exit(0);
}
System.out.println("What is the second number? ");
double operand2 = input.nextDouble();
switch (choice) {
case 1:
calc.add(operand2);
break;
case 2:
calc.subtract(operand2);
break;
case 3:
calc.multiply(operand2);
break;
case 4:
calc.divide(operand2);
break;
}
return choice;
}
public static double getOperand(String prompt) {
return 0;
}
private double currentValue;
public double getCurrentValue() {
System.out.println("The current value is " + currentValue);
return 0;
}
public void add(double operand2) {
currentValue = currentValue + operand2;
getCurrentValue();
}
public void subtract(double operand2) {
currentValue = operand2 - currentValue;
getCurrentValue();
}
public void multiply(double operand2) {
currentValue = operand2 * currentValue;
getCurrentValue();
}
public void divide(double operand2) {
if (operand2 == 0) {
System.out.println("Sorry, you can not divide by 0");
}
currentValue = operand2 / currentValue;
getCurrentValue();
}
public void clear() {
currentValue = 0;
getCurrentValue();
}
From getCurrentValue() you are always returning 0.
You need to return current value.
Also if you want to loop back to same thing you can put all this in while(true) loop. like this:
public static int displayMenu() {
Scanner input = new Scanner(System.in);
Demo calc = new Demo();
int choice;
System.out.println("Hello, welcome to the menu");
System.out.println("Select one of the following items from the menu:");
System.out.println("1) Add ");
System.out.println("2) Subtract ");
System.out.println("3) Multiply ");
System.out.println("4) Divide ");
System.out.println("5) Clear ");
System.out.println("6.Quit");
while(true){
System.out.println ("Please choice an option from the menu:");
choice = input.nextInt();
if (choice > 6 || choice < 1) {
System.out.println("Sorry," + choice + " was not an option");
continue;
}
if (choice == 5) {
calc.clear();
return 0;
} else if (choice == 6) {
System.out.println("Goodbye! ");
System.exit(0);
}
System.out.println("What is the second number? ");
double operand2 = input.nextDouble();
switch (choice) {
case 1:
calc.add(operand2);
break;
case 2:
calc.subtract(operand2);
break;
case 3:
calc.multiply(operand2);
break;
case 4:
calc.divide(operand2);
break;
}
}
}
I need to build code that first gets a 2d array and then prints it.
for this, I built a menu with a switch case.
when the user clicks 0, the user types the size of the array (the size is always n*n), and then the user types the values. then I need to create a function that uses this info to build a char array.(the values is hex base 0-F)
when the user clicks 1, the code needs to print the same 2d array.
I have a difficult time understanding how I can move the array from case 0.
import java.util.Scanner;
public class Assignment3 {
static Scanner reader = new Scanner (System.in);
public static void main(String[] args) {
int checker=1;
int user_selction;
do {
user_selction=Menu();
switch(user_selction) {
case 0:
Menu_0(user_selction);
break;
case 1:
break;
case 2:
break;
case 3:
break;
case 4:
checker=GoodBye(checker);
break;
default:
break;
}
}while(checker==1);
}
public static int Menu ()
{
int menu_num;
System.out.println("~ Photo Analyzed ~");
System.out.println("0. Load Photo");
System.out.println("1. Print Photo");
System.out.println("2. Circle Check");
System.out.println("3. Random Check");
System.out.println("4. Exit");
System.out.println("Please select an option>");
menu_num=reader.nextInt();
if(menu_num>4||menu_num<0)
{
System.out.println("Invalid input");
}
return menu_num;
}
public static int GoodBye(int GB)
{
GB=0;
System.out.println("Goodbye!");
return GB;
}
public static int Menu_0 (int a)
{
int Ps;
System.out.println("Please insert the photo size>");
Ps=reader.nextInt();
if(Ps<0||Ps>12)
{
System.out.println("Invalid Photo Input!");
return a;
}
System.out.println("Please insert the photo value>");
String strPhoto;
do {
strPhoto = reader.nextLine();
} while(strPhoto.length() == 0);
if(strPhoto.length()!=Ps*Ps)
{
System.out.println("Invalid Photo Input!");
return a;
}
for(int i=0;i<Ps*Ps;i++)
{
if(strPhoto.charAt(i)<'0'||strPhoto.charAt(i)>'F')
{
System.out.println("Invalid Photo Input!");
return a;
}
}
return a;
}
This is an example
import java.util.Scanner;
public class Assignment3 {
static Scanner reader = new Scanner (System.in);
public static void main(String[] args) {
int checker=1;
int user_selction;
char [][]array = null;
do {
user_selction=Menu();
switch(user_selction) {
case 0:
array = Menu_0();
break;
case 1:
print_array(array);
break;
case 2:
break;
case 3:
break;
case 4:
checker=GoodBye(checker);
break;
default:
break;
}
}while(checker==1);
}
public static int Menu ()
{
int menu_num;
System.out.println("~ Photo Analyzed ~");
System.out.println("0. Load Photo");
System.out.println("1. Print Photo");
System.out.println("2. Circle Check");
System.out.println("3. Random Check");
System.out.println("4. Exit");
System.out.println("Please select an option>");
menu_num=reader.nextInt();
if(menu_num>4||menu_num<0)
{
System.out.println("Invalid input");
}
return menu_num;
}
public static int GoodBye(int GB)
{
GB=0;
System.out.println("Goodbye!");
return GB;
}
public static char[][] Menu_0 ()
{
int Ps;
System.out.println("Please insert the photo size>");
Ps=reader.nextInt();
if(Ps<0||Ps>12)
{
System.out.println("Invalid Photo Input!");
return null;
}
System.out.println("Please insert the photo value>");
char [][]array = new char[Ps][Ps];
for(int i=0;i<Ps;i++)
{
for (int j = 0 ; j < Ps ; j++)
{
char c = reader.next().charAt(0);
if(c<'0'||c>'F')
{
System.out.println("Invalid Photo Input!");
return null;
} else {
array[i][j] = c;
}
}
}
return array;
}
public static void print_array(char [][]array){
for (int i = 0 ; i < array[0].length ; i++)
{
for (int j = 0 ; j < array[0].length ; j++)
{
System.out.print(array[i][j] + " ");
}
System.out.println();
}
}
}
Use Scanner like this:
Scanner sc = new Scanner(System.in);
System.out.println("Select 1 to input array size or 2 to do sth");
int option = sc.nextInt();
switch(option) {
case 1 :
Scanner sc = new Scanner(System.in);
System.out.println("Enter array size: ");
int size = sc.nextInt()
int[] array = new array[size*size];
break;
case 2 :
something;
break;
default:
System.out.println("No such option ");
break;
}
import java.util.Scanner;
public class RainRecording {
private int choice;
private Scanner input;
private String site;
private int days;
private int daysCounter;
private int[] rainRecorded;
private int[] rainEntered;
private float lattitude;
private float longitude;
private String message1;
private String message2;
private String message3;
private String message4;
private String message5;
private String message6;
// declare name of variable
public RainRecording() {
// declare value of variable
this.message1 = "Site";
this.message2 = "lattitude";
this.message3 = "longitude";
this.message4 = "Window";
this.message5 = "days";
this.message6 = ":";
this.daysCounter = 0;
this.input = new Scanner(System.in);
mainMenu();
}
private void mainMenu() {
System.out.println("");
System.out.println("*** Rain Gauge Menu ***");
System.out.println(" 1: Create rain gauge");
System.out.println(" 2: Display rain gauge details");
System.out.println(" 3: Add daily rainfall measurement");
System.out.println(" 4: Display rainfall histogram");
System.out.println(" 5: Get maximum rainfall");
System.out.println(" 6: Check rainfall is below threshold");
System.out.println(" 7: Display anaylsis");
System.out.println(" 8: Exit");
System.out.print("Please enter your selection: ");
Chosen();
}
private void Chosen() {
this.choice = Integer.parseInt(input.nextLine());
switch (choice) {
case 1:
createGauge();
break;
case 2:
gaugeDetails();
break;
case 3:
int i = 0;
while( i < this.days || this.daysCounter == this.days) {
if (this.daysCounter == this.days) {
System.out.printf("Error - system full\n");
mainMenu();
}
if (this.days < 1) {
mainMenu();
} else {
this.rainRecorded = new int[this.days];
System.out.printf("Please enter rainfall for the current day: ");
rainRecorded[this.daysCounter] = Integer.parseInt(input.nextLine());
this.daysCounter++;
this.rainEntered = new int[this.daysCounter];
mainMenu();
}
i++;
}
break;
case 4:
System.out.printf("\n");
displayHistogram();
break;
case 5:
break;
case 6:
break;
case 7:
break;
case 8:
break;
default:
System.out.println("Invalid input, try again");
mainMenu();
}
while (choice != 8)
;
}
private void createGauge() {
System.out.printf("\nPlease enter the name of the site :");
this.site = input.nextLine();
System.out.printf("Please enter the number of days to record :");
this.days = Integer.parseInt(input.nextLine());
System.out.printf("Please enter the lattitute :");
this.lattitude = Float.parseFloat(input.nextLine());
System.out.printf("Please enter the longitude :");
this.longitude = Float.parseFloat(input.nextLine());
mainMenu();
}
private void gaugeDetails() {
if (this.days > 0) {
System.out.printf("%-9s %-3s %s \n", this.message1, this.message6, this.site);
System.out.printf("%s %-3s % 09.4f\n", this.message2, this.message6, this.lattitude);
System.out.printf("%s %-3s %9.4f\n", this.message3, this.message6, this.longitude);
System.out.printf("%-9s %-3s %-2d%s \n", this.message4, this.message6, this.days, this.message5);
mainMenu();
} else {
mainMenu();
}
}
private void displayHistogram() {
for (int i = 0; i < this.rainEntered.length; i++) {
for (int j = 0; j < this.rainRecorded[i] - 1; j++) {
System.out.print("*");
}
System.out.println(i);
}
System.out.print("");
mainMenu();
}
public static void main(String[] args) {
#SuppressWarnings("unused")
RainRecording objName;
objName = new RainRecording();
}
}
I guys i being struck on this for a couple of days in my switch statement in case 3 is where i create my elements to enter into my array , but in seems to only remember the last array entered when i print my histogram out in case 4 displayHistogram(); and this is where my histogram is printing wrong as well.
So to issues my array isn't recording property and histogram is printing wrong.
For example users chooses 3 days to enter and values are 10,20,30, and when i print histogram its prints this.
0
1
*****************************2
What i want this below , one * for ever ten mills of rain with index printed first.
0 *
1 **
2 **
You need to move the initialisation of this.rainRecorded to createGauge method and update the displayHistogram to print as required. You can try the following:
import java.util.Scanner;
public class RainRecording {
private int choice;
private Scanner input;
private String site;
private int days;
private int daysCounter;
private int[] rainRecorded;
private int[] rainEntered;
private float lattitude;
private float longitude;
private String message1;
private String message2;
private String message3;
private String message4;
private String message5;
private String message6;
// declare name of variable
public RainRecording() {
// declare value of variable
this.message1 = "Site";
this.message2 = "lattitude";
this.message3 = "longitude";
this.message4 = "Window";
this.message5 = "days";
this.message6 = ":";
this.daysCounter = 0;
this.input = new Scanner(System.in);
mainMenu();
}
private void mainMenu() {
System.out.println("");
System.out.println("*** Rain Gauge Menu ***");
System.out.println(" 1: Create rain gauge");
System.out.println(" 2: Display rain gauge details");
System.out.println(" 3: Add daily rainfall measurement");
System.out.println(" 4: Display rainfall histogram");
System.out.println(" 5: Get maximum rainfall");
System.out.println(" 6: Check rainfall is below threshold");
System.out.println(" 7: Display anaylsis");
System.out.println(" 8: Exit");
System.out.print("Please enter your selection: ");
Chosen();
}
private void Chosen() {
this.choice = Integer.parseInt(input.nextLine());
switch (choice) {
case 1:
createGauge();
break;
case 2:
gaugeDetails();
break;
case 3:
int i = 0;
while( i < this.days || this.daysCounter == this.days) {
if (this.daysCounter == this.days) {
System.out.printf("Error - system full\n");
mainMenu();
}
if (this.days < 1) {
mainMenu();
} else {
System.out.printf("Please enter rainfall for the current day: ");
rainRecorded[this.daysCounter] = Integer.parseInt(input.nextLine());
this.daysCounter++;
this.rainEntered = new int[this.daysCounter];
mainMenu();
}
i++;
}
break;
case 4:
System.out.printf("\n");
displayHistogram();
break;
case 5:
break;
case 6:
break;
case 7:
break;
case 8:
break;
default:
System.out.println("Invalid input, try again");
mainMenu();
}
while (choice != 8)
;
}
private void createGauge() {
System.out.printf("\nPlease enter the name of the site :");
this.site = input.nextLine();
System.out.printf("Please enter the number of days to record :");
this.days = Integer.parseInt(input.nextLine());
this.rainRecorded = new int[this.days]; // move the array initialization here
System.out.printf("Please enter the lattitute :");
this.lattitude = Float.parseFloat(input.nextLine());
System.out.printf("Please enter the longitude :");
this.longitude = Float.parseFloat(input.nextLine());
mainMenu();
}
private void gaugeDetails() {
if (this.days > 0) {
System.out.printf("%-9s %-3s %s \n", this.message1, this.message6, this.site);
System.out.printf("%s %-3s % 09.4f\n", this.message2, this.message6, this.lattitude);
System.out.printf("%s %-3s %9.4f\n", this.message3, this.message6, this.longitude);
System.out.printf("%-9s %-3s %-2d%s \n", this.message4, this.message6, this.days, this.message5);
mainMenu();
} else {
mainMenu();
}
}
private void displayHistogram() {
for (int i = 0; i < this.rainEntered.length; i++) {
System.out.print(i + " ");
for (int j = 0; j < this.rainRecorded[i] - 1; j += 10 ) {
System.out.print("*");
}
System.out.println();
}
mainMenu();
}
public static void main(String[] args) {
#SuppressWarnings("unused")
RainRecording objName;
objName = new RainRecording();
}
}
So, your codes a little bit over the place and I've had some issues trying to understand the basic intent, for example
private int[] rainRecorded;
private int[] rainEntered;
I'm not sure what the intention is for these two variables. So in my example, I've discarded rainEntered for the time been.
So, your first problem starts here...
while( i < this.days || this.daysCounter == this.days) {
if (this.daysCounter == this.days) {
System.out.printf("Error - system full\n");
mainMenu();
}
if (this.days < 1) {
mainMenu();
} else {
this.rainRecorded = new int[this.days];
System.out.printf("Please enter rainfall for the current day: ");
rainRecorded[this.daysCounter] = Integer.parseInt(input.nextLine());
this.daysCounter++;
this.rainEntered = new int[this.daysCounter];
mainMenu();
}
i++;
}
First, I'd remove the need to for the two exit conditions, as it is going to make it more difficult to reasons about
Next, the checks for the validity of the data should be done outside of the loop and I'd also avoid calling mainMenu from within it, this is going to quickly put you in a strange place.
But, my main problem is with
this.rainRecorded = new int[this.days];
System.out.printf("Please enter rainfall for the current day: ");
rainRecorded[this.daysCounter] = Integer.parseInt(input.nextLine());
this.daysCounter++;
this.rainEntered = new int[this.daysCounter];
You keep creating new instances of both this.rainRecorded and this.rainEntered, meaning that each time the loop runs, you've lost anything that was previous entered.
So, in my "simplified" version, I modified it down to something like...
if (this.days < 1) {
System.out.println("Invalid number of days");
return;
}
if (this.daysCounter == this.days) {
System.out.printf("Error - system full\n");
return;
}
while (this.daysCounter < this.days) {
System.out.printf("Please enter rainfall for the day " + (daysCounter + 1) + ": ");
rainRecorded[this.daysCounter] = Integer.parseInt(input.nextLine());
this.daysCounter++;
}
I then simplified the histogram workflow as well, but I'm still trying to get my head around what rainEntered is suppose to do...
private void displayHistogram() {
for (int amount : rainRecorded) {
for (int count = 0; count < amount; count++) {
System.out.print("*");
}
System.out.println(" " + amount);
}
}
One last thing I also did, was to remove all the calls to mainMenu and instead relied on a simple do-while loop to reprint the menu each time it returned from Chosen method
private void mainMenu() {
do {
System.out.println("");
System.out.println("*** Rain Gauge Menu ***");
System.out.println(" 1: Create rain gauge");
System.out.println(" 2: Display rain gauge details");
System.out.println(" 3: Add daily rainfall measurement");
System.out.println(" 4: Display rainfall histogram");
System.out.println(" 5: Get maximum rainfall");
System.out.println(" 6: Check rainfall is below threshold");
System.out.println(" 7: Display anaylsis");
System.out.println(" 8: Exit");
System.out.print("Please enter your selection: ");
Chosen();
} while (shouldContinue);
}
This simplifies the workflow, as it's easier to reason about where you are at any point in the execution of the program, instead of wondering why when, under some condition, when you chose something from the menu, you end up in some other part of the program instead.
Example
import java.util.Scanner;
public class RainRecording {
private int choice;
private Scanner input;
private String site;
private int days;
private int daysCounter;
private int[] rainRecorded;
//private int[] rainEntered;
private float lattitude;
private float longitude;
private String message1;
private String message2;
private String message3;
private String message4;
private String message5;
private String message6;
private boolean shouldContinue = true;
// declare name of variable
public RainRecording() {
// declare value of variable
this.message1 = "Site";
this.message2 = "lattitude";
this.message3 = "longitude";
this.message4 = "Window";
this.message5 = "days";
this.message6 = ":";
this.daysCounter = 0;
this.input = new Scanner(System.in);
mainMenu();
}
private void mainMenu() {
do {
System.out.println("");
System.out.println("*** Rain Gauge Menu ***");
System.out.println(" 1: Create rain gauge");
System.out.println(" 2: Display rain gauge details");
System.out.println(" 3: Add daily rainfall measurement");
System.out.println(" 4: Display rainfall histogram");
System.out.println(" 5: Get maximum rainfall");
System.out.println(" 6: Check rainfall is below threshold");
System.out.println(" 7: Display anaylsis");
System.out.println(" 8: Exit");
System.out.print("Please enter your selection: ");
Chosen();
} while (shouldContinue);
}
private void Chosen() {
this.choice = Integer.parseInt(input.nextLine());
switch (choice) {
case 1:
createGauge();
break;
case 2:
gaugeDetails();
break;
case 3:
if (this.days < 1) {
System.out.println("Invalid number of days");
return;
}
if (this.daysCounter == this.days) {
System.out.printf("Error - system full\n");
return;
}
while (this.daysCounter < this.days) {
System.out.printf("Please enter rainfall for the day " + (daysCounter + 1) + ": ");
rainRecorded[this.daysCounter] = Integer.parseInt(input.nextLine());
this.daysCounter++;
}
break;
case 4:
System.out.printf("\n");
displayHistogram();
break;
case 5:
break;
case 6:
break;
case 7:
break;
case 8: shouldContinue = false;
break;
default:
System.out.println("Invalid input, try again");
}
}
private void createGauge() {
System.out.printf("\nPlease enter the name of the site :");
this.site = input.nextLine();
System.out.printf("Please enter the number of days to record :");
this.days = Integer.parseInt(input.nextLine());
System.out.printf("Please enter the lattitute :");
this.lattitude = Float.parseFloat(input.nextLine());
System.out.printf("Please enter the longitude :");
this.longitude = Float.parseFloat(input.nextLine());
if (days > 0) {
this.rainRecorded = new int[this.days];
}
}
private void gaugeDetails() {
if (this.days > 0) {
System.out.printf("%-9s %-3s %s \n", this.message1, this.message6, this.site);
System.out.printf("%s %-3s % 09.4f\n", this.message2, this.message6, this.lattitude);
System.out.printf("%s %-3s %9.4f\n", this.message3, this.message6, this.longitude);
System.out.printf("%-9s %-3s %-2d%s \n", this.message4, this.message6, this.days, this.message5);
}
}
private void displayHistogram() {
for (int amount : rainRecorded) {
for (int count = 0; count < amount; count++) {
System.out.print("*");
}
System.out.println(" " + amount);
}
}
public static void main(String[] args) {
#SuppressWarnings("unused")
RainRecording objName;
objName = new RainRecording();
}
}
Now, if rainEntered is suppose to be some kind of compounding array, where it allows you to record multiple days of rain over different periods, you might consider using a multi-dimensional array instead, so you could n periods and each period could have n days of rain...
my instructions on the project were as followed:
Instructions: Use a sentinel value loop. To create a basic Rental Car Calculator
Ask each user for:
Type of vehicle (May use something other than strings, such as: 1 for an economy, 2 for a sedan, etc.)
Days rented
Calculate the (For each customer):
Rental cost,
Taxes,
Total Due.
There are three different rental options with separate rates: Economy # 31.76, sedan # 40.32, SUV # 47.56. [Note: only whole day units to be considered (no hourly rates)].
Sales tax is = to 6% on the TOTAL.
Create summary data with:
Number of customers
Total money collected.
Also, Include IPO, algorithm, and desk check values (design documents).
{WHAT I HAVE GOING AND MY QUESTION(S)}
package tests;
import java.util.InputMismatchException;
import java.util.Scanner;
public class Tester {
public static void main(String []args){
int count=0;
int days;
int cus = 10;
double DailyFee=0, NontaxTotal, CarType, Total,FullTotal=0;
boolean F1 = false, F2 = false, F3 = false;
Scanner in=new Scanner(System.in);
while (F3 == false) {
F3 = true;
System.out.print("Press 1 to enter Rental Calculator or else press 0 to quit\n");
System.out.println("Please only enter 1 or 0. Also, please only enter number(s) not letter(s)");
try {
cus=in.nextInt();
if (cus == 0 || cus == 1) {
F3 = true;
} else {
F3 = false;
System.out.println("Number must be either 1 or 0");
}
} catch (InputMismatchException ex) {
F3 = false;
System.out.println("Invalid entry");
in.next();
}
}
if(cus == 1) {
while(F1 == false) {
F1 = true;
count++;
System.out.print("What vehical would you like to rent?\n");
System.out.println("Enter 1 for an economy car");
System.out.println("Enter 2 for a sedan car");
System.out.println("Enter 3 for an SUV");
//
try {
CarType = in.nextInt();
if (CarType <= 0 || CarType >= 4) {
System.out.print("Number must be 1-3\n");
System.out.println("Please enter 1 for an economy car");
System.out.println("Enter 2 for a sedan car");
System.out.println("Enter 3 for an SUV");
F1 = false;
} else {
if (CarType == 1) {
F1 = true;
DailyFee=31.76;
} else if(CarType == 2) {
F1 = true;
DailyFee=40.32;
} else if(CarType == 3) {
F1 = true;
DailyFee=47.56;
}
while (F2 == false) {
F2 = true;
try {
System.out.print("Please enter the number of days rented. (Example; 3) : ");
days = in.nextInt();
if (days <= 0) {
System.out.println("Number of days must be more than zero");
F2 = false;
} else {
double x=days;
NontaxTotal = (DailyFee * x);
Total = (NontaxTotal * 1.06);
FullTotal+=Total;
F3 = true;
}
} catch(InputMismatchException ex) {
System.out.println("Answer must be a number");
F2 = false;
in.next();
}
}
}
} catch (InputMismatchException ex) {
F1 = false;
System.out.println("Answer must be a number");
}
}
}
in.close();
System.out.println("Count of customers : " + count);
System.out.printf("Total of the Day : $ %.2f", FullTotal);
}
}
{MY QUESTIONS}
When a letter is entered to the prompt "Press 1 to enter Rental Calculator or else press 0 to quit" it displays, an error prompt then the console asks for input again. Similarly, when a letter is inputted at the prompt "What vehicle would you like to rent?" the console continues to print lines with no stop? I do not know how to fix this?
I want my program to allow multiple calculation inputs to be made. However, after full calculation input (Days * Tax * Car Type) the console post summary data rather than looping?
2a. After the prompt "Please enter the number of days rented. (Example; 3) : " and following user input. How would I get my program to loop back to asking "Press 1 to enter Rental Calculator or else press 0 to quit"? with still making 0 prompt my summary data?
I have just "refactored" your code a bit, removed some obsolete code and placed some other code on other locations.
I've also used more clear naming for variables, and followed the naming conventions.
The problem you had, was that you did not in each catch block had a in.next(); meaning that while iterating, the variable kept using the same variable (which was invalid) so kept looping over the error messages.
Now this code is far from perfect, it can easily be improved still, but this should get you started.
package tests;
import java.util.InputMismatchException;
import java.util.Scanner;
public class Tester {
public static void main(String []args){
int count=0;
int days;
int cus;
int carType;
double dailyFee=0, nonTaxTotal, total,fullTotal=0;
boolean checkRunOrQuit = false, chooseTypeVehicle = false, numberOfDAysChosen = false;
Scanner in=new Scanner(System.in);
while ( !checkRunOrQuit ) {
System.out.print("Press 1 to enter Rental Calculator or else press 0 to quit\n");
System.out.println("Please only enter 1 or 0. Also, please only enter number(s) not letter(s)");
try {
cus=in.nextInt();
switch ( cus ) {
case 0: System.out.println("End of application");
System.exit(0); // This will actually end your application if the user enters 0, no need to verify later on
break;
case 1: checkRunOrQuit = true;
break;
default:
System.out.println("Number must be either 1 or 0");
}
} catch (InputMismatchException ex) {
System.out.println("Invalid entry: ");
in.next();
}
}
while( !chooseTypeVehicle ) { // --> simplified comparison
count++;
System.out.print("What vehical would you like to rent?\n");
System.out.println("Enter 1 for an economy car");
System.out.println("Enter 2 for a sedan car");
System.out.println("Enter 3 for an SUV");
try {
carType = in.nextInt();
chooseTypeVehicle = true;
switch ( carType ) {
case 1: dailyFee = 31.76;
break;
case 2: dailyFee = 40.32;
break;
case 3: dailyFee = 47.56;
break;
default:
System.out.print("Number must be 1-3\n");
System.out.println("Please enter 1 for an economy car");
System.out.println("Enter 2 for a sedan car");
System.out.println("Enter 3 for an SUV");
chooseTypeVehicle = false;
break;
}
} catch (InputMismatchException ex) {
System.out.println("Answer must be a number");
in.next(); // -> you forgot this one.
}
}
while ( !numberOfDAysChosen ) {
try {
System.out.print("Please enter the number of days rented. (Example; 3) : ");
days = in.nextInt();
if (days <= 0) {
System.out.println("Number of days must be more than zero");
} else {
nonTaxTotal = (dailyFee * days);
total = (nonTaxTotal * 1.06);
fullTotal+=total;
numberOfDAysChosen = true;
}
} catch(InputMismatchException ex) {
System.out.println("Answer must be a number");
in.next();
}
}
in.close();
System.out.println("Count of customers : " + count);
System.out.printf("total of the Day : $ %.2f", fullTotal);
}
}
Here you go, i modified it a bit and put the whole thing in a while loop (while (cus != 0)) now it is working perfectly, try this code and do let me know if you have questions
package inter;
import java.util.InputMismatchException;
import java.util.Scanner;
public class Inter {
public static void main(String []args){
int count=0;
int days;
int cus = 10; // added
double DailyFee=0, NontaxTotal, CarType, Total,FullTotal=0;
boolean F1 = false, F2 = false;
Scanner in=new Scanner(System.in);
while (cus != 0) {
while (true) {
System.out.println("If there are any customer press 1 else press 0");
try {
cus=in.nextInt();
if (cus == 0 || cus == 1) {
break;
} else {
System.out.println("Number must be either 1 or 0");
}
} catch (InputMismatchException ex) {
System.out.println("Invalid entry");
in.next();
}
}
if(cus == 1) {
while(F1 == false) {
F1 = true;
count++;
System.out.print("What vehical would you like to rent?\n");
System.out.println("Enter 1 for an economy car");
System.out.println("Enter 2 for a sedan car");
System.out.println("Enter 3 for an SUV");
try {
CarType = in.nextInt();
if (CarType <= 0 || CarType >= 4) {
System.out.print("Number must be 1-3\n");
System.out.println("Please enter 1 for an economy car");
System.out.println("Enter 2 for a sedan car");
System.out.println("Enter 3 for an SUV");
F1 = false;
} else {
if (CarType == 1) {
F1 = true;
DailyFee=31.76;
} else if(CarType == 2) {
F1 = true;
DailyFee=40.32;
} else if(CarType == 3) {
F1 = true;
DailyFee=47.56;
}
while (F2 == false) {
F2 = true;
try {
System.out.print("Please enter the number of days rented. (Example; 3) : ");
days = in.nextInt();
if (days <= 0) {
System.out.println("Number of days must be more than zero");
F2 = false;
} else {
//days = in.nextInt();
double x=days;
NontaxTotal = (DailyFee * x);
Total = (NontaxTotal * 1.06);
FullTotal+=Total;
}
} catch(InputMismatchException ex) {
System.out.println("Answer must be a number");
F2 = false;
in.next();
}
}
F2 = false;
}
} catch (InputMismatchException ex) {
F1 = false;
System.out.println("Answer must be a number");
in.next();
}
}
F1 = false;
}
}
System.out.println("Count of customers : " + count);
System.out.printf("Total of the Day : $ %.2f", FullTotal);
}
}
I am having an issue where it isn't checking the validity of user input correctly. It breaks if I input a letter or string as a choice instead of looping through and asking again. I'm pretty sure that I have my functions, isDouble and isInt, correct and it's more a matter of placement. Advice?
public class Main
{
static Scanner scan = new Scanner(System.in);
public static void main(String[] args)
{
displayMenu();
int entryChoice = scan.nextInt();
while (entryChoice != 9)
{
System.out.println(userSelection(entryChoice));
displayMenu();
isInt(entryChoice);
entryChoice = scan.nextInt();
}
scan.close();
System.exit(0);
}
public static boolean isDouble(double x)
{
double userInput = x;
try
{
userInput = Double.parseDouble(scan.next());
return true;
}
catch (NumberFormatException ignore)
{
System.out.println("Invalid input. Try again.");
return false;
}
}
public static boolean isInt(int x)
{
int userInput = x;
try
{
userInput = Integer.parseInt(scan.next());
return true;
}
catch (NumberFormatException ignore)
{
System.out.println("Invalid input");
return false;
}
}
public static void displayMenu()
{
System.out.println("Please select from the following choices:");
System.out.println();
System.out.println("1) Addition");
System.out.println("2) Subtraction");
System.out.println("3) Multiplication");
System.out.println("4) Division");
System.out.println("5) Raise to a Power");
System.out.println("6) Square Root");
System.out.println("7) Store a Number");
System.out.println("8) Recall Stored Number");
System.out.println("9) Exit Program");
System.out.println();
System.out.println("Enter your choice here: ");
}
public static double userSelection(int entryChoice)
{
double result = 0;
double x = 0;
double y = 0;
if (entryChoice == 6)
{
System.out.println("Enter one number: ");
x = scan.nextDouble();
}
else
{
System.out.println("Enter two numbers seperated by a space");
x = scan.nextDouble();
y = scan.nextDouble();
}
switch (entryChoice)
{
case 1:
result = x + y;
break;
case 2:
result = x - y;
break;
case 3:
result = x * y;
break;
case 4:
if (y == 0)
{
System.out.println("Can't divide by zero. Please enter another number.");
y = scan.nextDouble();
result = x / y;
}
else
{
result = x / y;
}
break;
case 5:
result = Math.pow(x, y);
break;
case 6:
result = Math.sqrt(x);
break;
case 7:
//store a number
break;
case 8:
//recall a stored number
break;
case 9:
result = 0;
break;
default:
}
return result;
}
}
I'm pretty sure that I have my functions, isDouble and isInt, correct and it's more a matter of placement.
You don't.
Your isInt() method ignores its parameter, reads a new value from the scanner and checks to see if it's a number, and doesn't return the new value, whether or not it's a number.
In any case, the Scanner class you are using to collect user input already does this sort of validation for you. You started in the correct direction with
int entryChoice = scan.nextInt();
but it's dangerous to try to get a token from a Scanner without first checking to see if it has one for you to get.
If you look at the API docs for Scanner, you'll see a whole list of nextFoo() and hasNextFoo() methods. These are meant to be used together.
Generally what you want is a loop which prompts the user for the desired input until they give it, like this:
Scanner scan = new Scanner(System.in);
System.out.println("Please enter a number");
while (!scan.hasNextInt()) {
scan.next(); // throw away non-numeric input
System.out.println("Please enter a number");
}
System.out.println("User entered: " + scan.nextInt());
This will end up re-prompting the user until they give you a number:
Please enter a number
apple
Please enter a number
fox
Please enter a number
bear
Please enter a number
42
User entered: 42
Here is your code,However i did many changes.Wish this help you little.
import java.util.InputMismatchException;
import java.util.Scanner;
public class Main {
static Scanner scan = new Scanner(System.in);
static int entryChoice = 0;
static boolean tester = true;
static double result;
public static void main(String[] args) {
displayMenu();
boolean check = isInt(entryChoice);
while (check && entryChoice != 9) {
result = userSelection(entryChoice);
System.out.print(result == 0 && !tester ? "" : result + "\n");
if (!tester)
break;
}
scan.close();
System.exit(0);
}
/*
* public static boolean isDouble(double x) {
*
* try { x = Double.parseDouble(scan.next()); return true; } catch
* (NumberFormatException ignore) { System.out.println(
* "Invalid input. Try again.");
*
* return false; } }
*/
public static boolean isInt(int x) {
try {
x = Integer.parseInt(scan.next());
entryChoice = x;
return true;
} catch (NumberFormatException ignore) {
System.out.println("Invalid input");
System.err.println("program will be terminated!");
tester = false;
return false;
}
}
public static void displayMenu() {
System.out.println("Please select from the following choices:");
System.out.println();
System.out.println("1) Addition");
System.out.println("2) Subtraction");
System.out.println("3) Multiplication");
System.out.println("4) Division");
System.out.println("5) Raise to a Power");
System.out.println("6) Square Root");
System.out.println("7) Store a Number");
System.out.println("8) Recall Stored Number");
System.out.println("9) Exit Program");
System.out.println();
System.out.println("Enter your choice here: ");
}
public static double userSelection(int entryChoice) {
double result = 0;
double x = 0;
double y = 0;
if (entryChoice == 6) {
try {
System.out.println("Enter one number: ");
x = scan.nextDouble();
} catch (InputMismatchException ignore) {
System.out.println("Invalid input");
}
} else {
try {
System.out.println("Enter two numbers seperated by a space");
x = scan.nextDouble();
y = scan.nextDouble();
} catch (InputMismatchException ignore) {
System.err.println("Invalid input,program will be terminated !");
tester = false;
// return ;
}
}
switch (entryChoice) {
case 1:
result = x + y;
break;
case 2:
result = x - y;
break;
case 3:
result = x * y;
break;
case 4:
if (y == 0 && tester) {
System.out.println("Can't divide by zero. Please enter another number.");
try {
y = scan.nextDouble();
} catch (InputMismatchException ex) {
System.err.println("invalid input, program will be terminated");
tester = false;
}
result = x / y;
} else if (tester) {
result = x / y;
}
break;
case 5:
result = Math.pow(x, y);
break;
case 6:
result = Math.sqrt(x);
break;
case 7:
// store a number
break;
case 8:
// recall a stored number
break;
case 9:
result = 0;
break;
default:
}
return result;
}
}