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;
Related
is it possible in Java to check if a certain input is between a certain range and also an integer?
I have written the following code:
public void getBetAmountFromUser() {
//Get Amount of Bet
int x = 0;
System.out.println("Your current pot is: " + potAmount);
System.out.println("Enter your bet amount: ");
x = input.nextInt();
//Error message if bet is larger than pot and less than 0
while (x>potAmount || x<0 || !(input.hasNextInt())){
System.out.println("Error - cannot bet less than 0 or more than " + potAmount + "..Enter your bet amount: ");
x = input.nextInt();
}
//Bet should be less than or equal to pot if 0 user quit
if (x > 0 && x <= potAmount) {
betAmount = x;
potAmount = potAmount - betAmount;
} else if (x == 0) {
System.out.println("You end the game with pot " + potAmount);
System.exit(0);
}
}
The following loop did not work on validating Integer
while (x>potAmount || x<0 || !(input.hasNextInt())){
System.out.println("Error - cannot bet less than 0 or more than " + potAmount + "..Enter your bet amount: ");
x = input.nextInt();
}
You can try to use String in lieu of int. Then, you can go ahead with again int using Integer.parseInt(x) because it's already been verified as being valid integer after do-while
String x;
String regex = "[0-9]+"; // to check the string only is made up of digits
int potAmount = 10;
Scanner input = new Scanner(System.in);
do {
System.out.println("Please input an integer");
x = input.next();
} while (!x.matches(regex) || Integer.parseInt(x) > potAmount || Integer.parseInt(x) < 0);
int validBet = Integer.parseInt(x);
/* .
.
. *\
I am still having trouble figuring out how the heck the most efficient way to do this is.. Basically, I am trying to make the balance = 0 for every object in the Account array created. I tried using a for loop and set balance = 0for each account created, but I am unsure of how to make this work since the balance variable is created in the class that has all of the methods. I have been trying to this problem all day, but no luck. Thanks.
Main method:
import java.util.Scanner;
import java.text.NumberFormat;
public class Account2
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
Account[] acct = new Account[30];
for (int count2; count2 < 30; count2++)
{
balance = 0; //Initial balance is always set to zero to be able to run fresh program every time
}
System.out.println("Enter your account number (1-30): ");
int key = scan.nextInt() - 1;
int reset = 0;
while (reset == 0)
{
System.out.println("Enter W for withdrawl; D for deposit; X to escape");
char choice = scan.next().charAt(0);
if (choice == 'W' || choice == 'w' || choice == 'D' || choice == 'd' || choice == 'x' || choice == 'X')
{
if (choice == 'W' || choice == 'w')
{
System.out.println("Enter amount to withdraw: ");
Double withdraw1 = scan.nextDouble();
if (withdraw1 <= acct[key].getBalance())
{
acct[key].withdraw(withdraw1);
System.out.println("User # " + key++ + " funds after withdraw: " + acct[key].getBalance() + "$");
System.out.println("User # " + key++ + " funds after interest: " + acct[key].addInterest() + "$");
reset++;
}
else
System.out.println("Insufficient funds.");
}
if (choice == 'D' || choice == 'd')
{
System.out.println("Enter amount to deposit: ");
Double deposit1 = scan.nextDouble();
if (deposit1 > 0)
{
acct[key].deposit(deposit1);
System.out.println("User # " + key++ + " funds after deposit: " + acct[key].getBalance() + "$");
System.out.println("User # " + key++ + " funds after interest: " + acct[key].addInterest() + "$");
reset++;
}
else
System.out.println("Use the withdrawl feature to withdrawl money.");
}
if (choice == 'x' || choice == 'X')
System.out.println("Thank You for using this bank.");
reset++;
}
else
{
System.out.println("Invalid entry, please try again");
reset = 0;
}
}
}
}
Supporting class:
public class Account
{
private final double RATE = 0.03; //Interest is 3%
private int acctNumber;
private String name;
private balance;
//Defines owner, account number, and initial balance.
public Account(String owner, int account, double initial)
{
name = owner;
acctNumber = account;
balance = initial;
}
//deposits a specified amount and returns new balance
public double deposit(double amount)
{
balance = balance + amount;
return balance;
}
//withdraws the specified amount from the account and applies the fee
// + returns balance
public double withdraw(double amount)
{
int fee = 1;
balance = balance - amount - fee;
return balance;
}
//Adds interest to the account
public double addInterest()
{
balance += (balance * RATE);
return balance;
}
public double getBalance()
{
return balance;
}
//returns a one line description of the account as a string
public String toString()
{
NumberFormat fmt = NumberFormat.getCurrencyInstance();
return acctNumber + "/t" + name + "/t" + fmt.format(balance);
}
}
From an outside class, you can only interact with Account in the way exposed in its visible (e.g. public) API.
In this case, the current way to do this would be to withdraw() the current balance:
acct[i].withdraw(acct[i].getBalance());
Though this specific case would put the balance into the negatives because you charge a fee for a withdrawal (which is hidden from the calling class).
If you were to expose a setBalance method on Account, you could instead do
acct[i].setBalance(0);
However on closer look, it seems like what you are having trouble with is actually initializing the array of accounts. You can do this like this:
for (int count2; count2 < 30; count2++)
{
acct[count2] = new Account(owner, count2, 0);
}
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;
}
}
}
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++;
}
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).