how to add try and catch for this Java Program? - java

and i just created a program for fare with discount. but I dont know where to put the try and catch.
this is the program without try and catch
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String passengerType;
double distance;
double minimumFare = 20;
double fare1, finalFare;
System.out.println("Enter the type of Passenger (Ordinary/Student/Senior): ");
passengerType = input.nextLine();
System.out.println("Enter the Distance: ");
distance = input.nextDouble();
// Condition for "Ordinary Passenger"
if (passengerType.equalsIgnoreCase("Ordinary"))
{
if (distance <= 10)
{
System.out.println("Your Fare is: "+minimumFare);
}
else if (distance > 10)
{
fare1 = (distance - 10) * 2.50;
finalFare = fare1 + minimumFare;
System.out.println("Your Fare is: "+finalFare);
}
}
// Condition for "Student Passenger"
else if (passengerType.equalsIgnoreCase("Student"))
{
if (distance <= 10)
{
finalFare = 20 - (20 * 0.20);
System.out.println("Your Fare is: "+ finalFare);
}
else if (distance > 10)
{
fare1 = ((distance - 10) * 2.50);
finalFare = fare1 + 20 - ((fare1 + 20) * 0.20);
System.out.println("Your Fare is: "+finalFare);
}
}
// Condition for "Senior Passenger"
else if (passengerType.equalsIgnoreCase("Senior"))
{
if (distance <= 10)
{
finalFare = 20 - (20 * 0.30);
System.out.println("Your Fare is: "+ finalFare);
}
else if (distance > 10)
{
fare1 = ((distance - 10) * 2.50);
finalFare = fare1 + 20 - ((fare1 + 20) * 0.30);
System.out.println("Your Fare is: "+ finalFare);
}
}
}
}
the output of the program must be these.(when error input)
thank you so much in advance, its my first time in java language. please don't vote negative ^_^

I'm also new at this, but if you were to run the programme, and try to put in a different input than suggested. For example putting string where you need an int or putting an int where you need string, when you run the programme the compiler will show you the exceptions which you need to catch.
I've altered the start of the programme, just to show you how i'd do it, i'm also not the best but hopefully this puts you on the right track
Scanner input = new Scanner(System.in);
String passengerType = null;
double distance = 0;
double minimumFare = 20;
double fare1, finalFare;
try {
System.out.println("Enter the type of Passenger (Ordinary/Student/Senior): ");
passengerType = input.nextLine();
System.out.println("Enter the Distance: ");
distance = input.nextDouble();
} catch (InputMismatchException e){
System.out.println("Please enter strings for passenger and numbers for distance " + e);
}
also check out the link
When should an IllegalArgumentException be thrown?

Your code never throws any Exception. try and catch blocks are used to catch Exceptions that may be thrown when calling methods that throw them (you can see it on method declaration). If you want to output that an argument is invalid, add an else statement after your conditions, and throw an IllegalArgumentException:
else {
throw new IllegalArgumentException("You did something wrong");
}
Or if you want a "cleaner" error, output it to System.err, so that the user doesn't need to see the stack trace:
else {
System.err.println("Invalid Passenger Type");
}
The same goes to checking if distance is a String, like the other answer showed.

