I am trying to write a ' try and catch ' method in this example, but for some reason I'm getting in error on all of my variables saying; "cannot find symbol". This is happening in all instances of:
subtotal &
customerType. Does anyone know what can be causing this?
import java.text.NumberFormat;
import java.util.Scanner;
import java.util.*;
public class InvoiceApp
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String choice = "y";
while (!choice.equalsIgnoreCase("n"))
{
// get the input from the user
try
{
//System.out.print("Enter customer type (r/c): ");
String customerType = getValidCustomerType(sc);
System.out.print("Enter subtotal: ");
double subtotal = sc.nextDouble();
}
catch (InputMismatchException e)
{
sc.next();
System.out.println("Error! Invalid number. Try again \n");
continue;
}
// get the discount percent
double discountPercent = 0;
if (customerType.equalsIgnoreCase("R"))
{
if (subtotal < 100)
discountPercent = 0;
else if (subtotal >= 100 && subtotal < 250)
discountPercent = .1;
else if (subtotal >= 250)
discountPercent = .2;
}
else if (customerType.equalsIgnoreCase("C"))
{
if (subtotal < 250)
discountPercent = .2;
else
discountPercent = .3;
}
else
{
discountPercent = .1;
}
// calculate the discount amount and total
double discountAmount = subtotal * discountPercent;
double total = subtotal - discountAmount;
// format and display the results
NumberFormat currency = NumberFormat.getCurrencyInstance();
NumberFormat percent = NumberFormat.getPercentInstance();
System.out.println(
"Discount percent: " + percent.format(discountPercent) + "\n" +
"Discount amount: " + currency.format(discountAmount) + "\n" +
"Total: " + currency.format(total) + "\n");
// see if the user wants to continue
System.out.print("Continue? (y/n): ");
choice = sc.next();
System.out.println();
}
}
The problem with your code is the scope of your variables: if you declare something in a try block, it is visible only within that try block; it is not going to be visible outside the try block, including even the catch blocks after it.
In order to get around this problem, declare the variable outside the try block:
String customerType;
double subtotal;
try {
//System.out.print("Enter customer type (r/c): ");
customerType = getValidCustomerType(sc);
System.out.print("Enter subtotal: ");
subtotal = sc.nextDouble();
} catch (InputMismatchException e) {
sc.next();
System.out.println("Error! Invalid number. Try again \n");
continue;
}
You declare subtotal and customerType in try block, so that variable only visible in try block.
Change your code like this will fix the problem:
double subtotal = 0;
String customerType = "";
try
{
//System.out.print("Enter customer type (r/c): ");
String customerType = getValidCustomerType(sc);
System.out.print("Enter subtotal: ");
subtotal = sc.nextDouble();
}
catch (InputMismatchException e)
{
sc.next();
System.out.println("Error! Invalid number. Try again \n");
continue;
}
More : Blocks and Statements
You declared subtotal and customertype inside the brackets of the try {}. That is the only place where they are valid. If you declared them before the try this would have been fine.
private static String getValidCustomerType(Scanner sc)
{
String customerType = "";
boolean isValid = false;
while (isValid == false)
{
System.out.print("Enter customer type (r/c): ");
customerType = sc.next();
if (customerType.equalsIgnoreCase("r") || (customerType.equalsIgnoreCase("c")))
isValid = true;
else
{
System.out.println("Invalid customer type. Try again. \n");
}
sc.nextLine();
}
return customerType;
}
}
Related
Having a problem getting the program to keep running after an error message has occurred. I have tried using different If/Else or While loops to get it to work but none seem to be giving any luck. The current code posted works until you enter something other than y, Y, n, or N. The error message will keep popping up after even if i enter y, Y, n, or N.
import java.text.NumberFormat;
import java.util.InputMismatchException;
import java.util.Scanner;
public class FutureValueApp {
public static void main(String[] args) {
// Avery Owen
System.out.println("Welcome to the Future Value Calculator\n");
Scanner sc = new Scanner(System.in);
String choice = "y";
while (choice.equalsIgnoreCase("y")) {
// get the input from the user
System.out.println("DATA ENTRY");
double monthlyInvestment = getDoubleWithinRange(sc,
"Enter monthly investment: ", 0, 1000);
double interestRate = getDoubleWithinRange(sc,
"Enter yearly interest rate: ", 0, 30);
int years = getIntWithinRange(sc,
"Enter number of years: ", 0, 100);
System.out.println();
// calculate the future value
double monthlyInterestRate = interestRate / 12 / 100;
int months = years * 12;
double futureValue = calculateFutureValue(
monthlyInvestment, monthlyInterestRate, months);
// print the results
System.out.println("FORMATTED RESULTS");
printFormattedResults(monthlyInvestment, interestRate,
years, futureValue);
// see if the user wants to continue
choice = askToContinue(sc);
}
}
public static double getDoubleWithinRange(Scanner sc, String prompt,
double min, double max) {
double d = 0;
boolean isValid = false;
while (isValid == false) {
d = getDouble(sc, prompt);
if (d <= min) {
System.out.println(
"Error! Number must be greater than " + min + ".");
} else if (d >= max) {
System.out.println(
"Error! Number must be less than " + max + ".");
} else {
isValid = true;
}
}
return d;
}
public static double getDouble(Scanner sc, String prompt) {
double d = 0;
boolean isValid = false;
while (isValid == false) {
System.out.print(prompt);
if (sc.hasNextDouble()) {
d = sc.nextDouble();
isValid = true;
} else {
System.out.println("Error! Invalid number. Try again.");
}
sc.nextLine(); // discard any other data entered on the line
}
return d;
}
public static int getIntWithinRange(Scanner sc, String prompt,
int min, int max) {
int i = 0;
boolean isValid = false;
while (isValid == false) {
i = getInt(sc, prompt);
if (i <= min) {
System.out.println(
"Error! Number must be greater than " + min + ".");
} else if (i >= max) {
System.out.println(
"Error! Number must be less than " + max + ".");
} else {
isValid = true;
}
}
return i;
}
public static int getInt(Scanner sc, String prompt) {
int i = 0;
boolean isValid = false;
while (isValid == false) {
System.out.print(prompt);
try {
i = sc.nextInt();
isValid = true;
} catch (InputMismatchException e) {
System.out.println("Error! Enter a whole number. Try again.");
}
sc.nextLine(); // discard any other data entered on the line
}
return i;
}
public static double calculateFutureValue(double monthlyInvestment,
double monthlyInterestRate, int months) {
double futureValue = 0;
for (int i = 1; i <= months; i++) {
futureValue = (futureValue + monthlyInvestment) *
(1 + monthlyInterestRate);
}
return futureValue;
}
public static String askToContinue(Scanner sc) {
System.out.print("Continue? (y/n): ");
String choice = sc.next();
while (!choice.equalsIgnoreCase("n") && !choice.equalsIgnoreCase("y")){
sc.nextLine(); // discard any other data entered on the line
System.out.println("Error! Enter y or n. Try again.");
}
return choice;
}
private static void printFormattedResults(double monthlyInvestment,
double interestRate, int years, double futureValue) {
// get the currency and percent formatters
NumberFormat c = NumberFormat.getCurrencyInstance();
NumberFormat p = NumberFormat.getPercentInstance();
p.setMinimumFractionDigits(1);
// format the result as a single string
String results
= "Monthly investment: " + c.format(monthlyInvestment) + "\n"
+ "Yearly interest rate: " + p.format(interestRate / 100) + "\n"
+ "Number of years: " + years + "\n"
+ "Future value: " + c.format(futureValue) + "\n";
// print the results
System.out.println(results);
}
}
Try this:
public static String askToContinue(Scanner sc) {
System.out.print("Continue? (y/n): ");
String choice = sc.next();
while (!choice.equalsIgnoreCase("n") && !choice.equalsIgnoreCase("y")){
sc.nextLine(); // discard any other data entered on the line
System.out.println("Error! Enter y or n. Try again.");
System.out.print("Continue? (y/n): "); //this was missing
choice = sc.next(); //take the input again
}
return choice;
}
You are getting stuck in a while loop in case of invalid input and not accepting the input again.
I am trying to create a Java program that reads a double value from the user, Printing the difference between these two numbers so that the difference is always positive. I need to display an Error message if anything other than a number is entered. Please help, thank you !!
When I run the program and enter the second double value nothing happens. I have also tried adding try and catch but I get errors saying num1 cannot be resolved to a variable :(
import java.util.Scanner;
public class Positive {
public static void main(String[] args) {
//Reads input
Scanner sc = new Scanner(System.in);
System.out.println ("Please enter a double vaule: ");
double num1 = Math.abs(sc.nextDouble());
System.out.println("Please enter a second double vaule: " );
double num2 = Math.abs(sc.nextDouble());
double total = 0;
double total2 = 0;
if (sc.hasNextDouble()) {
num1 = sc.nextDouble();
if (num1>num2) {
total = ((num1 - num2));
System.out.println("The difference is " + total);
}
if ((num1 < num2)); {
total2 = ((num2 - num1));
System.out.println("The difference is "+ total2);
}
}else {
System.out.println("Wrong vaule entered");
}
}
}
You have the right idea. You just need to remove the semicolon (;) after the last if and properly nest your conditions:
if (sc.hasNextDouble()) {
num1 = sc.nextDouble();
if (num1 > num2) {
total = (num1 - num2);
System.out.println("The difference is " + total);
}
else if (num1 < num2) {
total2 = (num2 - num1);
System.out.println("The difference is "+ total2);
}
} else {
System.out.println("Wrong vaule entered");
}
Try running your code and when you enter your first double, type in something random like "abc". What happens? In your console it should display an error named java.util.InputMismatchException. You can use a try catch block like so:
try {
//tries to get num1 and num2
double num1 = Math.abs(sc.nextDouble());
double num2 = Math.abs(sc.nextDouble());
} catch (java.util.InputMismatchException i){
//will only go here if either num1 or num2 isn't a double
System.out.println("error");
}
Basically, the code will try to get num1 and num2. However if you enter a non-double, it'll "catch" the java.util.InputMismatchException and go to the catchblock
I might've misinterpreted your question, but if you want to find the absolute value of the difference between num1 and num2, all you have to do is:
import java.util.Scanner;
public class test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
try {
System.out.println("Please enter a double value: ");
double num1 = sc.nextDouble();
System.out.println("Please enter a double value: ");
double num2 = sc.nextDouble();
System.out.println("The difference is: " + Math.abs(num1 - num2));
} catch (java.util.InputMismatchException i) {
System.out.println("error");
}
}
}
To show error message until the user enters a double value I used a while loop for each value (num1 and num2).
If user enters a wrong value "Wrong vaule entered, Please enter again: " message will show and waits for the next input sc.next();
If user enters a double value check will be false and exits while loop
import java.util.Scanner;
public class Positive {
public static void main(String[] args) {
// Reads input
Scanner sc = new Scanner(System.in);
System.out.println("Please enter a double vaule: ");
double num1 = 0;
double num2 = 0;
double total = 0;
double total2 = 0;
boolean check = true;
while (check) {
if (sc.hasNextDouble()) {
num1 = Math.abs(sc.nextDouble());
check = false;
} else {
System.out.println("Wrong vaule entered, Please enter again: ");
sc.next();
}
}
check = true; // that's for second control
System.out.println("Please enter a second double vaule: ");
while (check) {
if (sc.hasNextDouble()) {
num2 = Math.abs(sc.nextDouble());
check = false;
} else {
System.out.println("Wrong vaule entered, Please enter again: ");
sc.next();
}
}
if (num1 > num2) {
total = ((num1 - num2));
System.out.println("The difference is " + total);
} else if ((num1 < num2)) {
total2 = ((num2 - num1));
System.out.println("The difference is " + total2);
}
}
}
I'm trying to write a code to convert a letter grade to a numerical value. I have this code but when I run it, I get an error saying java.lang.StringIndexOutOfBoundsException.
What am I doing wrong?
Here is the code:
import java.util.Scanner;
public class Lab6Smalls {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
String grade;
String letter1;
String letter2;
double gpa = 0;
System.out.print("Enter a letter grade: ");
grade = scan.nextLine();
letter1 = grade.substring(0,1);
letter2 = grade.substring(1,2);
if (letter1.equals("A") && letter2.equals("+")){
gpa = 4.3;
} else if (letter1.equals("A")){
gpa = 4.0;
} else if (letter1.equals("B")){
gpa = 3.0;
} else if (letter1.equals("C")){
gpa = 2.0;
} else if (letter1.equals("D")){
gpa = 1.0;
} else if (letter1.equals("F")){
gpa = 0.0;
} else {
System.out.println("The value is invalid.");
}
if (!letter1.equals("F")){
if(letter2.equals("+") && !letter1.equals("A")) gpa += 0.3;
else if(letter2.equals("-")) gpa -= 0.3;
}
System.out.println("The numerical value is " + gpa + ".");
}
}
There is an error because alphabets other than A+ do not have a second value
A+ has two letters
B has one so when you try to find a second, it breaks
C has one so when you try to find a second, it breaks
D has one so when you try to find a second, it breaks
You want to check if the second value exists, before you retrieve it.
Try this
String letter2 = "";
grade = scan.nextLine();
letter1 = grade.substring(0,1);
// Check, if there is a second letter, get it.
if (grade.length() >= 2) {
letter2 = grade.substring(1,2);
}
Before you substring(1, 2) you should make sure the length > 1.
The following is what you want.
import java.util.Scanner;
public class Lab6Smalls {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String grade;
double gpa;
System.out.print("Enter a letter grade: ");
grade = scan.nextLine();
if (null == grade || "".equals(grade)) {
System.out.println("The value is invalid.");
return;
}
switch (grade.substring(0, 1)) {
case "A":
gpa = 4.0;
break;
case "B":
gpa = 3.0;
break;
case "C":
gpa = 2.0;
break;
case "D":
gpa = 1.0;
break;
case "F":
gpa = 0.0;
break;
default:
System.out.println("The value is invalid. : " + grade);
return;
}
if (grade.length() > 1) {
String letter2 = grade.substring(1, 2);
if ("+".equals(letter2)) {
gpa += 0.3;
} else if ("-".equals(letter2)) {
gpa -= 0.3;
}
}
System.out.println("The numerical value is " + gpa + ".");
}
}
I am running into an issue with my Java code and I know where the issue lies, but I can't seem to figure out what I need to do to correct it. Can someone please help? This is the line that is causing the issue and I'm not sure how to fix it. subtotal = sc.nextDouble();
import java.text.NumberFormat;
import java.util.InputMismatchException;
import java.util.Scanner;
public class InvoiceApp
{
private static double subtotal;
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String choice = "y";
while (!choice.equalsIgnoreCase("n"))
{
// get the input from the user
String customerType = getValidCustomerType(sc);
try
{
System.out.print("Enter subtotal: ");
subtotal = sc.nextDouble();
}
catch (InputMismatchException e)
{
sc.next();
System.out.println("Error! Invalid number. Try again. \n");
continue;
}
// get the discount percent
double discountPercent = 0.0;
double subtotal = sc.nextDouble();
if (customerType.equalsIgnoreCase("R"))
{
if (subtotal < 100)
discountPercent = 0;
else if (subtotal >= 100 && subtotal < 250)
discountPercent = .1;
else if (subtotal >= 250)
discountPercent = .2;
}
else if (customerType.equalsIgnoreCase("C"))
{
if (subtotal < 250)
discountPercent = .2;
else
discountPercent = .3;
}
else
{
discountPercent = .1;
}
// calculate the discount amount and total
double discountAmount = subtotal * discountPercent;
double total = subtotal - discountAmount;
// format and display the results
NumberFormat currency = NumberFormat.getCurrencyInstance();
NumberFormat percent = NumberFormat.getPercentInstance();
System.out.println(
"Discount percent: " + percent.format(discountPercent) + "\n" +
"Discount amount: " + currency.format(discountAmount) + "\n" +
"Total: " + currency.format(total) + "\n");
// see if the user wants to continue
System.out.print("Continue? (y/n): ");
choice = sc.next();
System.out.println();
}
}
private static String getValidCustomerType(Scanner sc)
{
String customerType = "";
boolean isValid = false;
while (isValid == false)
{
System.out.print("Enter customer type (r/c): ");
customerType = sc.next();
if (!customerType.equalsIgnoreCase("r") && !customerType.equalsIgnoreCase("c"))
{
System.out.println("Invalid customer type. Try again. \n");
}
else
{
isValid = true;
}
sc.nextLine();
}
return customerType;
}
}
Program does not hang when it executes:
subtotal = sc.nextDouble();
rather it simply waits for a double value input from the console. Input a value, and the rest of your program magic should follow.
The issue is that you have an extra call that scans the subtotal there.
One in the try-catch block
try
{
System.out.print("Enter subtotal: ");
subtotal = sc.nextDouble();
}
and then another one right before you calculate the discountPercent
// get the discount percent
double discountPercent = 0.0;
double subtotal = sc.nextDouble();
This is what's making you enter the amount twice. Just remove the second call and the program should run fine.
This applicaiton validates that the user is entering the correct data. I have about 95% of this done but I can not figure out the Continue? (y/n) part. If you hit anything but y or n (or if you leave the line blank) it is supposed to print an error:So this is what the application is supposed to look like in the console:
Continue? (y/n):
Error! This entry is required. Try again.
Continue? (y/n): x
Error! Entry must be 'y' or 'n'. Try again.
Continue? (y/n): n
Here is my code:
public static void main(String[] args) {
System.out.println("Welcome to the Loan Calculator");
System.out.println();
Scanner sc = new Scanner(System.in);
String choice = "y";
while (choice.equalsIgnoreCase("y"))
{
System.out.println("DATA ENTRY");
double loanAmount = getDoubleWithinRange(sc, "Enter loan amount: ", 0, 1000000);
double interestRate = getDoubleWithinRange(sc, "Enter yearly interest rate: ", 0, 20);
int years = getIntWithinRange(sc, "Enter number of years: ", 0, 100);
double monthlyInterestRate = interestRate/12/100;
int months = years * 12;
double monthlyPayment = calculateMonthlyPayment(loanAmount, monthlyInterestRate, months);
NumberFormat currency = NumberFormat.getCurrencyInstance();
NumberFormat percent = NumberFormat.getPercentInstance();
percent.setMinimumFractionDigits(1);
String results = "Loan amount: \t\t" + currency.format(loanAmount) + "\n"
+ "Yearly interest rate: \t" + percent.format(interestRate/100) + "\n"
+ "Number of years: \t" + years + "\n"
+ "Monthly payment: \t" + currency.format(monthlyPayment) + "\n";
System.out.println();
System.out.println("FORMATTED RESULTS");
System.out.println(results);
String getContinue = getContinueWithinRange(sc, "Continue? (y/n): ", "y", "n");
System.out.print(getContinue);
System.out.println();
}
}
public static double getDoubleWithinRange(Scanner sc, String prompt, double min, double max)
{
double d = 0.0;
boolean isValid = false;
while (isValid == false)
{
d = getDouble(sc, prompt);
if (d <=min) {
System.out.println("Error! Number must be greater than " + min + ".");
}
else if (d >= max) {
System.out.println("Error! Number must be less than " + max + ".");
}
else {
isValid = true;
}
}
return d;
}
public static double getDouble(Scanner sc, String prompt)
{
double d = 0.0;
boolean isValid = false;
while (isValid == false)
{
System.out.print(prompt);
if (sc.hasNextDouble())
{
d = sc.nextDouble();
isValid = true;
}
else
{
System.out.println("Error! Invalid decimal value. Try Again.");
}
sc.nextLine();
}
return d;
}
public static int getIntWithinRange(Scanner sc, String prompt, int min, int max)
{
int i = 0;
boolean isValid = false;
while (isValid == false)
{
i = getInt(sc, prompt);
if (i <= min) {
System.out.println("Error! Number must be greater than " + min + ".");
}
else if (i >= max) {
System.out.println("Error! Number must be less than " + max + ".");
}
else {
isValid = true;
}
}
return i;
}
public static int getInt(Scanner sc, String prompt)
{
int i = 0;
boolean isValid = false;
while (isValid == false)
{
System.out.print(prompt);
if(sc.hasNextInt())
{
i = sc.nextInt();
isValid = true;
}
else
{
System.out.println("Error! Invalid integer value. Try again.");
}
sc.nextLine();
}
return i;
}
public static double calculateMonthlyPayment(double loanAmount, double monthlyInterestRate, double months)
{
double monthlyPayment = 0;
for (int i = 1; i <= months; i++)
{
monthlyPayment = loanAmount * monthlyInterestRate/(1 - 1/Math.pow(1 + monthlyInterestRate, months));
}
return monthlyPayment;
}
System.out.print(getContinue);
System.out.println();
public static String getContinueWithinRange(Scanner sc, String prompt, String yContinue, String nContinue)
{
String i = "";
boolean isValid = false;
while (isValid == false)
{
i = getContinue(sc, prompt);
if (!yContinue.equalsIgnoreCase("") && !nContinue.equalsIgnoreCase("")){
System.out.println("Error! Entry must be 'y' or 'n'. Try again.");
}
else{
isValid = true;
}
}
return i;
}
public static String getContinue(Scanner sc, String prompt)
{
String i = "";
boolean isValid = false;
while(isValid == false)
{
System.out.print(prompt);
if (i.length() > 0)
{
i = sc.nextLine();
isValid = true;
}
else
{
System.out.println("Error! Entry is required. Try again.");
}
sc.nextLine();
}
return i;
}
}
Change the content of the while loop in getContinue() to this:
System.out.print(prompt);
i = sc.nextLine();
if (i.length() > 0)
{
isValid = true;
}
else
{
System.out.println("Error! Entry is required. Try again.");
}
This first prints the prompt, then reads the input into the variable that will be returned, then checks whether the input had length greater than zero.
In getContinueWithinRange(), the condition in the if clause needs to be replaced by
!yContinue.equalsIgnoreCase(i) && !nContinue.equalsIgnoreCase(i)
This will "y" and "n" against the input instead of against "".
Also if you would like to actually continue after reading a "y", you need to do something like this:
if (!yContinue.equalsIgnoreCase(i) && !nContinue.equalsIgnoreCase(i)){
System.out.println("Error! Entry must be 'y' or 'n'. Try again.");
}
else {
isValid = true;
}
The first case catches invalid input, the second ends the loop if the user entered "n", the third tells the user the loop will continue after he entered a "y".
Finally, to make your program do what it's supposed to do, change
String getContinue = getContinueWithinRange(sc, "Continue? (y/n): ", "y", "n");
to
choice = getContinueWithinRange(sc, "Continue? (y/n): ", "y", "n");
in your main method.
I try something for you according to your first submitted code
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
public class Tester4 {
public static String getContinueWithinRange(Scanner sc, String prompt, String yContinue, String nContinue) {
String result = "";
boolean isValid = false;
boolean isStarted = false;
while(!isValid) {
result = getContinue(sc, prompt, isStarted);
isStarted = true;
if(yContinue.equalsIgnoreCase(result) || nContinue.equalsIgnoreCase(result)) {
isValid = true;
} else if(!yContinue.equalsIgnoreCase(result) || !nContinue.equalsIgnoreCase(result)) {
System.out.println("Error! Entry must be 'y' or 'n'. Try again.");
} else {
System.out.println("Error! Entry must be 'y' or 'n'. Try again.");
}
}
return result;
}
public static String getContinue(Scanner sc, String prompt, boolean isStarted) {
String result = "";
boolean isValid = false;
while(!isValid) {
if(result.isEmpty() && !isStarted) {
System.out.print(prompt);
System.out.println("Error! Entry is required. Try again.");
}
result = sc.nextLine();
if(result.length() > 0) {
isValid = true;
}
}
return result;
}
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
String getContinue = getContinueWithinRange(sc, "Continue? (y/n): ", "y", "n");
// to call the method
System.out.print(getContinue);
System.out.println();
}
// InputStream stream = this.getClass().getClassLoader().getResourceAsStream("/images/image.jpg");
// BufferedImage bufferedImage=ImageIO.read(stream);
// ImageIcon icon= new ImageIcon(bufferedImage);
}
import java.util.*;
import java.text.*;
public class LoanPaymentApp {
public static void main(String[] args)
{
System.out.println("Welcome to the Loan Calculator");
System.out.println();
Scanner sc = new Scanner(System.in);
String choice = "y";
while (!choice.equalsIgnoreCase("n"))
{
System.out.println("DATA ENTRY");
double loanAmount = getDoubleWithinRange(sc, "Enter loan amount: ", 0, 1000000);
double interestRate = getDoubleWithinRange(sc, "Enter yearly interest rate: ", 0, 20);
int years = getIntWithinRange(sc, "Enter number of years: ", 0, 100);
double monthlyInterestRate = interestRate/12/100;
int months = years * 12;
double monthlyPayment = calculateMonthlyPayment(loanAmount, monthlyInterestRate, months);
NumberFormat currency = NumberFormat.getCurrencyInstance(Locale.US);
NumberFormat percent = NumberFormat.getPercentInstance();
percent.setMinimumFractionDigits(1);
String results = "Loan amount: \t\t" + currency.format(loanAmount) + "\n"
+ "Yearly interest rate: \t" + percent.format(interestRate/100) + "\n"
+ "Number of years: \t" + years + "\n"
+ "Monthly payment: \t" + currency.format(monthlyPayment) + "\n";
System.out.println();
System.out.println("FORMATTED RESULTS");
System.out.println(results);
System.out.print("Continue? (y/n): ");
choice = sc.nextLine();
while (!choice.equalsIgnoreCase("y") && !choice.equalsIgnoreCase("n"))
{
if (choice.equals(""))
{
System.out.println("Error! This entry is required. Try again.");
System.out.print("Continue? (y/n): ");
}
else
{
System.out.println("Error! Entry must be 'y' or 'n'. Try again.");
System.out.print("Continue? (y/n): ");
}
choice = sc.nextLine();
}
}
}
public static double getDoubleWithinRange(Scanner sc, String prompt, double min, double max)
{
double d = 0.0;
boolean isValid = false;
while (isValid == false)
{
d = getDouble(sc, prompt);
if (d <=min) {
System.out.println("Error! Number must be greater than " + min + ".");
}
else if (d >= max) {
System.out.println("Error! Number must be less than " + max + ".");
}
else {
isValid = true;
}
}
return d;
}
public static double getDouble(Scanner sc, String prompt)
{
double d = 0.0;
boolean isValid = false;
while (isValid == false)
{
System.out.print(prompt);
if (sc.hasNextDouble())
{
d = sc.nextDouble();
isValid = true;
}
else
{
System.out.println("Error! Invalid decimal value. Try Again.");
}
sc.nextLine();
}
return d;
}
public static int getIntWithinRange(Scanner sc, String prompt, int min, int max)
{
int i = 0;
boolean isValid = false;
while (isValid == false)
{
i = getInt(sc, prompt);
if (i <= min) {
System.out.println("Error! Number must be greater than " + min + ".");
}
else if (i >= max) {
System.out.println("Error! Number must be less than " + max + ".");
}
else {
isValid = true;
}
}
return i;
}
public static int getInt(Scanner sc, String prompt)
{
int i = 0;
boolean isValid = false;
while (isValid == false)
{
System.out.print(prompt);
if(sc.hasNextInt())
{
i = sc.nextInt();
isValid = true;
}
else
{
System.out.println("Error! Invalid integer value. Try again.");
}
sc.nextLine();
}
return i;
}
public static double calculateMonthlyPayment(double loanAmount, double monthlyInterestRate, double months)
{
double monthlyPayment = 0;
for (int i = 1; i <= months; i++)
{
monthlyPayment = loanAmount * monthlyInterestRate/(1 - 1/Math.pow(1 + monthlyInterestRate, months));
}
return monthlyPayment;
}
}