Using Loops to Reset Basic Financial Calculator - java

I cannot quite figure out how to make my basic financial calculator be able to run a new set of numbers without closing the program. What I currently have allows me to run one set of numbers, and when I get to "Would you like to continue?", when I press 1 it simply will print "Would you like to continue?" however many times I press 1. Here is what I have so far:
package Register;
import java.util.Scanner;
public class Register {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Register myRegister = new Register();
System.out.println("Welcome to the Electricity Bill calculator.");
System.out.print("Enter amount of electricity (kW) used in the daytime: ");
float num1 = scan.nextFloat();
System.out.print("Enter amount of electricity (kW) used in the evening: ");
float num2 = scan.nextFloat();
System.out.print("Enter rate for daytime: ");
float num3 = scan.nextFloat();
System.out.print("Enter rate for evening: ");
float num4 = scan.nextFloat();
float day1 = num1 * num3;
float night2 = num2 * num4;
float total = day1 + night2;
{
System.out.println("Electricity Bill: $" + total);
}
System.out.println("");
boolean keepLooping = true;
while (keepLooping) {
System.out.print("Would you like to continue? Press 1 continue or 0 to exit.");
int answer = scan.nextInt();
if(answer == 0) {
keepLooping = false;
} else {
keepLooping = true;
}
}
}
}

You have used while loop around asking choice statements only. So use while loop at the beginning in main method as below:
import java.util.Scanner;
public class Register{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Register myRegister = new Register();
boolean keepLooping = true;
while(keepLooping) {
System.out.println("Welcome to the Electricity Bill calculator.");
System.out.print("Enter amount of electricity (kW) used in the daytime: ");
float num1 = scan.nextFloat();
System.out.print("Enter amount of electricity (kW) used in the evening: ");
float num2 = scan.nextFloat();
System.out.print("Enter rate for daytime: ");
float num3 = scan.nextFloat();
System.out.print("Enter rate for evening: ");
float num4 = scan.nextFloat();
float day1 = num1 * num3;
float night2 = num2 * num4;
float total = day1 + night2;
System.out.println("Electricity Bill: $" + total);
System.out.println("");
System.out.print("Would you like to continue? Press 1 continue or 0 to exit.");
int answer = scan.nextInt();
if(answer == 0) {
keepLooping = false;
} else {
keepLooping = true;
}
}
}
}

Related

How do I validate user input in Java

I wrote a bmi calculator program and I want to validate user input so that the user would not enter a negative number for the height or weight input.
How do I do this? I am new to Java, so I have no idea.
import java.util.Scanner;
public class BMICalculator {
public static void main(String[] args) throws Exception {
calculateBMI();
}
private static void calculateBMI() throws Exception {
System.out.print("Please enter your weight in kg: ");
Scanner s = new Scanner(System.in);
float weight = s.nextFloat();
System.out.print("Please enter your height in cm: ");
float height = s.nextFloat();
float bmi = (100*100*weight)/(height*height);
System.out.println("Your BMI is: "+bmi);
printBMICategory(bmi);
s.close();
}
private static void printBMICategory(float bmi) {
if(bmi < 24) {
System.out.println("You are underweight");
}else if (bmi < 29) {
System.out.println("You are healthy");
}else if (bmi < 34) {
System.out.println("You are overweight");
}else {
System.out.println("You are OBESE");
}
}
}
you can keep asking for value until the user input a valid number
private float readZeroOrPositiveFloat(Scanner scanner , String promptMessage)
{
float value = -1;
while(value < 0){
System.out.println(promptMessage);
value = scanner.nextFloat();
}
return value;
}
private static void calculateBMI() throws Exception {
System.out.print("Please enter your weight in kg: ");
Scanner s = new Scanner(System.in);
float weight = readZeroOrPositiveFloat(s , "Please enter your weight in kg: ");
float height = readZeroOrPositiveFloat(s , "Please enter your height in cm: ");
float bmi = (100*100*weight)/(height*height);
System.out.println("Your BMI is: "+bmi);
printBMICategory(bmi);
s.close();
}
Just to handle negative inputs and keep asking for valid input,
boolean flag = true;
while(flag){
System.out.print("Please enter your weight in kg: ");
int weight = sc.nextInt();
System.out.print("Please enter your height in cm: ");
int height = sc.nextInt();
if(weight >= 0 && height >= 0){
float bmi = (100*100*weight)/(height*height);
flag = false;
}else{
System.out.println("Invalid Input");
}
}
To handle all the unexpected inputs and keep asking for valid input,
boolean flag = true;
while(flag){
Scanner sc = new Scanner(System.in);
try{
System.out.print("Please enter your weight in kg: ");
int weight = sc.nextInt();
System.out.print("Please enter your height in cm: ");
int height = sc.nextInt();
if(weight >= 0 && height >= 0){
float bmi = (100*100*weight)/(height*height);
flag = false;
}else{
System.out.println("Invalid Input");
}
}catch(Exception e){
System.out.println("Invalid Input");
}
}
When you get input from the scanner, you could use an if statement to make sure the value is not negative. For example:
if(input value <= 0){
System.out.println("Invalid Input");
}else { *program continues* }