In this case, you are making use of a Scanner which needs to be closed after use, so it is best to go with a try-with-resources statement which will take care of automatically closing the Scanner when it is done.
Also, in order to ensure valid input is gotten, I have included an input checker to keep reading until a valid string is entered for Passenger and a Distance >= 0 is entered.
In the case of Distance, using the input.nextDouble() ensures the input is a valid number and will throw an InputMismatchException if it is not a valid number. Consider reading the input as a String and parse it to Double, that way you have more control over what happens and can demand a new input without the program being terminated. The way it is currently, the program will get terminated as there is no way to read a new input after displaying the error message.
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
String passengerType;
double distance;
double minimumFare = 20;
double fare1, finalFare;
try(Scanner input = new Scanner(System.in);){
System.out.println("Enter the type of Passenger (Ordinary/Student/Senior): ");
passengerType = input.nextLine();
while(passengerType == null || passengerType.trim().equals("") || (!passengerType.equals("Ordinary") && !passengerType.equals("Student") && !passengerType.equals("Senior"))){
System.out.println("Valid Passengers are Ordinary/Student/Senior: ");
passengerType = input.nextLine();
}
System.out.println("Enter the Distance: ");
distance = input.nextDouble();
while(distance < 0){
System.out.println("Distance must be greater than or equal to 0: ");
distance = input.nextDouble();
}
System.out.println("Input read: " + passengerType + ", " + distance);
} catch (InputMismatchException e){
System.out.println("Distance must be a number");
return;
} catch (Exception e){
e.printStackTrace();
return;
}
// Condition for "Ordinary Passenger"
if (passengerType.equalsIgnoreCase("Ordinary"))
{
if (distance <= 10)
{
System.out.println("Your Fare is: "+minimumFare);
}
else if (distance > 10)
{
fare1 = (distance - 10) * 2.50;
finalFare = fare1 + minimumFare;
System.out.println("Your Fare is: "+finalFare);
}
}
// Condition for "Student Passenger"
else if (passengerType.equalsIgnoreCase("Student"))
{
if (distance <= 10)
{
finalFare = 20 - (20 * 0.20);
System.out.println("Your Fare is: "+ finalFare);
}
else if (distance > 10)
{
fare1 = ((distance - 10) * 2.50);
finalFare = fare1 + 20 - ((fare1 + 20) * 0.20);
System.out.println("Your Fare is: "+finalFare);
}
}
// Condition for "Senior Passenger"
else if (passengerType.equalsIgnoreCase("Senior"))
{
if (distance <= 10)
{
finalFare = 20 - (20 * 0.30);
System.out.println("Your Fare is: "+ finalFare);
}
else if (distance > 10)
{
fare1 = ((distance - 10) * 2.50);
finalFare = fare1 + 20 - ((fare1 + 20) * 0.30);
System.out.println("Your Fare is: "+ finalFare);
}
}
}
}

Related

Outputting a condition I didn't mean to get, probably code blocks are not managed properly

New to Java, having hard time with the blocks, the output should be only "Error invalid numbers" when inputting sum = 9 , examGrade = 105 and average = 105.
Output is now :
"Error invalid numbers"
100
100.00
It's somehow gets to the else condition , didn't succeed to manage it, thank you for help in advance :)
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int examGrade = 0, sum;
double average = 0;
System.out.println("Please enter your Exam Grade");
examGrade = input.nextInt();
System.out.println("Please enter your homework average");
average = input.nextDouble();
System.out.println("Please enter number of exercise");
sum = input.nextInt();
if (sum > 8 || examGrade > 100 || average > 100) {
System.out.println("Error invaild numbers");
}
if (sum <= 4) {
System.out.println("Your Final grade is zero");
}
if (sum == 5 || sum == 6) {
if (examGrade >= 55) {
System.out.println(examGrade*0.8 + average*0.2);
}
}
else {
System.out.println(examGrade);
}
if (sum == 7 || sum == 8) {
if(examGrade <= 54) {
if(average >= 80) {
System.out.println(examGrade*0.75 + average*0.25);
}
else if(average < 80) {
System.out.println(examGrade*0.8 + average*0.2);
}
}
}
else {
System.out.println(examGrade*0.7 + average*0.3);
}
}
You probably want to not do all the other checks if you have an "invalid numbers" condition. To do that, you need to wrap all of them into an else like this:
if (sum > 8 || examGrade > 100 || average > 100 ) {
System.out.println("Error invaild numbers");
} else {
if (sum <= 4 ) {
System.out.println("Your Final grade is zero");
}
// and so on with all the other ifs
} // finish the "not invalid" block

How to return Scanner.in value from the method to another method

