I'm stupid.
import java.util.Scanner;
public class ATM {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
double withdraw = scanner.nextDouble();
double balance = scanner.nextDouble();
int withdraw = 0; int balance;
if (withdraw % 5 == 0 && withdraw<(balance-.5)) {
balance = balance - (withdraw + .5);
System.out.println(balance);
}
else {
System.out.println(balance);
}}}
I'm trying to make it so that the Balance is being subtracted by the Withdrawal amount while incurring a $.50 charge. Unfortunately, it keeps only subtracting the $.50 without subtracting withdraw. Thanks in advance.
FIXED CODE
import java.util.Scanner;
public class ATM {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
double withdraw = scanner.nextDouble();
double balance = scanner.nextDouble();
if (withdraw % 5 == 0 && withdraw<(balance-.5)) {
balance -= (withdraw + .5);
System.out.println(balance);
}
else {
System.out.println(balance);
}}}
Here is the algorithm https://stackoverflow.com/a/14387552/1083704
You have the same problem - a bug in the complex expression, which includes using unknown types. And you must do the same thing to debug your program -- simplify the oneliner into multiple simple expressions, using intermediate variables. Then you can step-by-step debug your code and observe those intermediate values. Being a programmer means being a hacker and you won't be a hacker without learning debugging.
where are you setting the withdraw variable? I'd look there, it sounds like you're adding .5 to a variable that hasn't been assigned a value greater than 0. A real easy way to test in more complex code would be to set withdraw in your code to say a value of 5 right before using it in your balance equation, that way you can tell if the problem is with your equation, or the withdraw variable, the equation looks solid though. Also, you can do
balance -= (withdraw + .5)
It is fairly hard to debug code when given so little information; but my best guess would be an initialization bug - where withdraw has not been initialized correctly and is just at what I'd assume to be its default value, 0
But to be sure, we'd need to know what withdraw is equal to before your print statement.
Could you add a print statement before adding up the balance like so:
System.out.println(withdraw);
balance -= (withdraw + .5);
System.out.println(balance);
And then see whether withdraw is > 0 at runtime? And if not; check that it gets set to your withdraw value before computing the balance.
Even better would be to post your full code snippet, so we can see ourselves I guess.
N.B. a -= b is shorthand for a = a - b
Related
I am creating a bankteller loop java code. I am trying to ask the user for what amount of money they would like to deposit into their account. I can get this to work once. For example, they will enter in $20 the first time. Then they will decide to put in $10 more. However, instead of displaying the current balance at $30, it only displays the one recently entered (the $10). How do I fix this?
Here is my code for that part of the loop in the menu that calls the class:
else if( userInput == 3 ){
Account account = new Account();
System.out.print("\nHow much would you like to deposit?: ");
float money = input.nextFloat();
account.deposit(money);
}
Here is the code for deposit that is called:
public void deposit(float money) {
if (money < 0) {
System.err.println("Error: Can't deposit negative money.\n");
return;
}
else {
currentBalance = money + currentBalance;
System.out.println("Current balance: $" + currentBalance + "\n");
}
}
You want to maintain the total balance so far. However, the moment you create a new Account object, balance gets initialized to zero and thus losing previous balance.
What you need to do is create an Account object only once and then call deposit on the same Account object.
This program will calculate the amortization table for a user. The problem is my assignment requires use of subroutines. I totally forgot about that, any ideas on how to modify this to include subroutines?
public class Summ {
public static void main(String args[]){
double loanamount, monthlypay, annualinterest, monthlyinterest, loanlength; //initialize variables
Scanner stdin = new Scanner (System.in); //create scanner
System.out.println("Please enter your loan amount.");
loanamount = stdin.nextDouble(); // Stores the total loan amount to be payed off
System.out.println("Please enter your monthly payments towards the loan.");
monthlypay = stdin.nextDouble(); //Stores the amount the user pays towards the loan each month
System.out.println("Please enter your annual interest.");
annualinterest = stdin.nextDouble(); //Stores the annual interest
System.out.println("please enter the length of the loan, in months.");
loanlength = stdin.nextDouble(); //Stores the length of the loan in months
monthlyinterest = annualinterest/1200; //Calculates the monthly interest
System.out.println("Payment Number\t\tInterest\t\tPrincipal\t\tEnding Balance"); //Creates the header
double interest, principal; //initialize variables
int i;
/* for loop prints out the interest, principal, and ending
* balance for each month. Works by calculating each,
* printing out that month, then calculating the next month,
* and so on.
*/
for (i = 1; i <= loanlength; i++) {
interest = monthlyinterest * loanamount;
principal = monthlypay - interest;
loanamount = loanamount - principal;
System.out.println(i + "\t\t" + interest
+ "\t\t" + "$" + principal + "\t\t" + "$" + loanamount);
}
}
}
any ideas on how to modify this to include subroutines?
Well, you are better off doing it the other way around; i.e. working out what the methods need to be before you write the code.
What you are doing is a form or code refactoring. Here's an informal recipe for doing it.
Examine code to find a sections that perform a specific task and produces a single result. If you can think of a simple name that reflects what the task does, that it a good sign. If the task has few dependencies on the local variables where it currently "sits" that is also a good sign.
Write a method declaration with arguments to pass in the variable values, and a result type to return the result.
Copy the existing statements that do the task into the method.
Adjust the new method body so that references to local variables from the old context are replaced with references to the corresponding arguments.
Deal with the returned value.
Rewrite the original statements as a call to your new method.
Repeat.
An IDE like Eclipse can take care of much of the manual work of refactoring.
However, the real skill is in deciding the best way to separate a "lump" of code into discrete tasks; i.e. a way that will make sense to someone who has to read / understand your code. That comes with experience. And an IDE can't make those decisions for you.
(And did I say that it is easier to design / implement the methods from the start?)
I deleted my previous comment as I answered my own question by reading the associated tags :-)
As an example, define a method like this in your class:
public double CalculateInterest(double loanAmount, double interestRate) {
//do the calculation here ...
}
And then call the method by name elsewhere in your class code e.g.
double amount = CalculateInterest(5500, 4.7);
I'm having trouble i need to take a user input and increment it by 1/10 starting at 0 so if the user enters a 5.2 i need to to go through 0.1 0.2 0.3 etc display each and stop at 5.2 until the method is called again and a new input is entered here is what i have but it just runs through up until 10 i understand why it does this just not enough to be able to fix this any help would be appreciated
import java.util.Scanner;
public class SpeedChange {
public double startSpeed;
public double newSpeed;
public void changeUserSpeed(){
Scanner sc = new Scanner (System.in);
System.out.println("How fast would you like to go between 1-10 mph?");
double newSpeed = sc.nextDouble();
for(newSpeed = sc.nextDouble(); newSpeed <= 10.00; newSpeed+=.1 ){
System.out.println(newSpeed);
}
}
}
You need to change your loop content.Since your newSpeed has been specified by the user,you don't need to alter it.You simply need to create a new double variable,say Speed,which will increment in the limit of 0.1 at each iteration and keep running until your Speed equals newSpeed.
for(double Speed=0;Speed<=newSpeed;Speed+=0.1 ){
System.out.println(Speed); }
I hope this clears and solves your doubt!
Your code should instead be
for(double speed=0; speed <= newSpeed; speed+=.1 ){
System.out.println(speed);
}
P.S: double/float is not suitable for this kind of use. Use BigDecimal class to do this.
For details, see http://javarevisited.blogspot.in/2012/02/java-mistake-1-using-float-and-double.html?m=1
I've been having trouble with my program. Im supposed to take in 3 variables and plug them into a formula to get an answer. My answer comes out to 0.0 and im not sure what i am doing wrong.
public double compute_cert (int years, double amount, double rate, double certificate)
{
certificate = amount * Math.pow(1 + rate/100, years);
return certificate;
}
The variables rate, amount and years are set up correctly but the answer certificate is always returned as 0.0
public static void main(String[] args)
{
int years = 0;
double amount = 0;
double rate = 0;
double certificate = 0;
char ans;// allows for char
do{
CDProgram C = new CDProgram(years, amount, rate, certificate);
C.get_years();
C.get_amount();
C.get_rate();
C.get_info();
C.compute_cert(years, amount, rate, certificate);
System.out.println ("Would you like to repeat this program? (Y/N)");
ans = console.next().charAt(0);// user enters either Y or y until they wish to exit the program
} while(ans == 'Y'||ans == 'y'); // test of do/while loop
}
Not sure what else to do. Thanks for the help
It looks like you are not assigning the local variables that you are passing into the computation function?
years = C.get_years();
amount = C.get_amount();
rate = C.get_rate();
info = C.get_info();
As it is, the code is just passing 0 for every parameter into your function. Multiplying by 0 will get you 0. If you pass 0, the following line will multiply 0 by some quantity.
certificate = amount * Math.pow(1 + rate/100, years);
It looks like your CDProgram class has fields for years, amount and rate, and your get_ method are prompting the user for the values.
That being the case, it doesn't make sense to pass parameters for them into your calculation method. I would change the method to this.
public double compute_cert () {
certificate = amount * Math.pow(1 + rate/100, years);
return certificate;
}
Then when you call it in main, don't pass any values in. This will just use the values from the fields in the CDProgram class.
Been wracking my brain for hours trying to figure this out.
i have the main method which is:
public static void main(String [] args)
{
double payRate;
double grossPay;
double netPay;
int hours;
Scanner input = new Scanner(System.in);
System.out.println("Welcome to the Pay Roll Program");
printDescription();
System.out.print("Please input the pay per hour: ");
payRate = input.nextDouble();
System.out.println("\nPlease input the pay per hour: ");
hours = input.nextInt();
System.out.println("\n");
netPay = computePaycheck(netPay);
System.out.println("The net pay is $" + (netPay));
System.out.println("We hope you enjoyed this program");
System.exit(0);
and the method that calculated the netPay
public static double computePaycheck(double payRate, int hours)
{
double grossPay = computePaycheck(payRate*hours);
double netPay = (grossPay - (grossPay *.15));
return netPay;
}
But I'm getting the error "computePaycheck(double,int) in PayCheck cannot be applied to (double)"
I sort of understand this, but I can't for the life of me figure out a remedy.
1) You are calling a function with 2 parameters while only passing 1. That will cause a compilation error.
2) When you call computePaycheck from within itself that will loop and cause a stack overflow.
netPay = computePaycheck(netPay);
public static double computePaycheck(double payRate, int hours)
"computePaycheck(double,int) in PayCheck cannot be applied to (double)"
Your method takes two parameters, a double and an int.
You can only call it with those two (you are missing the number of hours in the call).
netPay = computePaycheck(payRate, hours);
double grossPay = payRate*hours;
In your computePaycheck method, you have the following line:
double grossPay = computePaycheck(payRate*hours);
This is passing one parameter (the product of payRate and hours) to the computePaycheck function, which requires two parameters. It looks like you meant to say:
double grossPay = computePaycheck(payRate, hours);
But you will need to be careful! This will cause your program to recur infinitely! You will need to determine how to calculate the gross pay without calling this function, since if you do call it recursively within itself, there is no condition from which it will return.
Your method takes two parameters -- double payRate and int hours, but you are only specifying a double when you call computePaycheck in your main method.
It's not clear what you intend to happen, but the mismatched parameters should let you know what is wrong with your program.
The first statement of your computePaycheck method calls computePaycheck with a single parameter (a double) whereas the computePaycheck takes 2 parameters (a double and an int). That is why your code fails to compile.
If you "fix" this by using double grossPay = computePaycheck(payRate, hours); instead, this will compile BUT you will get infinite recursion! Don't you simply want to do double grossPay = payRate*hours; ?
It's clear that you set 2 parameters but from the main class you are only calling just one parameter. You should find a way to call the 2 parameters at the same time.