I am writing a loan calculate with data validation. My maximum loan amount is 1,000,000 and I am using the method below to validate. When I enter 1,000,000 into the program it comes back with my error method. I thought (d >= max) would allow me to go up to and including my max. Can anyone see a problem with this method or is it possible I should be looking elsewhere in my code for a problem.
Any help is appreciated.
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;
//Get input from user
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);
you are saying if the amount is greater than or equal to one million cause an error. you want to say if it is greater than show an error
Use else if (d>max), since you want up to 1,000,000 (and 1,000,000 can be included).
Related
I am trying to prompt the user if the information they entered is correct and the program just proceeds anyway instead of re-prompting the user. I think i need to change how I loop this do some type of do-while loop, but I don't quite know what to do.
{
//Here we will set up our method of data entry and decimal format
Scanner keyboard = new Scanner(System.in);
DecimalFormat eNotation1 = new DecimalFormat("00.00");
//Let's introduce our program to the user
System.out.println("Hi, This is a program to calculate quarterly interest growth");
//Here we will prompt the user to enter the amount of quarters
System.out.println("How many quarters would you like to display? Please pick a number greater than zero and less than or equal to 10");
int quarterNumber = keyboard.nextInt();
if (quarterNumber > 10 || quarterNumber < 0)
{
System.out.println("You entered a number outside of the boundrys. Please run the program again and choose a number between 0 and 10 (number can include 10)");
System.exit(0);
}
//Here we will prompt the user for the starting balance.
System.out.println("What is the starting balance of this account?");
double startingBalance = keyboard.nextDouble();
//Here we will prompt the user for the interest rate
System.out.println("What is the interest rate (in percent) in your area? Please pick a number from 1 - 20.");
double interestRate = keyboard.nextDouble();
if (interestRate < 1 || interestRate > 20)
{
System.out.println("You entered a number outside of the boundrys. Please run the program again and choose a number between 1 and 20 (can include 1 and 20)");
System.exit(0);
}
//Here we will double check with the user that the info is correct.
System.out.println("The amount of quarters you would like displayed is " + quarterNumber);
System.out.println("The starting balance you would like to work with is " + startingBalance);
System.out.println("The interest rate in your area is " + interestRate);
System.out.println("Is this information correct?");
keyboard.nextLine();
String answer = keyboard.nextLine();
System.out.println("");
//We will have them enter the information again if the answer is no or No
if (answer == "no" || answer == "No")
{
//Here we will prompt the user to enter the amount of quarters
System.out.println("How many quarters would you like to display? Please pick a number greater than zero and less than or equal to 10");
keyboard.nextInt();
quarterNumber = keyboard.nextInt();
//Here we will prompt the user for the starting balance.
System.out.println("What is the starting balance of this account?");
keyboard.nextDouble();
startingBalance = keyboard.nextDouble();
//Here we will prompt the user for the interest rate
System.out.println("What is the interest rate (in percent) in your area? Please pick a number from 1 - 20.");
keyboard.nextDouble();
interestRate = keyboard.nextDouble();
}
//Next we will proceed with the calculation if the information is indeed correct
double endingBalance = startingBalance + (startingBalance * (interestRate / 100 * .25));
double interestEarned = endingBalance - startingBalance;
//Now we will output the information
for (int qn = 1; qn < (quarterNumber + 1); qn++ , startingBalance = startingBalance + interestEarned , endingBalance =startingBalance + (startingBalance * (interestRate / 100 * .25)), interestEarned = endingBalance - startingBalance )
{
System.out.println("Quarter Number Starting Balance Interest Earned Ending Balance ");
System.out.println(qn + " " + eNotation1.format(startingBalance) + " " + eNotation1.format(interestEarned) + " " + eNotation1.format(endingBalance) + " ");
}
}
}
I probably figured what your problem is.
Example code snippet: (Note I am doing without an actual java editor so just handle any missing syntax
//Here we will prompt the user to enter the amount of quarters
int quarters = 0;
System.out.println("How many quarters would you like to display? Please pick a number greater than zero and less than or equal to 10");
do
{
quarters = keyboard.nextInt();
if (quarters <= 0 || quarters >= 10)
{
System.out.println("You entered a number outside of the boundrys. Please Type a number greater than 0 and less than equal to 10 again)");
}
}
while (quarters <= 0 || quarters >= 10)
The idea is for a recursive prompt. The application first prompts the user to type in the result, and then you handle the amount of So you have to handle the prompt within the do-while loop. Assuming you don't want to repeat the same old text, you can do what I did (which is much cleaner in my opinion).
EDIT: Assuming you want to handle the entire repeating of the application. place everything for the declaration of variables into a method (or better various methods for cleaner handling, and handle something like this.
int quarters;
double balance;
//TODO : Add all other required variables
string verification;
do
{
quarters = getNumberOfQuartersFromUser();
balance = getStartingBalance();
... //TODO : all the other methods
//verification
System.out.println("Is this accepted?");
verification = keyboard.nextString();
//Handle verfication if it is no or No
if (verification == null || verification == "No" || verification == "no")
{
System.out.println("Starting from the beginning again");
}
}
while (verification == null || verification == "No" || verification == "no")
//out of loop, so handle calculation.
...
and a method snippet
private int getNumberOfQuartersFromUser()
{
int quarters = 0;
System.out.println("How many quarters would you like to display? Please pick a number greater than zero and less than or equal to 10");
do
{
quarters = keyboard.nextInt();
if (quarters <= 0 || quarters >= 10)
{
System.out.println("You entered a number outside of the boundrys. Please Type a number greater than 0 and less than equal to 10 again)");
}
}
while (quarters <= 0 || quarters >= 10)
return quarters;
}
I think you should enclose your codes to Else statement to avoid proceeding unintentionally. Remember that else limits the run-time of your codes and put it on a more specified path for you.
{
//Here we will set up our method of data entry and decimal format
Scanner keyboard = new Scanner(System.in);
DecimalFormat eNotation1 = new DecimalFormat("00.00");
//Let's introduce our program to the user
System.out.println("Hi, This is a program to calculate quarterly interest growth");
//Here we will prompt the user to enter the amount of quarters
System.out.println("How many quarters would you like to display? Please pick a number greater than zero and less than or equal to 10");
int quarterNumber = keyboard.nextInt();
//Here you had started your condition I'll try to make it nested if statement
if (quarterNumber > 10 || quarterNumber < 0)
//if the condition is true perform this
{
System.out.println("You entered a number outside of the boundrys. Please run the program again and choose a number between 0 and 10 (number can include 10)");
System.exit(0);
}
else{
//if false conditions inside else statement should be performed
//Here we will prompt the user for the starting balance.
System.out.println("What is the starting balance of this account?");
double startingBalance = keyboard.nextDouble();
//Here we will prompt the user for the interest rate
System.out.println("What is the interest rate (in percent) in your area? Please pick a number from 1 - 20.");
double interestRate = keyboard.nextDouble();
//you could put another if statement inside if statement which is known as nested if statement.
if (interestRate < 1 || interestRate > 20)
{
System.out.println("You entered a number outside of the boundrys. Please run the program again and choose a number between 1 and 20 (can include 1 and 20)");
System.exit(0);
}
else{
//like before you should enclose this to else to avoid confusion
//Here we will double check with the user that the info is correct.
System.out.println("The amount of quarters you would like displayed is " + quarterNumber);
System.out.println("The starting balance you would like to work with is " + startingBalance);
System.out.println("The interest rate in your area is " + interestRate);
System.out.println("Is this information correct?");
keyboard.nextLine();
String answer = keyboard.nextLine();
System.out.println("");
//We will have them enter the information again if the answer is no or No
if (answer == "no" || answer == "No")
{
//Here we will prompt the user to enter the amount of quarters
System.out.println("How many quarters would you like to display? Please pick a number greater than zero and less than or equal to 10");
keyboard.nextInt();
quarterNumber = keyboard.nextInt();
//Here we will prompt the user for the starting balance.
System.out.println("What is the starting balance of this account?");
keyboard.nextDouble();
startingBalance = keyboard.nextDouble();
//Here we will prompt the user for the interest rate
System.out.println("What is the interest rate (in percent) in your area? Please pick a number from 1 - 20.");
keyboard.nextDouble();
interestRate = keyboard.nextDouble();
}
//Next we will proceed with the calculation if the information is indeed correct
double endingBalance = startingBalance + (startingBalance * (interestRate / 100 * .25));
double interestEarned = endingBalance - startingBalance;
//Now we will output the information
for (int qn = 1; qn < (quarterNumber + 1); qn++ , startingBalance = startingBalance + interestEarned , endingBalance =startingBalance + (startingBalance * (interestRate / 100 * .25)), interestEarned = endingBalance - startingBalance )
{
System.out.println("Quarter Number Starting Balance Interest Earned Ending Balance ");
System.out.println(qn + " " + eNotation1.format(startingBalance) + " " + eNotation1.format(interestEarned) + " " + eNotation1.format(endingBalance) + " ");
}
}
}
}
Remember that learning nested if statement is essential to a programmer. without this, all your conditions will literally proceed.
I am trying to create a while loop where the user has a total of three tries to enter a valid number. I'm not understanding how the system recognizes that 3 invalid attempts have been made before displaying the message.
Classes, variables, and scanner objects are made. After the three attempts, I want to say "No more tries". I already have the program written to use the user's input for quantity if its valid. This is just if they input three invalid attempts.
Updated code:
int quantity = 0;
// Get user's desired amount of lemonade cups
System.out.print("Hello " + name + ". How many cups of lemonade can I get you? ");
quantity = keyboard.nextInt(); // Store amount of cups wanted
int attempts = 0;
int maxAttempts = 3;
double subTotal = quantity * lemonadeCost;
double totalTax = subTotal * 0.08;
double totalPrice = subTotal + totalTax;
while (attempts < maxAttempts) {
if (quantity < 1 || quantity >= 20) {
System.out.println("That is an invalid amount, please try again");
quantity = keyboard.nextInt(); }
else {
System.out.println("Subtotal: " + defaultFormat.format(subTotal));
System.out.println("Tax: " + defaultFormat.format(totalTax));
System.out.println("Total: " + defaultFormat.format(totalPrice));
}
attempts++;
if (attempts >= 3) {
System.out.print ("No lemonade for you");
break;
}
// Ask for user's payment method
Scanner method = new Scanner(System.in);
System.out.println("How would you like to pay? Enter 'm' for money, 'c' for credit or 'g' for gold. ");
String payment = method.nextLine();
dxdy is correct about the braces required for making the while() loop function.
Once the while loop has ended (either quantity is between 1 and 20, or attempts > maxAttempts), you just need to have an if statement like the following:
if (attempts > maxAttempts) {
System.out.println("No more tries);
return -1; // or something else to break out of your code
}
and then continue on with the rest of your code working with the quantity variable.
You seem to be missing the opening and closing brackets for the loop. As it is, your code reads
while (quantity < 1 || quantity >= 20 && attempts <= maxAttempts)
System.out.println("That is an invalid amount, please try again");
// these below are not part of the loop
quantity = keyboard.nextInt();
attempts++;
Instead you should do
while (quantity < 1 || quantity >= 20 && attempts <= maxAttempts){
System.out.println("That is an invalid amount, please try again");
quantity = keyboard.nextInt();
attempts++;
}
try this code:
//start with 1 since the user will attempt it at least one time.
int attempts = 1;
int maxAttempts = 3;
int quantity=0;
Scanner keyboard = new Scanner(System.in);
//LESS THAN OR EQUAL TO 3...
while(attempts<=maxAttempts){
System.out.print("Enter amount: ");
quantity = keyboard.nextInt();
//check if valid
if(quantity < 1 || quantity >= 20){
//check if it's 1st and 2nd trial.
if(attempts<maxAttempts){
System.out.println("That is an invalid amount, please try again");
}else{
//third trial and still invalid
System.out.print("No more tries");
}
}else{
//user entered a valid amount so let's break the loops.
System.out.println("The amount is valid. Value of amount: "+ quantity);
break;
}
//increment attempts
attempts++;
}
//never forget to close the scanner
keyboard.close();
}
}
Though I could have turned this into methods if it's allowed
EDIT: As you updated the question, so it was necessary to update the answer too. Here it is what you actually want.
public static void main(String[] args) {
// Get user's desired amount of lemonade cups
String name = "Jimmy Nguyen";
Scanner keyboard = new Scanner(System.in);
int quantity;// Store amount of cups wanted
int lemonadeCost = 4; // Suppose
int attempts = 0;
int maxAttempts = 3;
System.out.print("Hello " + name + ". How many cups of lemonade can I get you? ");
while (attempts < maxAttempts) {
quantity = keyboard.nextInt();
if (quantity < 1 || quantity >= 20) {
System.out.println("That is an invalid amount, please try again\n");
++attempts;
} else {
double subTotal = quantity * lemonadeCost;
double totalTax = subTotal * 0.08;
double totalPrice = subTotal + totalTax;
System.out.println("Subtotal: " + subTotal);
System.out.println("Tax: " + totalTax);
System.out.println("Total: " + totalPrice);
// Ask for user's payment method
System.out.println("How would you like to pay? Enter 'm' for money, 'c' for credit or 'g' for gold. ");
keyboard.nextLine();
String payment = keyboard.nextLine();
break;
}
if (attempts >= 3) {
System.out.print("No lemonade for you");
break;
}
}
}
I'm getting some errors saying that it cannot find symbol
import javax.swing.JOptionPane;
public class ShippingSales
{
public static void main (String [] args)
{
int weight, miles;
String temp;
double shippingcharge, rate;
shippingcharge = miles * rate;
miles = 500;
temp = JOptionPane.showInputDialog("Enter the weight of the package");
weight = Interger.parseInt(temp);
if (weight <= 2)
{
JOptionPane.showMessageDialog(null, "Your total amount is " + shipppingcharge);
rate = 1.10;
}
if (weight > 2 && weight<= 6 )
{
JOptionPane.showMessageDialog(null, "Your total amount is " + shipppingcharge);
rate = 2.20;
}
if (weight > 6 && weight<= 10)
{
JOptionPane.showMessageDialog(null, "Your total amount is " + shipppingcharge);
rate = 3.70;
}
if (weight > 10)
{
JOptionPane.showMessageDialog(null, "Your total amount is " + shipppingcharge);
rate = 3.80;
}
}
}
Interger.parseInt(temp);
Anything wrong with this line you can see at second glance?
Hint: Spelling.
Also, you misspelled "shipping charge" in a variable reference multiple times.
Well you used three "p"s in all of the showMessageDialogs but the variable is called shippingcharge
And you spelled Integer wrong, you used Interger
import java.util.Scanner;
public class Teacher{
public static void main(String [] args){
Scanner reader = new Scanner(System.in);
double salary;
double pi;
int year;
int years = 1;
double predict;
double predict2 = 0;
double sum = 0;
System.out.print("What is your starting salary: ");
salary = reader.nextDouble();
System.out.print("What is your precentage increase: ");
pi = reader.nextDouble();
System.out.print("How many years are you working: ");
year = reader.nextInt();
if (salary <= 0){
System.out.print("The salary must be positive.");
}
if (pi <= 0){
System.out.print("The percentage increase must be positive.");
}
if (year < 0){
System.out.print("The years must be positive.");
}
while (year > years) {
predict = salary * (pi/100);
System.out.println(years + ". " + predict);
years++;
if (years == year){
break;
}
}
}
}
I am having trouble trying to print out a loop. Every time I run the program, this segment only prints out one number and doesn't print out the rest.
per #ajb wouldn't you want to do something like this in your loop? This will print your salary increase every year, and also add that to the salary for the next iteration
Per your new comment
Every time their is an output, I would like it to display the year and
their salary.
while (year > years) {
//predict = salary * (pi/100); commented this because it is not necessary anymore.
salary += salary * (pi/100);
System.out.println(years + ". " + salary); // replaced predict with salary, to show their salary and not just their predicted raise.
years++;
// This block of code will never be hit, therefore it is not needed.
//if (years == year){
// break;
//}
}
Revised could be something like this.
while (year > years) {
salary += salary * (pi/100);
System.out.println(years + ". " + salary);
years++;
}
what i need 2 do is prompt the user for principal, interest rate, and term. the user then chooses months or years.
i have no idea on how to compute the compounded monthly interest rate using a for loop. i've looked at formulas online but whenever i try to translate it into java code i fail miserably.
i know i'd need to divide by 12, but during the loop my interest and principal amount keeps getting smaller until 0. can anyone help? ty
public Calculator()
{
Scanner input = new Scanner(System.in);
boolean error = false;
while (!error){
System.out.print("Please input the following: principal, interest rate, term >> ");
double principal = input.nextDouble();
double interest_rate = input.nextDouble();
int term = input.nextInt();
String MonthOrYear = input.next();
int termInMonths = term * 12;
char dollar_sym = 36;
if (interest_rate <= 0 || term <= 0 || principal <= 0)
{
System.out.println("The term, interest rate and principal must be greater than zero");
continue;
}
if (!MonthOrYear.equals("month") && (!MonthOrYear.equals("year")&&
(!MonthOrYear.equals("Month")&& (!MonthOrYear.equals("Year") && (!MonthOrYear.equals("years")
&& (!MonthOrYear.equals("months") && (!MonthOrYear.equals("Years") &&
(!MonthOrYear.equals("Months")))))))))
{
System.out.println("Please input either month or year after term");
continue;
}
System.out.println("Month: " + " Interest: " + "Principal: ");
if (MonthOrYear.equals("month") || (MonthOrYear.equals("Months") || (MonthOrYear.equals("Month")
|| (MonthOrYear.equals("months")))))
{
for (int month = 1; month <= term; month++)
{
double interest = principal * interest_rate / 100;
principal = principal + interest;
System.out.printf("%4d %c%5.2f %c%5.2f\n", month, dollar_sym, interest, dollar_sym, principal );
}
}
else if (MonthOrYear.equals("year") || (MonthOrYear.equals("Years") || (MonthOrYear.equals("Year")
|| (MonthOrYear.equals("years")))))
{
for (int month = 1; termInMonths >= month; month++)
{
double interest = principal * interest_rate / 100;
principal = principal + interest;
System.out.printf("%4d %c%5.2f %c%5.2f\n", month, dollar_sym, interest, dollar_sym, principal );
}
}
break;