I want to make some simple program which will count monthly rate of product. There is two inputs: cost of the product - between 100-10000 and number of rates - between 6-48. I wanted to do it like in the code below:
import java.util.Scanner;
public class Calculator {
Scanner sc = new Scanner (System.in);
double productCost;
int numberOfRates;
double loanInterestRate;
double monthlyRate;
Double print () {
Calculator c = new Calculator();
System.out.println ("Enter the value of your product from 100 to 10 000 : ");
productCost=sc.nextDouble();
if (productCost < 100){
System.out.println ("You have to choose price between 100 to 10000. Try again: ");
c.print();
} else if (productCost >10000){
System.out.println ("You have to choose price between 100 to 10000. Try again: ");
c.print();
} else if (productCost >= 100 || productCost <=10000){
c.print1();
return = productCost;
// how to return productCost to be used in next method print1()?
}
else return null;
}
void print1(){
Calculator c = new Calculator();
System.out.println ("Now enter how many rates do you want to pay from 6 to 48: ");
numberOfRates=sc.nextInt();
if (numberOfRates<6){
System.out.println ("You can't choose this number of rates. Choose between 6-48: ");
c.print1();
} else if (numberOfRates>48){
System.out.println ("You can't choose this number of rates. Choose between 6-48: ");
c.print1();
} else if (numberOfRates>=6 || numberOfRates<=12) {
loanInterestRate=1.025;
monthlyRate = (productCost*loanInterestRate)/numberOfRates;
System.out.printf("Your monthly rate is: "+ "%.2f%n",monthlyRate);
} else if (numberOfRates>=13 || numberOfRates <=24 ) {
loanInterestRate=1.05;
monthlyRate = (productCost*loanInterestRate)/numberOfRates;
System.out.printf("Your monthly rate is: "+ "%.2f%n",monthlyRate);
} else if (numberOfRates >=25|| numberOfRates<=48){
loanInterestRate=1.1;
monthlyRate = (productCost*loanInterestRate)/numberOfRates;
System.out.printf("Your monthly rate is: "+ "%.2f%n",monthlyRate);
}
}
}
And the main method only calling the method from the other class.
public class MonthlyRate {
public static void main(String[] args) {
Calculator calc = new Calculator();
calc.print();
// TODO code application logic here
}
}
And what is the problem, I don't know how to return the "double productCost" from the method "print()". productCost is taking from the input and this is double but NetBeans showing me that it's not correct type. Can anybody help me understand where is the problem?
Simply do
return productCost;
return is a keyword, not a variable. It 'returns' the given value and exits the function, so that the entity calling the function can do this:
public static void main(String[] args) {
...
double cost = calc.print(); // note calc.print() PRODUCES a value, which we assign to `cost`
...
}
You can then do whatever you want with cost (or whatever you choose to name the variable), including passing it to another function.
Your program needs changes in a few places. I have done those changes and written below the updated program:
import java.util.Scanner;
class Calculator {
Scanner sc = new Scanner(System.in);
double productCost;
int numberOfRates;
double loanInterestRate;
double monthlyRate;
void print() {
Calculator c = new Calculator();
System.out.println("Enter the value of your product from 100 to 10 000 : ");
productCost = sc.nextDouble();
if (productCost < 100) {
System.out.println("You have to choose price between 100 to 10000. Try again: ");
c.print();
} else if (productCost > 10000) {
System.out.println("You have to choose price between 100 to 10000. Try again: ");
c.print();
} else if (productCost >= 100 || productCost <= 10000) {
print1(productCost);
}
}
void print1(double productCost) {
Calculator c = new Calculator();
System.out.println("Now enter how many rates do you want to pay from 6 to 48: ");
numberOfRates = sc.nextInt();
if (numberOfRates < 6) {
System.out.println("You can't choose this number of rates. Choose between 6-48: ");
c.print1(productCost);
} else if (numberOfRates > 48) {
System.out.println("You can't choose this number of rates. Choose between 6-48: ");
c.print1(productCost);
} else if (numberOfRates >= 6 || numberOfRates <= 12) {
loanInterestRate = 1.025;
monthlyRate = (productCost * loanInterestRate) / numberOfRates;
System.out.printf("Your monthly rate is: " + "%.2f%n", monthlyRate);
} else if (numberOfRates >= 13 || numberOfRates <= 24) {
loanInterestRate = 1.05;
monthlyRate = (productCost * loanInterestRate) / numberOfRates;
System.out.printf("Your monthly rate is: " + "%.2f%n", monthlyRate);
} else if (numberOfRates >= 25 || numberOfRates <= 48) {
loanInterestRate = 1.1;
monthlyRate = (productCost * loanInterestRate) / numberOfRates;
System.out.printf("Your monthly rate is: " + "%.2f%n", monthlyRate);
}
}
}
public class MonthlyRate {
public static void main(String[] args) {
Calculator calc = new Calculator();
calc.print();
// TODO code application logic here
}
}
It is easy to understand the changes after comparing your program with this updated program. Nevertheless, feel free to let me know if you need any further help on this.