how to write while loop

I am currently making a simple ATM program in java.
I want to write a while loop where when user enters wrong pin it will prompt the user to enter again until the pin is matched. When the pin is matched, it will display the main menu.
I tried by myself, but I don't know how to fix it.
while(userPIN != savedPIN)
{
System.out.print("Please enter your correct PIN : ");
Scanner again = new Scanner(System.in);
int pass = again.nextInt();
break;
}
Remove the `break;' statement and update userPIN with the new pin as follows:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int savedPIN = 4444;
Scanner input = new Scanner(System.in);
System.out.println("Enter password");
int userPIN = input.nextInt();
double withdraw = 0.0, amount = 0.0, deposit = 0.0;
while (userPIN != savedPIN) {
System.out.print("Please enter your correct PIN : ");
Scanner again = new Scanner(System.in);
userPIN = again.nextInt();
}
while (userPIN == savedPIN) {
System.out.println(" 1 - Inquire Balance \n 2 - Withdraw \n 3 - Deposit \n 0 - Quit ");
Scanner inputNum = new Scanner(System.in);
int number = inputNum.nextInt();
switch (number) {
case 1:
System.out.println("The current balance is $" + amount);
break;
case 2:
System.out.println("Enter the amount to withdraw : ");
withdraw = input.nextDouble();
if (amount >= withdraw) {
amount = amount - withdraw;
System.out.println("The current balance is $" + amount);
} else {
System.out.println("Insufficient balance");
}
break;
case 3:
System.out.println("Enter the amount to deposit : ");
deposit = input.nextDouble();
amount = amount + deposit;
System.out.println("The current balance is $" + amount);
break;
case 0:
System.exit(4);
}
}
}
}
Ok 2 errors:
1)you test userPIN != savedPIN but you accept the value into variable pass with which you do nothing.
2)remove the break in the first loop it will always exit without looping.
it should look like :
while(pass!= savedPIN)
{
System.out.print("Please enter your correct PIN : ");
Scanner again = new Scanner(System.in);
int pass = again.nextInt();
}

Program is not quitting when choice 2 is entered instead it is asking to enter a positive number. What is the issue here?

The program is not quitting when choice 2 is entered instead it's asking to enter a positive value. It should only ask that if the choice was 1 and then the number of rooms entered was less than one. It should immediately quit the program but it's not. What can I do to fix this? Is it because of braces missing or extra ones.
import java.util.Scanner;
import java.text.DecimalFormat;
public class Paint {
public static void main(String[] args) {
DecimalFormat formatter = new DecimalFormat("###0.00");
Scanner keyboard = new Scanner(System.in);
double numbGallons;
double costPerGallon;
double totalSquareFeet = 0;
double numbHours;
double costPerHour;
double paintCost1;
double squareFeet;
int choice;
int numRooms = 0;
double laborCost1;
double totalEstimate;
do {
displayMenu();
choice = keyboard.nextInt();
if (choice == 1) {
System.out.println("How many rooms do you want to paint?");
numRooms = keyboard.nextInt();
}
while (numRooms < 1) {
System.out.println("Please enter a positive value");
numRooms = keyboard.nextInt();
}
for (int counter = 1; counter <= numRooms; counter++) {
System.out.println("How many square feet of room " + counter +
" do you want to paint?");
squareFeet = keyboard.nextDouble();
totalSquareFeet = totalSquareFeet + squareFeet;
}
System.out.println("The total square feet is " + totalSquareFeet);
numbGallons = numGallons(totalSquareFeet);
numbHours = numHours(totalSquareFeet);
System.out.println("How much is the price per hour?");
costPerHour = keyboard.nextDouble();
System.out.println("How much is the price per gallon?");
costPerGallon = keyboard.nextDouble();
laborCost1 = laborCost(costPerHour, numbHours);
paintCost1 = paintCost(numbGallons, costPerGallon);
System.out.println("The number of Gallons is " + numbGallons);
System.out.println("The number of Hours is " + numbHours);
System.out.println("The labor cost is " + laborCost1);
System.out.println("The paint cost is " + paintCost1);
totalEstimate = laborCost1 + paintCost1;
System.out.println("The total estimate is " + totalEstimate);
} while (choice != 2);
}
public static void displayMenu() {
System.out.println("1)Calculate Estimate");
System.out.println("2)Quit the program");
System.out.println("Please make a selection");
}
public static double numGallons(double sqr) {
return sqr / 115;
}
public static double numHours(double sqr) {
return (sqr / 115) * 8;
}
public static double laborCost(double cph, double nh) {
return cph * nh;
}
public static double paintCost(double ng, double cpg) {
return ng * cpg;
}
}
You should show the menu and get the choice before entering the loop, and at the end of the loop.
public static void main(String[] args) {
DecimalFormat formatter = new DecimalFormat("###0.00");
Scanner keyboard = new Scanner(System.in);
double numbGallons;
double costPerGallon;
double totalSquareFeet = 0;
double numbHours;
double costPerHour;
double paintCost1;
double squareFeet;
int choice;
int numRooms = 0;
double laborCost1;
double totalEstimate;
displayMenu();
choice = keyboard.nextInt();
while (choice != 2) {
//if (choice ==1)
//{
System.out.println("How many rooms do you want to paint?");
numRooms = keyboard.nextInt();
//}
while (numRooms < 1) {
System.out.println("Please enter a positive value");
numRooms = keyboard.nextInt();
}
for (int counter = 1; counter <= numRooms; counter++) {
System.out.println("How many square feet of room " + counter +
" do you want to paint?");
squareFeet = keyboard.nextDouble();
totalSquareFeet = totalSquareFeet + squareFeet;
}
System.out.println("The total square feet is " + totalSquareFeet);
numbGallons = numGallons(totalSquareFeet);
numbHours = numHours(totalSquareFeet);
System.out.println("How much is the price per hour?");
costPerHour = keyboard.nextDouble();
System.out.println("How much is the price per gallon?");
costPerGallon = keyboard.nextDouble();
laborCost1 = laborCost(costPerHour, numbHours);
paintCost1 = paintCost(numbGallons, costPerGallon);
System.out.println("The number of Gallons is " + numbGallons);
System.out.println("The number of Hours is " + numbHours);
System.out.println("The labor cost is " + laborCost1);
System.out.println("The paint cost is " + paintCost1);
totalEstimate = laborCost1 + paintCost1;
System.out.println("The total estimate is " + totalEstimate);
displayMenu();
choice = keyboard.nextInt();
}
}

Issue with looping in Java code

Use a while loop to keep asking the user to enter the order of
numbers until the user does give two numbers in the right order (first
smaller than second
Hi! i'm a beginner in java and I have this code but I can't loop the "error" message. it just prints 2 times
import java.util.Scanner;
public class Q6 {
public static void main(String[] args) {
int num1, num2;
Scanner keyboard = new Scanner(System.in);
System.out.print("Please type two numbers:");
num1 = keyboard.nextInt();
num2 = keyboard.nextInt();
if (num1 < num2) {
int counter = num1;
while (counter <= num2) {
System.out.print(counter + " ");
counter = counter + 1;
}
}
else {
System.out.println("Error: the first number must be smaller than the second");
System.out.print("Please type two numbers: ");
num1 = keyboard.nextInt();
num2 = keyboard.nextInt();
}
}
}
int num1,num2;
while (num1>=num2) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Please type two numbers");
System.out.printn("first number must be smaller than the second:)";
num1 = keyboard.nextInt();
num2 = keyboard.nextInt();
}
int num1,num2;
while (num1>=num2) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Please type two numbers:");
num1 = keyboard.nextInt();
num2 = keyboard.nextInt();
if(num1>=num2) {
System.out.println("Error: First number must be smaller than the second.");
}
}

Calculating Areas of Geometric Figures using multiple methods in Java

My program will calculate the area but I need to have each different shape in it's own method and I'm having difficulty understanding how to first separate them all into their own method and link them all together. Any help is much appreciated.
import java.util.Scanner;
public class Project4 {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String s = "Please choose which area/volume to calculate: 1-Circle 2-Triangle 3-Cone 4-Cylinder 5-Sphere 6-Quit: ";
System.out.print(s);
System.out.println(" ");
int num = keyboard.nextInt();
if (num < 1 || num > 6){
System.out.print("Please choose a number between 1 and 6: ");
num = keyboard.nextInt();
}
if(num == 1){
System.out.print("Please enter the radius: ");
double r = keyboard.nextDouble();
double a;
a = 3.14 * r * r;
System.out.print("The area of the circle is: " + a);
System.out.println(" ");
System.out.print(s);
num = keyboard.nextInt();
}
if(num == 2){
System.out.print("Please enter the base: ");
double b = keyboard.nextDouble();
double at;
System.out.print("Please enter the height: ");
double h = keyboard.nextDouble();
at = .5 * b * h;
System.out.print("The area of the triangle is: " + at);
System.out.println(" ");
System.out.print(s);
num = keyboard.nextInt();
}
if(num == 3){
System.out.print("Please enter the radius: ");
double r = keyboard.nextDouble();
System.out.print("Please enter the height: ");
double h = keyboard.nextDouble();
double v1;
v1 = (1/3) * 3.14 * r * r * h;
System.out.print("The volume of the cone is: " + v1);
System.out.println(" ");
System.out.print(s);
num = keyboard.nextInt();
}
if(num == 4){
System.out.print("Please enter the radius: ");
double r = keyboard.nextDouble();
System.out.print("Please enter the height: ");
double h = keyboard.nextDouble();
double vc;
vc = 3.14 * r * r * h;
System.out.print("The volume of the cylinder is: " + vc);
System.out.println(" ");
System.out.print(s);
num = keyboard.nextInt();
}
if(num == 5){
System.out.print("Please enter the radius: ");
double r = keyboard.nextDouble();
double vs;
vs = (4/3) * 3.14 * r * r * r;
System.out.print("The volume of the sphere is: " + vs);
System.out.println(" ");
System.out.print(s);
num = keyboard.nextInt();
}
if(num == 6){
System.out.print("Thank you for using this program");
}
}
}
You can use switch..case
switch(num) {
case 1: calculateCircleArea();
break;
case 2: calculateTriangleArea();
break;
case 3: calculateConeVolume();
break;
case 4: calculateCylinderVolume();
break;
case 5: calculateSphereVolume();
break;
case 6: System.out.print("Thank you for using this program");
break;
default: System.out.print("Please choose a number between 1 and 6: ");
break;
}
You can create new private/public methods to do the calculations and seperate them.
Take this part
if(num == 1){
System.out.print("Please enter the radius: ");
double r = keyboard.nextDouble();
double a;
a = 3.14 * r * r;
System.out.print("The area of the circle is: " + a);
System.out.println(" ");
System.out.print(s);
num = keyboard.nextInt();
}
You can create a new method for the calculation like so
public static double getArea(double radius)
{
return 3.14*radius*radius;
}
Then, inside your if statement you can say
if(num == 1){
System.out.print("Please enter the radius: ");
double r = keyboard.nextDouble();
double a;
a = getArea(r);
System.out.print("The area of the circle is: " + a);
System.out.println(" ");
System.out.print(s);
num = keyboard.nextInt();
}
you see in this case, you get a one-line method which isn't very usefull. But you can split off more extensive calculations as well, this is just as an example. In addition, instead of all the if-blocks, you can use a switch statement like the other answer shows you.

Categories