So we have to make a mortgage calculation project where we have to ask the user to calculate again and now we have to make it so it prints out a error message every time the user enters a string value for any of the inputs. I thought I did it right but something strange happens every time I run it and I can't figure out why and I know it's something wrong with the Try-Catch blocks.
Here are my outputs: http://imgur.com/cbvwM5v
As you can see the third time i run the program I enter a "two" as the second input and it still did the calculations. Then, the third time I tried it, I entered a negative number then a "two" and everything worked the way I wanted it to. Then, the last time I ran it I put a positive number for the first input and it still did the calculations, anything you guys see that might be doing this? Also, I think I may have used the wrong exception, I'm not uite sure what it means, I just guessed. am I supposed to user NumberFormatException and there is also a line under nfe saying that the value is not being used.
Here's my code:
package MortgageCalculation2c;
import java.text.NumberFormat;
import java.util.Scanner;
/**
*
* #author Akira
*/
public class MortgageCalculation2c {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
double loanAmount = 0;
double interestRate = 0;
double numberYears = 0;
double months;
double monthlyPayment;
double numerator;
double denominator;
double formula;
boolean userInput = true;
String answer = ("y");
while (userInput) {
try {
loanAmount = 0;
interestRate = 0;
numberYears = 0;
//prompt user for the loan amount
System.out.print("Enter the loan amount: ");
loanAmount = Double.parseDouble(in.nextLine());
//prompt the user for the interest rate
System.out.print("Enter the rate: ");
interestRate = Double.parseDouble(in.nextLine());
//prompt the user for thenumber of years
System.out.print("Enter the number of years: ");
numberYears = Double.parseDouble(in.nextLine());
} catch (NumberFormatException nfe) {
System.out.println("You must enter positive numerical data!");
}
//if the user enters a negative number print out a error message, if not, continue calculations
if ((loanAmount <= 0) || (interestRate <= 0) || (numberYears <= 0)) {
System.out.println("ALL NUMERICAL VALUES MUST BE POSITIVE!");
} else {
//convert the interest rate
interestRate = interestRate / 100 / 12;
//the number of years must be converted to months
months = numberYears * 12;
//numerator of the monthly payment formula
numerator = (Math.pow(1 + interestRate, months));
//denominator of the monthly payment formula
denominator = ((numerator)-1);
//the formula equals the numerator divided by the denominator
formula = ( numerator / denominator );
//monthly payment calculation
monthlyPayment = (interestRate * loanAmount * formula);
//sytem output
NumberFormat defaultFormat = NumberFormat.getCurrencyInstance();
System.out.println("The monthly payment is: " + defaultFormat.format(monthlyPayment));
}
//prompt the user if they would like to calculate the program again.
System.out.println("Would you like to calculate again (y/n) : ");
//if the user enters "y" the program will run again and if the user enters anything else it ends
answer = in.nextLine();
answer = answer.toLowerCase();
if ( answer.equals("y")){
userInput = true; //tests the program if it needs to run again
}else{
break; //ends the program
}
}
}
}
Is there anything that you guys can see that might be the problem?
It seems you need continue in your catch block, so the program flow goes back to the loop.
...
} catch (NumberFormatException nfe) {
System.out.println("You must enter positive numerical data!");
continue; // <---------- here
}
...
If this is not a specific exercise in try-catch construct, it be would be better to use Scanner's method hasNextDouble() for validatiing and nextDouble for reading and converting the numbers.
It will look something like this:
//prompt user for the loan amount
loanAmount = enterPositiveDouble("Enter the loan amount: ")
//prompt the user for the interest rate
interestRate = enterPositiveDouble("Enter the rate: ");
//prompt the user for the number of years
numberYears = enterPositiveDouble("Enter the number of years: ");
and you will have a special static method enterPositiveDouble like following:
static void enterPositiveDouble(String prompt) {
Scanner in = new Scanner(System.in);
boolean ok = true;
double result = -1;
do {
System.out.print(prompt);
ok = (in.HasNextDouble() && (result = in.NextDouble()) > 0)
if ! ok
System.out.println("You must enter positive numerical data!");
} while (!ok);
}
The above is not an optimal code but just the illustration of a possible solution.
Related
I'm new to java and I have a question about an assignment I have. I've written a bunch of methods that are different formulas, like the duration of a storm. The assignment asks me to write two helper methods to get input from the user. One of them is called get_S_Input() and I was able to implement it correctly I think. But the one I'm stuck on is this other helper method called get_2_Invals(). It wants me to prompt the user with my parameter, and read in 2 double values. It wants me to record the values in a class global array of doubles and then exit the method, but I don't know how to do this. I want to put it in the else statement in the method below. Here is my code so far...
import java.lang.Math;
import java.util.Scanner;
public class FunFormulas {
public void sd(){
double durationOfStorm = Math.sqrt(((Math.pow(get_S_Input("Enter the diameter of storm in miles:"), 3) / 216)));
if (durationOfStorm > 0)
System.out.println("The storm will last: " + durationOfStorm);
}
public void sl(){
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the number of seconds since the lightning strike:");
double secondsSinceLightning = Double.valueOf(scanner.nextLine());
double distanceFromLightning = (1100 * secondsSinceLightning);
System.out.println(distanceFromLightning);
}
public void si(){
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the edge of cube in inches:");
double edgeOfCubeInInches = Double.valueOf(scanner.nextLine());
if (edgeOfCubeInInches < 0){
System.out.println("ERROR: please enter a non-negative number!!!");
}
double weightOfCube = (0.33 * (Math.pow(edgeOfCubeInInches, 3)));
System.out.println(weightOfCube);
}
public void dt(){
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the time in hours:");
double timeInHours = Double.valueOf(scanner.nextLine());
if (timeInHours < 0){
System.out.println("ERROR: please enter a non-negative number!!!");
}
System.out.println("Enter the rate of speed in mph:");
double rateOfSpeed = Double.valueOf(scanner.nextLine());
if (rateOfSpeed < 0){
System.out.println("ERROR: please enter a non-negative number!!!");
}
double distanceTravelled = (rateOfSpeed * timeInHours);
System.out.println(distanceTravelled);
}
public void sa(){
Scanner scanner = new Scanner(System.in);
System.out.println("Enter your weight in pounds:");
double weight = Double.valueOf(scanner.nextLine());
weight = weight * 0.4536;
System.out.println("Enter your height in inches:");
double height = Double.valueOf(scanner.nextLine());
height = height * 2.54;
double BSA = ((Math.sqrt(weight * height)) / 60);
System.out.println(BSA);
}
public double get_S_Input(String promptStr){
//Scanner helper method
System.out.println(promptStr);
Scanner scanner = new Scanner(System.in);
double value = Double.valueOf(scanner.nextLine());
if (value < 0 ){
System.out.println("ERROR: please enter a non-negative number!!!");
}
return value;
}
public void get_2_Invals(String promptStr){
/*Prompt the user with the promptStr passed in as a parameter
ii. Read in the first double precision value entered by the user with the Scanner
iii. Read in the second double precision value entered by the user with the Scanner
iv. Check to make sure the values entered by the user are non-negative
a. If either number entered by the user is negative, the method should print out an
error message, and return to step i. above.
b. If the number is non-negative (that is greater than or equal to zero) the method
should record the numbers obtained from the user in a class-global array of
doubles and exit.*/
System.out.println(promptStr);
Scanner scanner = new Scanner(System.in);
double firstValue = scanner.nextInt();
double secondValue = scanner.nextInt();
if (firstValue < 0 || secondValue < 0)
System.out.println("ERROR: please enter non-negative number!");
else
}
public static void main(String [] args){
FunFormulas fun = new FunFormulas();
fun.sd();
}
}
I am sure this is a dumb question but i have been at it for quite a bit.. I am trying to create a java program that calculates compound interest based off a user input of years and amount of money. But i keep getting an error that a void method cannot return a value. So i switch the method to a double because thats what will be returned, but than it tells me that a double method must return a double. Even tho im returning a double in the loop... Please help
import java.text.DecimalFormat;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
DecimalFormat df = new DecimalFormat("#.00");
**strong text**
Scanner reader = new Scanner(System.in); //creates scanner
System.out.println("Enter number of years until retirement: "); //asks user to input number of years until retirement
int Years = reader.nextInt();
if (Years <= 0) {
System.out.println("Please enter a valid number"); //if the number of years was invalid, exits the program and asks to enter a valid number
System.exit(0);
}
System.out.println("Enter amount of money able to save annually: "); //asks user how much money they can input
double MoneySaved = reader.nextInt();
reader.close(); //closes scanner
for(int i=0; i < Years; i++)
{
Total = MoneySaved * 1.05;
return Total;
}
System.out.println("You will have $" + df.format(TotalAmount) + " saved up by retirement");
}
}
change your for to this
Double total = 0;
for(int i=0; i < Years; i++) {
total += MoneySaved;
total *= 1.05;
}
System.out.println(total);
Make the method a double and change
double MoneySaved = reader.nextInt();
to
double MoneySaved = reader.nextDouble();
Also I do not see your declaration of 'Total'; make sure that is declared as a double.
First, main Java method must be void and void methods cannot return a value(even compiler tells you that), although you can use a return statement to break execution of the method and return to calling method.
So answering your question, you have to create method that returns double and then just prints it in your main method or do not return anything and just replace
return Total;
with
System.out.println("You will have $" + df.format(Total) + " saved up by retirement");
PS: it looks like you are new to Java, so for a start read some content about Java, for example offical oracle tutorial
I am trying to figure out how to validate the input of a user. I want the user to enter a double but if the user enters a string I want the question repeated until a double is entered. Iv'e searched but I couldn't find anything. Below is my code so far any help is appreciated. I have to use a do while loop I am stuck on what to put in the while loop to make sure the input is a double and not a string.
public class FarenheitToCelsius {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
double fahrenheit, celsius;
Scanner in = new Scanner(System.in);
do{
System.out.printf("Enter a fahrenheit degree: ");
fahrenheit = in.nextDouble();
}
while();
celsius = ((fahrenheit - 32)*5)/9;
System.out.println("Celsius value of Fahrenheit value " + fahrenheit + " is " + celsius);
One trick you can use here is to read the entire user input as a string, which would allow any type of input (string, double, or anything else). Then, use Double#parseDouble() to try to convert that input to a bona-fide double value. Should an exception occur, allow the loop to continue, otherwise, end the loop and continue with the rest of your program.
Scanner in = new Scanner(System.in);
boolean isValid;
do {
System.out.printf("Enter a fahrenheit degree: ");
isValid = false;
String input = in.nextLine();
try {
fahrenheit = Double.parseDouble(input);
isValid = true;
}
catch (Exception e) {
// do something
}
} while(!isValid);
celsius = ((fahrenheit - 32) * 5) / 9;
I am new to java and I can't figure out what is wrong with my code. After the user inputs annual income and # of exemptions, the code stops working. There are no error messages on my console either. Please help me.
The program:
My code:
import java.util.Scanner;
public class TaxRate {
public static void main (String[] args)
{
Scanner sc = new Scanner(System.in);
// before asking the user for input
final double TAX_RATE = 0.12;
System.out.println ("Type in your name:");
String name;
name = sc.next();
System.out.println (name + ", type in your annual income and number of exemptions, separated by spaces:");
double income, exempt;
income = sc.nextDouble();
exempt = sc.nextDouble();
sc.close();
} // main method
} // lab class
Where you have
double num2 = 2000 * exempt;
num2 = sc.nextDouble();
you are calculating num2 and then waiting for the user to enter it.
Where you have
double adjustedGrossIncome = income - num2;
adjustedGrossIncome = sc.nextDouble();
you are calculating adjustedGrossIncome and then waiting for the user to enter it.
Where you have
double tax = TAX_RATE * adjustedGrossIncome;
tax = sc.nextDouble();
you are calculating tax and then waiting for the user to enter it.
If you take out the nextDouble() lines in those three cases, your program will run along instead of stopping for user input.
Your problem is that you ask for an input for tax that you already calculated, since that would be a useless line of code.
I'm not quiet sure how to go about doing the calculations for this. I have everything down right up until i'm trying to actually get the investment amount. I know what i have right now is wrong, but google isn't being super helpful for me, and my book just does not have what i need in order to complete this darn thing.
Here what i have right now
import java.util.Scanner;
class InvestmentCalculator {
public static void main(String[] args) {
// create a scanner object
Scanner input = new Scanner(System.in);
// Prompt user to enter investment amount
Scanner amount = new Scanner(System.in);
System.out.println("Enter Investment Amount");
while (!amount.hasNextDouble()) {
System.out.println("Only Integers");
amount.next();
}
//Promt user to enter interest rate
Scanner interest = new Scanner(System.in);
System.out.println("Enter Interest Percentage in decimals");
while (!interest.hasNextDouble()) {
System.out.println("Just like before, just numbers");
interest.next();
}
//Prompt user to enter number of years
Scanner years = new Scanner(System.in);
System.out.println("Enter Number of Years");
while (!years.hasNextDouble()) {
System.out.println("Now you are just being silly. Only Numbers allowed");
years.next();
}
//Compute Investment Amount
double future = amount * Math.pow((1 + interest), (years * 12));
//Display Results
System.out.println("Your future investment amount is " + future);
}
}
Any assistance would be very very helpful!
First of all amount, interest and years are Scanners, they are not numbers. The Scanner could contain any number of different types of content so it's impossible for something like Math.pow to know what it should do with them
You need to assign the values you read from the user to some variables.
I'd start by using a single Scanner, say called kb...
Scanner kb = new Scanner(System.in);
Then use this whenever you want to get a value from the user...
You input loops seem wrong to me, I'm not particularly experienced with the Scanner, so there is probably a better way to achieve this, but...
int invest = -1; // amount
double rate = -1; // percentage
int period = -1; // period
do {
System.out.println("Only Integers");
String text = kb.nextLine();
try {
invest = Integer.parseInt(text);
} catch (NumberFormatException exp) {
System.out.println("!! " + text + " is not an integer");
}
} while (invest == -1);
System.out.println(invest);
Once you have all the information you need, make your calculations with these primitive types...
double future = invest * Math.pow((1 + rate), (period * 12));
You don't have to use 4 different scanners for this because you are reading from the same stream.... Your code should be something like this -
import java.util.Scanner;
class InvestmentCalculator {
public static void main(String[] args) {
double amount=0;
int interest=0;
double years=0;
// create a scanner object
Scanner input = new Scanner(System.in);
// Prompt user to enter investment amount
Scanner amount = new Scanner(System.in);
System.out.println("Enter Investment Amount");
while (!input.hasNextDouble()) { // you say you only want integers and are
// reading double values??
System.out.println("Only Integers");
amount = input.nextDouble();
}
//Promt user to enter interest rate
System.out.println("Enter Interest Percentage in decimals");
while (!input.hasNextInt()) {
System.out.println("Just like before, just numbers");
interest= input.nextInt();
}
//Prompt user to enter number of years
System.out.println("Enter Number of Years");
while (!input.hasNextDouble()) {
System.out.println("Now you are just being silly. Only Numbers allowed");
years=input.nextDouble();
}
//Compute Investment Amount
double future = amount * Math.pow((1 + interest), (years * 12));
//Display Results
System.out.println("Your future investment amount is " + future);
}
}