Java -vending machine that can't accept pennies

So I'm working on a java project that involves creating a soda machine that adjusts price based on temperature. I can't seem to figure out how to make sure the machine does NOT accept pennies when accepting payment from the user.
I feel like I'm overcoding but I'm at my wit's end because I don't have any clue how to not accept pennies.
import java.util.*;
import java.text.*;
public class SodaMachine extends SodaTester
{
public static void main(String[] args)
{
double temp;
double money;
double change;
double price1 = .50;
double price2 = .55;
double price3 = .60;
double price4 = .65;
double price5 = .75;
double price6 = .80;
double price7 = .85;
double price8 = .90;
double price9 = 1.00;
System.out.println("Hi there! Please enter the temperature in Farenheit:");
Scanner scan = new Scanner(System.in);
temp = scan.nextDouble();
DecimalFormat fmt = new DecimalFormat("0.#");
NumberFormat fmt2 = NumberFormat.getCurrencyInstance();
if (temp < 40 || temp > 120)
{
System.out.println("Invalid input. Temperature should be between 40 and 120 degrees Farenheit.");
while (temp < 40 || temp > 120)
{
temp = scan.nextDouble();
System.out.println("The rounded temperature in degrees Farenheit is: " + fmt.format(temp));
System.out.println("Invalid input. Temperature should be between 40 and 120 degrees Farenheit.");
}
}
if(temp < 50 && temp >= 40)
{
System.out.println("The rounded temperature in degrees Farenheit is: " + fmt.format(temp));
System.out.println("The price is: " + fmt2.format(price1));
System.out.println("Please insert amount of payment: ");
money = scan.nextDouble();
while (money < price1)
{
System.out.println("Invalid input please try again. Your total is: " + fmt2.format(price1));
money = scan.nextDouble();
}
change = money - price1;
System.out.println("Your Change is: " + fmt2.format(change));
}else if (temp >= 50 && temp <= 60) {
System.out.println("The rounded temperature in degrees Farenheit is: " + fmt.format(temp));
System.out.println("The price is: " + fmt2.format(price2));
System.out.println("Please insert amount of payment: ");
money = scan.nextDouble();
while (money < price2)
{
System.out.println("Invalid input please try again. Your total is: " + fmt2.format(price2));
money = scan.nextDouble();
}
change = money - price2;
System.out.println("Your Change is: " + fmt2.format(change));
}else if (temp > 60 && temp <= 65) {
System.out.println("The rounded temperature in degrees Farenheit is: " + fmt.format(temp));
System.out.println("The price is: " + fmt2.format(price3));
System.out.println("Please insert amount of payment: ");
money = scan.nextDouble();
while (money < price3)
{
System.out.println("Invalid input please try again. Your total is: " + fmt2.format(price3));
money = scan.nextDouble();
}
change = money - price3;
System.out.println("Your Change is: " + fmt2.format(change));
}else if (temp > 65 && temp <= 70) {
System.out.println("The rounded temperature in degrees Farenheit is: " + fmt.format(temp));
System.out.println("The price is: " + fmt2.format(price4));
System.out.println("Please insert amount of payment: ");
money = scan.nextDouble();
while (money < price4)
{
System.out.println("Invalid input please try again. Your total is: " + fmt2.format(price4));
money = scan.nextDouble();
}
change = money - price4;
System.out.println("Your Change is: " + fmt2.format(change));
}else if (temp > 70 && temp <= 75) {
System.out.println("The rounded temperature in degrees Farenheit is: " + fmt.format(temp));
System.out.println("The price is: " + fmt2.format(price5));
System.out.println("Please insert amount of payment: ");
money = scan.nextDouble();
while (money < price5)
{
System.out.println("Invalid input please try again. Your total is: " + fmt2.format(price5));
money = scan.nextDouble();
}
change = money - price5;
System.out.println("Your Change is: " + fmt2.format(change));
}else if (temp > 75 && temp <= 80) {
System.out.println("The rounded temperature in degrees Farenheit is: " + fmt.format(temp));
System.out.println("The price is: " + fmt2.format(price6));
System.out.println("Please insert amount of payment: ");
money = scan.nextDouble();
while (money < price6)
{
System.out.println("Invalid input please try again. Your total is: " + fmt2.format(price6));
money = scan.nextDouble();
}
change = money - price6;
System.out.println("Your Change is: " + fmt2.format(change));
}else if (temp > 80 && temp <= 85) {
System.out.println("The rounded temperature in degrees Farenheit is: " + fmt.format(temp));
System.out.println("The price is: " + fmt2.format(price7));
System.out.println("Please insert amount of payment: ");
money = scan.nextDouble();
while (money < price7)
{
System.out.println("Invalid input please try again. Your total is: " + fmt2.format(price7));
money = scan.nextDouble();
}
change = money - price7;
System.out.println("Your Change is: " + fmt2.format(change));
}else if (temp > 85 && temp <= 90) {
System.out.println("The rounded temperature in degrees Farenheit is: " + fmt.format(temp));
System.out.println("The price is: " + fmt2.format(price8));
System.out.println("Please insert amount of payment: ");
money = scan.nextDouble();
while (money < price8)
{
System.out.println("Invalid input please try again. Your total is: " + fmt2.format(price8));
money = scan.nextDouble();
}
change = money - price8;
System.out.println("Your Change is: " + fmt2.format(change));
}else if (temp > 90 && temp <= 120) {
System.out.println("The rounded temperature in degrees Farenheit is: " + fmt.format(temp));
System.out.println("The price is: " + fmt2.format(price9));
System.out.println("Please insert amount of payment: ");
money = scan.nextDouble();
while (money < price9)
{
System.out.println("Invalid input please try again. Your total is: " + fmt2.format(price9));
money = scan.nextDouble();
}
change = money - price9;
System.out.println("Your Change is: " + fmt2.format(change));
}
}
}
I won't go into detail about your current code, but you basically want to check if the decimal value you've read from the user modulo-0.05 equals 0 (so it has no remainder). One issue in this is that floating point precision can interfere with the checks when you use double, which is why you'd always want to use java.math.BigDecimal for currency calculations.
Here an example:
BigDecimal input = new BigDecimal(scanner.next());
if(input.remainder(new BigDecimal("0.05")).compareTo(BigDecimal.ZERO) == 0){
System.out.println("Input "+input+" is valid!");
} else{
System.out.println("Input "+input+" is not valid!");
}
For the inputs "1", "1.00", "1.05", "4.35", "1.01", "3.21", "4.68" it will output the following:
Input 1 is valid!
Input 1.00 is valid!
Input 1.05 is valid!
Input 4.35 is valid!
Input 1.01 is not valid!
Input 3.21 is not valid!
Input 4.68 is not valid!
Try it online.
Since BigDecimal can be quite confusing for new Java users, you could perhaps let the user input the amount in cents (so as integers), in which case it can be something like this instead:
int input = scanner.nextInt();
if(input % 5 == 0){
System.out.println("Input "+input+" is valid!");
} else{
System.out.println("Input "+input+" is not valid!");
}
For the input "100", "105", "435", "101", "321", "468" it will output the following:
Input 100 is valid!
Input 105 is valid!
Input 435 is valid!
Input 101 is not valid!
Input 321 is not valid!
Input 468 is not valid!
Try it online.
EDIT: Since I had some time, I reworked your solution with re-usable methods.
Please have a good look what I did, and if you have any questions about specific parts let me know. It now uses recursive methods until the user enters a valid input. The boolean showMessage parameters in the methods are to show the "Please enter X" messages only once.
import java.lang.IllegalArgumentException;
import java.lang.NumberFormatException;
import java.math.BigDecimal;
import java.text.NumberFormat;
import java.util.InputMismatchException;
import java.util.Scanner;
public class SodaMachine{
private static final String currencySymbol = "$";
private static final BigDecimal roundOn = new BigDecimal("0.05");
private Scanner scanner;
private NumberFormat currencyFormat;
public SodaMachine(){
scanner = new Scanner(System.in);
currencyFormat = NumberFormat.getCurrencyInstance();
}
public static void main(String[] args){
SodaMachine sodaMachine = new SodaMachine();
double farenheitInput = sodaMachine.enterFarenheit(true);
System.out.println("The temperature in degrees Farenheit you've entered is: " + farenheitInput);
BigDecimal price = sodaMachine.determinePrice(farenheitInput);
System.out.println("The price is: " + sodaMachine.currencyFormat.format(price));
BigDecimal payment = sodaMachine.enterPayment(price, true);
BigDecimal change = payment.subtract(price);
System.out.println("Your change is: " + sodaMachine.currencyFormat.format(change));
}
private double enterFarenheit(boolean showMessage){
if(showMessage){
System.out.println("Hi there! Please enter the temperature in Farenheit:");
}
double farenheitInput;
try{
farenheitInput = scanner.nextDouble();
} catch(InputMismatchException ex){
scanner.nextLine(); // Get rid of the invalid user-input
System.out.println("The value you've entered is not a valid. The input should be a decimal input. Please try again.");
return enterFarenheit(false);
}
if(farenheitInput < 40 | farenheitInput > 120){
System.out.println("Invalid input. Temperature should be between 40 and 120 degrees Farenheit.");
return enterFarenheit(false);
}
return farenheitInput;
}
private BigDecimal determinePrice(double farenheit){
String strPrice;
// Temperature is in the range [40, 50):
if(farenheit >= 40 && farenheit < 50){
strPrice = "0.50";
}
// Temperature is in the range [50, 60]:
else if(farenheit >= 50 && farenheit <=60){
strPrice = "0.55";
}
// Temperature is in the range (60, 65]:
else if(farenheit > 60 && farenheit <= 65){
strPrice = "0.60";
}
// Temperature is in the range (65, 70]:
else if(farenheit > 65 && farenheit <= 70){
strPrice = "0.65";
}
// Temperature is in the range (70, 75]:
else if(farenheit > 70 && farenheit <= 75){
strPrice = "0.75";
}
// Temperature is in the range (75, 80]:
else if(farenheit > 75 && farenheit <= 80){
strPrice = "0.80";
}
// Temperature is in the range (80, 85]:
else if(farenheit > 80 && farenheit <= 85){
strPrice = "0.85";
}
// Temperature is in the range (85, 90]:
else if(farenheit > 85 && farenheit <= 90){
strPrice = "0.90";
}
// Temperature is in the range (90, 120]:
else if(farenheit > 90 && farenheit <= 120){
strPrice = "1.00";
}
// Invalid temperature range:
else{
// Since we already validated the input-range, it should never go here,
// but added it just in case.
throw new IllegalArgumentException("The temperature must be in the range [40, 120]!");
}
return new BigDecimal(strPrice);
}
private BigDecimal enterPayment(BigDecimal price, boolean showMessage){
if(showMessage){
System.out.println("Please enter amount of payment: ");
}
String userInput = scanner.next();
// Remove the optional currency symbol from the user input
userInput = userInput.replace(currencySymbol, "");
BigDecimal paymentInput;
try{
paymentInput = new BigDecimal(userInput);
} catch(NumberFormatException ex){
scanner.nextLine(); // Get rid of the invalid user-input
System.out.println("The value you've entered is not a valid. The input should be a price input. Please try again.");
return enterPayment(price, false);
}
if(paymentInput.compareTo(price) < 0){
System.out.println("Your payment of " + currencyFormat.format(paymentInput) + " is too low. Please try again. The total price is: " + currencyFormat.format(price));
return enterPayment(price, false);
}
if(paymentInput.remainder(roundOn).compareTo(BigDecimal.ZERO) != 0){
System.out.println("Your payment should be rounded to " + currencyFormat.format(roundOn) + ". Please try again.");
return enterPayment(price, false);
}
return paymentInput;
}
}
Try it online.
Your code can be simplified alot, but I will focus on the issue at hand.
I would create a function to get user input, ensuring it does not contain pennies:
double getMoney(String prompt, Scanner scan)
{
double money = 0;
while(true) { // Loop until proper input
System.out.println(prompt);
money = scan.nextDouble();
// There are a few ways to determine if it has pennies.
// I will convert to int and check if it is divisible
// by 10 or 5
int i = (int)Math.round(money * 100); // Convert to pennies
if (0 == i % 5) {
// It's ok, return
return money;
}
}
}
Side note: using floating point for currency is bad practice. Floating point can introduce rounding errors. It's better to use integers and store the values using the lowest denomination. In this case pennies.

