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.
Related
I just started learning how to program in Java. Everything was going well so far.. That was until I came across this "bonus" question/problem our teacher gave us to solve as an additional "challenge".
Please click here to view the Question and the Sample input/output (it's an image file)
Note that I'm not allowed to use anything that wasn't taught or discussed in class. So, things like arrays, method overloading, parsing arrays to methods, parseInt, etc. gets ruled out.
Here's what I was able to come up with, so far:
import java.util.Scanner;
public class Test
{
public static void main(String[] args)
{
int N; // number of lines of input
double length1, length2, length3; // the 3 lengths
double perimeter; // you get this by adding the 3 lengths
double minperimeter=0; // dummy value
Scanner input = new Scanner(System.in);
System.out.println("Enter the number of triangles you have:");
N = input.nextInt();
System.out.println("Insert the lengths of the sides of these " +
"triangles (3 real numbers per line):");
for (int counter=0; counter<N; counter++)
{
length1 = input.nextDouble();
length2 = input.nextDouble();
length3 = input.nextDouble();
perimeter = (length1 + length2 + length3);
minperimeter = Math.min(perimeter,Math.min(perimeter,perimeter));
}
System.out.printf("The minimum perimeter is %.1f%n", minperimeter);
}
}
My 2 main problems are:
1) The program only stores and works with the 'last' input.
The ones before it get replaced with this one. [update: solved this problem]
2) How do I print the "triangle number" in the final output? [update: solved this problem, too]
So, can anyone please help me come up with a solution that requires only the very basic learnings of Java? If it helps, this is the book we're using. Currently at Chapter 4. But we did learn about Math Class (which is in Chapter 5).
Update: Thank you so much for your replies, everyone! I was able to come up with a solution that does exactly what was asked in my question.
Math.min(perimeter,perimeter) will always give you perimeter. You probably wanted to do Math.min(perimeter,minPerimeter)
Since it's a programming assignment is best if I don't give you the full solution to your second question, but your hint is, in the counter parameter of your for loop. Save that when you update minperimeter, so that you know in which iteration of the loop you found the minimum.
Also, initialise your minPerimeter to 10000 or higher. If you start at 0, Math.Min will never be lower than that.
Change your for loop as:
double minperimeter=-1;
for (int counter=0; counter<N; counter++)
{
length1 = input.nextDouble();
length2 = input.nextDouble();
length3 = input.nextDouble();
perimeter = (length1 + length2 + length3);
if(minperimeter == -1){
minperimeter = perimeter;
} else{
Math.min(perimeter,minperimeter);
}
}
You have to store the smaller perimeter in your variable perimeter.
The hint from your task tells you, that any given perimeter is smaller than 1000. Thus initiate the perimeter to 1000.
In your for-loop then you have to store the smaller perimeter:
perimeter = Math.min(perimeter, length1 + length2 + length3)
if the sum of the edges is smaller than the current perimeter, the smaller value will be stored.
Please note that according to your given task, you have to input 3 doubles within one line.
Alternative Solution
Make an ArrayList and add all perimeter to that list and then find the minimum value from that list.
List<Double> perimeter = new ArrayList<>();
for (int counter=0; counter<N; counter++)
{
length1 = input.nextDouble();
length2 = input.nextDouble();
length3 = input.nextDouble();
perimeter.add(length1 + length2 + length3);
}
System.out.printf("The minimum perimeter is %.1f%n", Collections.min(perimeter));
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
This question already has answers here:
min change greedy algorithm in java
(2 answers)
Closed 8 years ago.
I have a cashregister program that inputs purchases and payment and outputs the change due. i need it to not give just an amount but what particular coins/dollars user should get back. heres two methods i have
public void recordPurchase()
{
System.out.print("Enter total purchase price or negative number to end: ");
double input = keyboard.nextDouble();
while(input > 0)
{
purchase = purchase + input;
System.out.print("Enter total purchase price or negative number to end: ");
input = keyboard.nextDouble();
}
}
public double giveChange(Money moneyTypes)
{
double change = payment - purchase;
purchase = 0;
payment = 0;
//computes change rounding to two decimal places
change = (double)(Math.round(change*100))/100;
return change;
}
I need to output what coins/dollars person should get back. i have the money types saved in an array called moneyTypes. for example if the change due is $1.06 it would output you receive a dollar nickel and penny.
any advice would help. Thanks! if you need to see more of the code let me know
I'll give you an advice how to do it, not a solution.
Make a list of possible coin/note values.
Then from the biggest to lowest, compute how many times it fits into the remainder, and subtract this amount of money from the value. Make a note of the number of coins/notes.
This way, you will get the numbers you need.
count = Math.floor(remainder/coinValue) might help you.
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
Im working on a CS assignment and Im having a little trouble understanding how to output an array of doubles that represent the amt of money in a bank account at increments of time given a user specified growth rate. I have a main method that asks the user for initialAmount of $, a growthRate and the number of time intervals (denoted iA, gR and nP for inital Amount, growth Rate and number of Periods). this method then calls another method which is of return type double[]. My issue is with the code inside my for-loop, it compiles fine but outputs gibberish. heres the code:
import java.util.Scanner;
public class Benford {
public static double[] generateBenfordNumbers (double iA, double gR, int nP) {
double[] bankStatement = new double[nP];
for (int i = 0; i<nP; i++) {
bankStatement[i] = (iA*(Math.pow((1+(gR)), (i++))));
}
return bankStatement;
}
public static void main (String[] args) {
Scanner scan = new Scanner(System.in);
double iA;
double gR;
int nP;
System.out.print("What is the initial amount of money that you are starting with? : ");
iA = scan.nextDouble();
System.out.println();
System.out.print("What is the amount of growth per time period? : ");
gR = scan.nextDouble();
System.out.println();
System.out.print("How many time periods would you like to use? : ");
nP = scan.nextInt();
System.out.println();
generateBenfordNumbers(iA, gR, nP);
System.out.print(generateBenfordNumbers(iA, gR, nP));
}
}
In the line
bankStatement[i] = (iA*(Math.pow((1+(gR)), (i++))));
i++ increments i a second time. You probably want:
bankStatement[i] = (iA*(Math.pow((1+(gR)), i + 1)));
or, if we clean it up,
bankStatement[i] = iA * Math.pow(1 + gR, i + 1);
i + 1 returns a value 1 greater than that of i, but does not actually increment the variable itself.
Also, do you really have to use Math.pow each time? Can't you just manually set the first element of your array to iA and subsequently use bankStatement[i-1] to compute bankStatement[i]? Doing something like this will probably improve your program.
i is incremented twice : at loop level and into the body
The gibberish output looks like this:
[D#1b67f74
which is s double array text representation. You could use:
System.out.print(Arrays.toString(generateBenfordNumbers(iA, gR, nP)));
You should not be incrementing i inside your call to Math.pow. This is because you already increment it in your for loop. The result is that elements of your array are getting skipped and not set. This is probably where the gibberish-ness is coming from.
You probably want to change:
bankStatement[i] = (iA*(Math.pow((1+(gR)), (i++))));
To:
bankStatement[i] = iA*Math.pow(1+gR, i);
Also, as an aside, you generally shouldn't use so many parenthesis because it makes it hard to read. If you're not sure what the order of operations is, look it up.
What the others said, you're incrementing i twice so I'm not going to repeat that. I just want to add that brackets are good to organize formulas and to ensure correct execution order of calculations, but if you overuse them, they can obfuscate the intention of your program and they may make the problem you're looking for harder to spot. Compare
bankStatement[i] = iA * Math.pow(1.0 + gR, i+1);
with
bankStatement[i] = (iA*(Math.pow((1+(gR)), (i))));
See what I mean?
EDIT - following ARS very valid remark about the initial value of i, I changed the cleaned up statement.