This code doesn't work. I get the following errors (in eclipse) that I can't seem to resolve:
Syntax error, insert ":: IdentifierOrNew" to complete ReferenceExpression
Syntax error, insert ";" to complete BlockStatements
Duplicate local variable interest
import java.util.Scanner;
public class DoWhile {
public static void main (String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("balance: ");
int balance = in.nextInt();
System.out.print("interestRate: ");
double interestRate = in.nextDouble();
System.out.print("year: ");
int year = in.nextInt();
System.out.print("input: ");
String input = in.next();
Integer interest = null; //to define interest
do
{
double interest = balance * interestRate / 100;
balance += interest;
year++; // print current balance
}
while (input.equals("N"));
System.out.println("interest: " + interest + "balance: " + balance + "year: " + year) ;
};
}
The variable interest is declared twice.
Here is a slightly cleaned up version of your code:
import java.util.Scanner;
public class DoWhile {
public static void main (String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("balance: ");
int balance = in.nextInt();
System.out.print("interestRate: ");
double interestRate = in.nextDouble();
System.out.print("year: ");
int year = in.nextInt();
System.out.print("press 'N' to exit");
String input = in.next();
double interest = 0; //to define interest
do
{
interest = balance * interestRate / 100;
balance += interest;
year++; // print current balance
}
while (input.equals("N"));
System.out.println("interest: " + interest + "balance: " + balance + "year: " + year) ;
}
}
Related
I am working on a school project and I am pretty much done but have been stuck in a detail. I am asking the user to enter their starting balance and the interest rate, to make it easier for the user just asking to enter a whole number like 1, 2, 3, etc. Example, if they enter 1000 in starting balance and 9% in the interest rate the result would 1750.00, the expected result is 1007.50 which comes when the user enters .09%, is there a way to change any number the user enters to that so when they enter 9 it transforms it into .09. If you run the code, enter starting balance and rate and then select "M", you will see those numbers. Any ideas will be appreciated, here is the code:
///BankDemo class
import java.util.Scanner;
public class BankDemo {
#SuppressWarnings("unlikely-arg-type")
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
float startingBalance;
float interestRate;
String userInput;
System.out.print("Enter beginning balance :$");
startingBalance = keyboard.nextFloat();
System.out.print("Enter interest rate(whole number) :%");
interestRate = keyboard.nextFloat();
System.out.println("Enter D for deposit" + "\nEnter W to Withdraw" + "\nEnter B for Balance" +
"\nEnter M for Monthly Process" + "\nEnter E to Exit");
userInput = keyboard.next().toLowerCase();
float bal = startingBalance;
float rate = interestRate;
BankAccount ba = new BankAccount(startingBalance, interestRate);
SavingsAccount sv = new SavingsAccount(bal, rate);
if("d".equals(userInput)) {
ba.deposit();
} else if("w".equals(userInput)) {
ba.withdraw();
} else if("b".equals(userInput)) {
ba.totalBalance();
} else if("m".equals(userInput)) {
ba.monthlyProcess();
} else if("e".equals(userInput)) {
ba.exit();
} else {
System.out.print("Error, option to valid");
}
}
}
///BankAccount Class
import java.util.Scanner;
public class BankAccount {
protected float balance;
protected float numDeposits;
protected float numWithdrawals;
protected float annualRate;
protected float monthlyServCharg;
public BankAccount() {
balance = 0;
numDeposits = 0;
numWithdrawals = 0;
annualRate = 0;
monthlyServCharg = 0;
}
public BankAccount(float startingBalance, float interestRate) {
balance = startingBalance;
annualRate = interestRate;
}
public void deposit() {
float valueD;
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter the amount you want to deposit :$");
valueD = keyboard.nextFloat();
balance += valueD;
numDeposits++;
}
public void withdraw() {
float valueW;
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter the amount you want to withdraw :$");
valueW = keyboard.nextFloat();
if(valueW < 1) {
System.out.println("Error: Must enter positive value\n");
}
balance -= valueW;
numDeposits++;
}
public void totalBalance() {
System.out.print("Balance is: " + balance);
}
public void calcInterest() {
float monRate = annualRate / 12;
float monInt = balance * monRate;
balance += monInt;
}
public void monthlyProcess() {
calcInterest();
balance -= monthlyServCharg;
numWithdrawals = 0;
numDeposits = 0;
monthlyServCharg = 0;
System.out.printf("Your Balance after Monthly process is: %.2f", balance);
}
public void exit() {
totalBalance();
System.out.print("\nThank you. Bye");
}
}
In your overload constructor, set annualRate equal to (interestRate / 100) to convert it to a percentage. Also, as a side node, you don't need to initialize all the variables on the default constructor because they're initialize to 0 since they're primitive data types.
I have to do this program where I have to display the calculation of the profit for each individual stock, but I also have to display the profit for the total amount of stocks. My code only has it so it displays the calculation for all of the stocks:
import java.util.Scanner;
public class KNW_MultipleStockSales
{
//This method will perform the calculations
public static double calculator(double numberShare, double purchasePrice,
double purchaseCommission, double salePrice,
double salesCommission)
{
double profit = (((numberShare * salePrice)-salesCommission) -
((numberShare * purchasePrice) + purchaseCommission));
return profit;
}
//This is where we ask the questions
public static void main(String[] args)
{
//Declare variables
Scanner scanner = new Scanner(System.in);
int stock;
double numberShare;
double purchasePrice;
double purchaseCommission;
double salePrice;
double saleCommission;
double profit;
double total = 0;
//Ask the questions
System.out.println("Enter the stocks you have: ");
stock = scanner.nextInt();
//For loop for the number stock they are in
for(int numberStocks=1; numberStocks<=stock; numberStocks++)
{
System.out.println("Enter the number of shares for stock " + numberStocks + ": ");
numberShare = scanner.nextDouble();
System.out.println("Enter the purchase price" + numberStocks + ": ");
purchasePrice = scanner.nextDouble();
System.out.println("Enter the purchase commissioned:" + numberStocks + ": ");
purchaseCommission = scanner.nextDouble();
System.out.println("Enter the sale price:" + numberStocks + ": ");
salePrice = scanner.nextDouble();
System.out.println("Enter the sales commissioned:" + numberStocks + ": ");
saleCommission = scanner.nextDouble();
profit = calculator(numberShare, purchasePrice, purchaseCommission,
salePrice, saleCommission);
total = total + profit;
}
//Return if the user made profit or loss
if(total<0)
{
System.out.printf("You made a loss of:$%.2f", total);
}
else if(total>0)
{
System.out.printf("You made a profit of:$%.2f", total);
}
else
{
System.out.println("You made no profit or loss.");
}
}
}
How can I get it so each individual stock profit gets shown, with the profit of all the stocks together?
Try maintaining a separate Map for profit/loss. You may want to accept Stock Name as an input which will help manage individual stocks effectively.
// Map of stock name and profit/loss
Map<String,Double> profitMap = new HashMap<String,Double>();
After calculating profit/loss, add entry to map
profitMap.put("stockName", profit);
total = total + profit;
At the end of your program, iterate and display profit/loss for each Stock from Map.
for (Entry<String, Integer> entry : profitMap.entrySet()) {
System.out.println("Stock Name : " + entry.getKey() + " Profit/loss" + entry.getValue());
}
I haven't been able to make this code executable for class and can't find the reason why there are no errors prompting however when i execute i get this:
Exception in thread "main" java.lang.UnsupportedOperationException: Not
supported yet.
at set.fixedSalary(set.java:14)
at Main.main(Main.java:23)
C:\Users\the_h\AppData\Local\NetBeans\Cache\8.2\executor-
snippets\run.xml:53: Java returned: 1
I honestly have no idea how to fix this problem any help is appreciated I have the source code below.
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
private double fixedSalary;
private double commission;
private double salesTarget;
private double Acc_Rate;
private ArrayList<Double> annualSales;
private ArrayList name;
public static void main(String[] args){
// salesperson will earn a fixed salary of $32,600
set.fixedSalary(32600);
// The current sales target for every salesperson is $120,000.00
set.SalesTarget(120000.00);
//The acceleration factor is 2.1
set.Acc_Rate(2.1);
}
public ArrayList<Double> getAnnualSales(){
return annualSales;
}
public Main() {
this.name = new ArrayList();
this.annualSales = new ArrayList<>();
}
private float calculateCommission(double personSale) {
throw new UnsupportedOperationException("Not supported yet."); //To
change body of generated methods, choose Tools | Templates.
}
function read user input
class readData{
public void readData(){
// Creates a scanner object for sales entry.
Scanner input = new Scanner(System.in);
// prompts user for name of sales person
System.out.println("Please enter First Sales Person name: ");
name = addinput.nextLine();
// prompts user for name of sales person
System.out.println("Please enter 2nd Sales Person name: ");
name = addinput.nextLine();
//Prompts user for sales
System.out.println("Please enter annual sales First Person: ");
annualSales = addinput.nextDouble();
//Prompts user for sales
System.out.println("Please enter annual sales Second Person: ");
annualSales = addinput.nextDouble();
}
}
class calculateCommission {
double commission = 0.00;
double Acc_Rate;
calculateCommission() {
}
public double calculateCommission(double annualSales, double fixedSalary,
double salesTarget) {
this.Acc_Rate = 0.045 * annualSales;
double earnings = fixedSalary;
// The current commission is 4.5 of total sales
if(annualSales < 0.8 * salesTarget) {
earnings = fixedSalary + commission;
} else if (annualSales <= salesTarget){
//The current acc rate is 2.1 of total sales
commission = 0.045 * annualSales;
earnings = fixedSalary + commission;
} else if (annualSales > salesTarget){
earnings = fixedSalary + Acc_Rate;
}
return earnings;
}
} // function get commision
public double getCommission() {
return commission;
}
// function get total annual compensation
public double getTotalCommissionCalc(){
return fixedSalary + getCommission();
}
// funtion set value for fixedSalary
public void setfixedSalary(double fixedSalary){
this.fixedSalary = fixedSalary;
}
// funtion set value for salesTarget
public void setSalesTarget(double salesTarget){
this.salesTarget = salesTarget;
}
// funtion set value for incentive rate
public void setAcc_Rate(double Acc_Rate) {
this.Acc_Rate = Acc_Rate;
}
// Display a table of potential total annual compensation
public void displayResult(){
double annualSalesCalc;
double personSale;
for (int i = 0; i < name.size(); i++){
String personName = (String) name.get(i);
personSale = annualSales.get(i);
System.out.println("Total Compensation of Sales Person " +
personName + " is " + Math.round(calculateCommission(personSale)));
//Print column names
System.out.print("SalePerson\tTotal Sales\tTotal Compensation");
annualSalesCalc = personSale * 1.50;
while(personSale <= annualSalesCalc){
calculateCommission(personSale);
System.out.println((personName) + "\t\t" +
Math.round((personSale)) + "\t\t" +
Math.round(calculateCommission(personSale)));
personSale = personSale + 5000;
}
System.out.println(); // print blank line
}
if (annualSales.get(0) > annualSales.get(1)) {
System.out.println("Salesperson " + name.get(1)
+ "'s additional amount of sales that he must "
+ "achieve to match or exceed the higher of the salesperson
"
+ Math.round(annualSales.get(0)) + " is");
System.out.print("$" + Math.round((annualSales.get(0) -
annualSales.get(1))));
} else if(annualSales.get(1) > annualSales.get(0)){
System.out.println("Salesperson " + name.get(0)
+ "'s additional amount of sales that he must "
+ "achieve to match or exceed the higher of the salesperson
"
+ Math.round(annualSales.get(1)) + " is");
System.out.print("$" + Math.round((annualSales.get(1) -
annualSales.get(0))));
} else{
System.out.print("Both have same compensation");
}
}
}
It might be because your set.fixedSalary needs to be an integer because you dont set it as a double. you set it to 36000 when it needs to be 36000.0
/**I am trying to ask for user input for the number of the books they want to order, then using for find the cost of each book, total them up and give them their receipt at the end for their order. I understand how to give them the output just having trouble with my loop.*/
import java.util.Scanner;
public class BookOrder {
public static void main(String[] orgs){
Scanner in = new Scanner(System.in);
final double TAX = .065;
final double SHIPPING = 2.95;
int counter = 0;
double bookSubtotal, subtotal, taxPaid;
System.out.print("Please enter the number of books you're ordering: ");
double numberOfBooks = in.nextDouble();
for (counter = 0; counter < numberOfBooks; counter++){
System.out.println("Please enter the cost of your book: ");
double priceOfBooks = in.nextDouble();
bookSubtotal = priceOfBooks + bookSubtotal;
counter ++;
}
double subtotal = numberOfBooks * priceOfBooks;
double taxpaid = subtotal * (TAX);
double shippingCharge = SHIPPING * numberOfBooks;
double sumOfOrder = bookSubtotal + priceOfOrder + shippingCharge + TAX;
System.out.println("Number of books purchased:" + numberOfBooks);
System.out.println("Book subtotal: $" + subtotal);
System.out.println("Tax: $" + taxPaid);
System.out.println("Shipping: $" + shippingCharge);
System.out.println("-------------------------------");
System.out.println("The price of the order is $" + sumOfOrder + ".");
}
}
You seem to increment counter twice:
for (counter = 0; counter < numberOfBooks; counter++){
System.out.println("Please enter the cost of your book: ");
double priceOfBooks = in.nextDouble();
bookSubtotal = priceOfBooks + bookSubtotal;
counter ++;//this line
}
What happens in this line is that you increment counter, but the loop does that for you, because of:
for(counter = 0;counter<numberOfBooks;counter++)
the counter++ in that line increments counter for you, so just remove the
counter++;
line in the for loop (the one I wrote this line next to)
Also, you should set a value to bookSubtotal:
int bookSubtotal = 0;
in the beginning.
Additionally, you might want to make numberOfBooks an integer:
int numberOfBooks = in.nextInt();
And you shouldn't re declare subtotal twice, just remove the word double in the line:
double subtotal = (double)numberOfBooks * priceOfBooks;
Nor do you need the create taxpaid before the loop, because you have taxPaid after it. Naming is case sensitive, meaning capital letters Are ImpOrtaNt...
public class BookOrder {
public static void main(String[] orgs){
Scanner in = new Scanner(System.in);
final double TAX = .065;
final double SHIPPING = 2.95;
int counter = 0;
double bookSubtotal = 0;
System.out.print("Please enter the number of books you're ordering: ");
int numberOfBooks = in.nextInt();
for (counter = 0; counter < numberOfBooks; counter++){
System.out.println("Please enter the cost of your book: ");
double priceOfBooks = in.nextDouble();
bookSubtotal += priceOfBooks;
}
double shippingCharge = SHIPPING * numberOfBooks;
double tax = TAX * bookSubtotal;
double sumOfOrder = bookSubtotal + shippingCharge + tax;
System.out.println("Number of books purchased:" + numberOfBooks);
System.out.println("Book subtotal: $" + bookSubtotal);
System.out.println("Tax: $" + tax);
System.out.println("Shipping: $" + shippingCharge);
System.out.println("-------------------------------");
System.out.println("The price of the order is $" + sumOfOrder + ".");
}
}
The problem
Design a SavingsAccount class that stores a savings account’s annual interest rate and balance. The class constructor should accept the amount of the savings account’s starting balance. The class should also have methods for subtracting the amount of a withdrawal, adding the amount of a deposit, and adding the amount of monthly interest to the balance. The monthly interest rate is the annual interest rate divided by twelve. To add the monthly interest to the balance, multiply the monthly interest rate by the balance, and add the result to the balance.
Test the class in a program that calculates the balance of a savings account at the end of a period of time. It should ask the user for the annual interest rate, the starting balance, and the number of months that have passed since the account was established. A loop should then iterate once for every month, performing the following:
Ask the user for the amount deposited into the account during the month. Use the class method to add this amount to the account balance.
Ask the user for the amount withdrawn from the account during the month. Use the class method to subtract this amount from the account balance.
Use the class method to calculate the monthly interest.
After the last iteration, the program should display the ending balance, the total amount of deposits, the total amount of withdrawals, and the total interest earned.
I keep getting one issue in the Main Program on line 22, that if I fix, it messes up a bunch of the code. Anyone know how I could go about fixing this?
import java.text.DecimalFormat;
import java.util.Scanner;
import java.io.*;
public class SavingsAccountMainProgram {
public static void main(String args[]) {
Scanner keyboard = new Scanner(System.in);
System.out.print("How much money is in the account?: ");
double startingBalance = keyboard.nextDouble();
System.out.print("Enter the annual interest rate:");
double annualInterestRate = keyboard.nextDouble();
SavingsAccountClass savingAccountClass = new SavingsAccountClass();
SavingsAccount savingsAccountClass = savingAccountClass.new SavingsAccount(
startingBalance, annualInterestRate);
System.out.print("How long has the account been opened? ");
double months = keyboard.nextInt();
double montlyDeposit;
double monthlyWithdrawl;
double interestEarned = 0.0;
double totalDeposits = 0;
double totalWithdrawn = 0;
for (int i = 1; i <= months; i++) {
System.out.print("Enter amount deposited for month: " + i + ": ");
montlyDeposit = keyboard.nextDouble();
totalDeposits += montlyDeposit;
savingsAccountClass.deposit(montlyDeposit);
System.out.print("Enter amount withdrawn for " + i + ": ");
monthlyWithdrawl = keyboard.nextDouble();
totalWithdrawn += monthlyWithdrawl;
savingsAccountClass.withdraw(monthlyWithdrawl);
savingsAccountClass.addInterest();
interestEarned += savingsAccountClass.getLastAmountOfInterestEarned();
}
keyboard.close();
DecimalFormat dollar = new DecimalFormat("#,##0.00");
System.out.println("Total deposited: $" + dollar.format(totalDeposits));
System.out.println("Total withdrawn: $" + dollar.format(totalWithdrawn));
System.out.println("Interest earned: $" + dollar.format(interestEarned));
System.out.println("Ending balance: $"
+ dollar.format(savingsAccountClass.getAccountBalance()));
}}
And the other program for this
import java.util.Scanner;
import java.io.*;
public class SavingsAccountClass {
class SavingsAccount {
private double accountBalance;
private double annualInterestRate;
private double lastAmountOfInterestEarned;
public SavingsAccount(double balance, double interestRate) {
accountBalance = balance;
annualInterestRate = interestRate;
lastAmountOfInterestEarned = 0.0;
}
public void withdraw(double withdrawAmount) {
accountBalance -= withdrawAmount;
}
public void deposit(double depositAmount) {
accountBalance += depositAmount;
}
public void addInterest() {
// Get the monthly interest rate.
double monthlyInterestRate = annualInterestRate / 12;
// Calculate the last amount of interest earned.
lastAmountOfInterestEarned = monthlyInterestRate * accountBalance;
// Add the interest to the balance.
accountBalance += lastAmountOfInterestEarned;
}
public double getAccountBalance() {
return accountBalance;
}
public double getAnnualInterestRate() {
return annualInterestRate;
}
public double getLastAmountOfInterestEarned() {
return lastAmountOfInterestEarned;
}
}
}
Also, would anyone know how I could submit a .class file like the teacher has requested?
Not sure why you have SavingsAccount as inner class. For what purpose?
Here I modified what you have shared and I think it answers the problem statement well
main method
public static void main (String arg[]) {
Scanner keyboard = new Scanner(System.in);
System.out.print("How much money is in the account?: ");
double startingBalance = keyboard.nextDouble();
System.out.print("Enter the annual interest rate:");
double annualInterestRate = keyboard.nextDouble();
SavingsAccount savingsAccount = new SavingsAccount(startingBalance, annualInterestRate);
System.out.print("How long has the account been opened? ");
double months = keyboard.nextInt();
double montlyDeposit;
double monthlyWithdrawl;
double interestEarned = 0.0;
double totalDeposits = 0;
double totalWithdrawn = 0;
for (int i = 1; i <= months; i++) {
System.out.print("Enter amount deposited for month: " + i + ": ");
montlyDeposit = keyboard.nextDouble();
totalDeposits += montlyDeposit;
savingsAccount.deposit(montlyDeposit);
System.out.print("Enter amount withdrawn for " + i + ": ");
monthlyWithdrawl = keyboard.nextDouble();
totalWithdrawn += monthlyWithdrawl;
savingsAccount.withdraw(monthlyWithdrawl);
savingsAccount.addInterest();
interestEarned += savingsAccount.getLastAmountOfInterestEarned();
}
keyboard.close();
DecimalFormat dollar = new DecimalFormat("#,##0.00");
System.out.println("Total deposited: $" + dollar.format(totalDeposits));
System.out.println("Total withdrawn: $" + dollar.format(totalWithdrawn));
System.out.println("Interest earned: $" + dollar.format(interestEarned));
System.out.println("Ending balance: $" + dollar.format(savingsAccount.getAccountBalance()));
}
and, removed SavingsAccountClass and made SavingsAccount as the top level class
class SavingsAccount {
.
.
//everything as it is
}