Interest calculator not displaying results

I'm trying to finish this at the last minute for my Java class, when I run the program after it asks the user if the information is correct, it just loops back to the first question no matter what. Here's the code:
import java.util.Scanner;
public class InterestCalculator {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String userResponse = null;
do {
int quartersDisplayed = -1;
double startingBalance = -1,
interestRate = -1;
do {
System.out.println("Enter the numbers of quarters you wish to display that is greater than zero and less or equal to 10: ");
userResponse = input.next();
try{
quartersDisplayed = Integer.parseInt(userResponse);
} catch(NumberFormatException e) {
}
if(quartersDisplayed <= 0 || quartersDisplayed > 10) {
System.out.println("Sorry, that value is not valid.");
} else {
break;
}
} while(true);
do {
System.out.println("Enter the starting balance (must be greater than zero): ");
userResponse = input.next();
try {
startingBalance = Double.parseDouble(userResponse);
} catch(NumberFormatException e) {
}
if(startingBalance <= 0) {
System.out.println("Sorry, that value is not valid.");
} else {
break;
}
} while(true);
do {
System.out.println("Enter the interest rate (greater than zero less than twenty percent): ");
userResponse = input.next();
try {
interestRate = Double.parseDouble(userResponse);
} catch(NumberFormatException e) {
}
if(interestRate <= 0 || interestRate > 20){
System.out.println("Sorry, that value is not valid.");
} else {
break;
}
} while(true);
System.out.println("You have entered the following amount of quarters: "
+ quartersDisplayed);
System.out.println("You also entered the starting balance of: " + startingBalance);
System.out.println("Finally, you entered the following of interest rate: "
+ interestRate);
System.out.println("If this information is not correct, please exit the program and enter the correct information.");
double quarterlyEndingBalance = startingBalance + (startingBalance * interestRate / 100 * .25);
System.out.println("Your ending balance for your quarters is "
+ quarterlyEndingBalance);
System.out.println("Do you want to continue?");
userResponse = input.next();
if("y".equalsIgnoreCase(userResponse) || "yes".equalsIgnoreCase(userResponse))
continue;
else
break;
} while(true);
}
}
What I am looking for as a sample output:
Enter number of quarters from 1 to 10
5
Enter the beginning principal balance greater than zero
4500
Enter the interest rate percentage without the percent sign, greater than 0 percent and less than/equal to 20%
3.5
You entered a principal balance of $4500.0 for 5 quarters at 3.5% interest.
Is this correct? (y/n)
y
Quarter Beginning Interest Ending
Number Balance Earned Balance
1 4500.00 39.38 4539.38
ect ect
Maybe what you ment to do is to restart the loop, if the input was wrong. In this case, you just need to switch the continue and the break.
The continue statement makes a loop immediately start the next iteration. You shoud either remove it by an empty statement ;, or negate the if-condition, remove the else and make it break on true. In addition, your code does nothing else, then getting the input and asking whether it is correct. And as it is written inside a do...while(true) loop, this loop will never end. So either remove that loop, or add an option to abort the process.
Your code should look something like the one below...
**Look out to the bottom, where the user is informed of the values entered and check for the changes made**. This is quite simple...
import java.util.Scanner;
public class correctstack{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String userResponse = null;
do {
int quartersDisplayed = -1;
double startingBalance = -1,
interestRate = -1;
do {
System.out.println("Enter the numbers of quarters you wish to display that is greater than zero and less or equal to 10: ");
userResponse = input.next();
try{
quartersDisplayed = Integer.parseInt(userResponse);
} catch(NumberFormatException e) {
}
if(quartersDisplayed <= 0 || quartersDisplayed > 10) {
System.out.println("Sorry, that value is not valid.");
} else {
break;
}
} while(true);
do {
System.out.println("Enter the starting balance (must be greater than zero): ");
userResponse = input.next();
try {
startingBalance = Double.parseDouble(userResponse);
} catch(NumberFormatException e) {
}
if(startingBalance <= 0) {
System.out.println("Sorry, that value is not valid.");
} else {
break;
}
} while(true);
do {
System.out.println("Enter the interest rate (greater than zero less than twenty percent): ");
userResponse = input.next();
try {
interestRate = Double.parseDouble(userResponse);
} catch(NumberFormatException e) {
}
if(interestRate <= 0 || interestRate > 20){
System.out.println("Sorry, that value is not valid.");
} else {
break;
}
} while(true);
System.out.println("You have entered the following amount of quarters: "+ quartersDisplayed);
System.out.println("You also entered the starting balance of: " + startingBalance);
System.out.println("Finally, you entered the following of interest rate: "+ interestRate);
System.out.println("If this information is not correct, please exit the program and enter the correct information.");
//Here, you give the user the opportunity to continue or re-enter the values. So you go like...
System.out.println("Is this info correct?");
String user_input = input.next();
if("y".equalsIgnoreCase(user_input) || "yes".equalsIgnoreCase(user_input)){
double quarterlyEndingBalance = startingBalance + (startingBalance * interestRate / 100 * .25);
System.out.println("Your ending balance for your quarters is "+ quarterlyEndingBalance);
System.out.println("\n\nDo you want to continue?");
userResponse = input.next();
if("y".equalsIgnoreCase(userResponse) || "yes".equalsIgnoreCase(userResponse))
continue;
else
break;
}
else
continue;
} while(true);
}
}

Java, subtracting double data type

I am trying to do a simple calculation. I can't figure out how to subtract "double admissionPrice" in the last if-else statements.
Its pointing to the subtraction sign giving me this error message:
operator - cannot be applied to java.lang.String,double
Please help. thanks.
import java.text.*;
import java.util.Scanner;
class IMC {
public static void main(String[] args) {
int numEmployees = 0;
double costPerAttendee = 0.00;
int employeeDiscount;
double admissionPrice = 0.00;
Scanner keyboard = new Scanner (System.in);
System.out.print("Enter amount of employees attending: ");
numEmployees = keyboard.nextInt();
System.out.print("Have any employees attended previously? \n For: YES=1 or NO=2"
);
employeeDiscount = keyboard.nextInt();
if (numEmployees == 1) { admissionPrice = 695.00;
} else if (numEmployees == 2 || numEmployees == 3 ||numEmployees == 4) { admissionPrice = 545.00;
} else if (numEmployees >= 5 ||numEmployees >= 6 ||numEmployees >= 7 ||numEmployees >= 8){ admissionPrice = 480.00;
} else if (numEmployees >= 9) { admissionPrice = 395.00;
}
System.out.print("The cost per attendee is: " + admissionPrice );
if (employeeDiscount == 1){
System.out.print("Total price after discount (15%) is : " + admissionPrice - (admissionPrice * 0.15) );
} else if (employeeDiscount == 2) {
System.out.print("No discount. Total price is still: " + admissionPrice);
}
}
}
Place parenthesis around (admissionPrice - (admissionPrice * 0.15) ). Right now, it concatenates admissionPrice on to "Total price after discount (15%) is : " before attempting subtraction.
The + operator in your println() statement is taking precedence and converting admissionPrice to a String.
Put your arithmetic operation in parenthesis.
System.out.print("Total price after discount (15%) is : " + (admissionPrice - (admissionPrice * 0.15)));
^ ^
You need to add () to fix the precedence, else, as the error indicates, you are subtracting, not from admissionPrice but the string that is formed of "To....:" + admissionPrice

Categories

Resources