Beginner Java Issues [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
EDIT: I am using BlueJ. When I right click my class I am supposed to enter the values for a and b there rather than the actual code. Is there a way to do that?
Hello I am trying to write a basic program that will let me enter 2 numbers and then automatically calculate the sum, difference, division and remainder, and then print the results to the output. Here is what I have so far. It compiles but I get this error
java.lang.ArithmeticException: / by zero
at Q1A3.DoTheCalculation(Q1A3.java:33)
at Q1A3.<init>(Q1A3.java:24)
when I try to run it. I have no java experience and this is my first time trying anything on the computer other than emailing. Please be gentle! Can you point out my errors and guide me toward fixing them? Thank you.
/*
This program accepts two numbers from the user. Finds out the sum, diff, division and
remainder of the two numbers, and prints the results on the screen
*/
public class Q1A3
{
//instant variables - replace the example below with your own
private int a;
private int b;
private int sum;
private int difference;
private int division;
private int remainder;
//-----------------------------------------
//The following is the constructor that takes the input from the user
//and stores it in the system
public Q1A3(int a, int b)
{
DoTheCalculation ( );
PrintTheResults ( );
}
//-------------------------------------------------------------
//The following routine does all of the required calculations.
public void DoTheCalculation ( )
{
sum = (a+b);
difference = (a-b);
division = (a/b);
remainder = (a%b);
}
//----------------------------------------------------------------------------
//The following routine prints all of the information including the calculated
//items on the screen
public void PrintTheResults ( )
{
System.out.println("The value of “a” is:");
System.out.println("The value of “b” is:");
System.out.println("The sum is:" );
System.out.println("The difference is:");
System.out.println("The division is:");
System.out.println("The remainder is:");
}
}

You don't assign any values to a or b. try this:
private int a = 5;
private int b = 7;

(1) Make sure that private member variables are initialized from constructor parameters.
(2) Make sure to assign variables to string outputs.
Please observe the proposed changes in the following source code:
public Q1A3(int a, int b)
{
this.a = a;
this.b = b;
DoTheCalculation ( );
PrintTheResults ( );
}
public void PrintTheResults ( )
{
System.out.println("The value of 'a' is:"+a);
System.out.println("The value of 'b' is:"+b);
System.out.println("The sum is:" +sum);
System.out.println("The difference is:"+difference);
System.out.println("The division is:"+division);
System.out.println("The remainder is:"+remainder);
}
public static void main(String [] args)
{
Q1A3 obj = new Q1A3(8,4);
}

Your answer is in the first line of the error code "/ by zero". You cannot divide by zero (it'd implode the universe or something.) Try an if statement to test if 0 is being passed, and reject, or skip it.

You cannot divide by zero (it'd implode the universe or something.)
~ Andrew
No, it creates black holes. Or something :P
The question has been answered. BUT:
A good way to find the mistake yourself (next time) would have been a good debugger or systematic outputs, e.g. System.out.println("var a:"+a) to see what values which variables have at the time, before the error occurs.

Related

How can I change this linear Java Code for a program that adds and subtracts to Object-Oriented Code

I am trying to make a simple android app that can add and subtract numbers, but my challenge is to make sure that the program is Object-Oriented. Currently I have been told that it is linear, but I am confused as to how it has remained linear after trying many times to make it object-oriented. How can I make this object oriented programming. Here is my code.
import java.util.Scanner;
public class addNumbers {
public static void main(String[] args)
{ // Begin main
Scanner input = new Scanner( System.in ); // Instantiate object input
System.out.println("Enter number 1"); // Ask the user to enter number 1
double number1 = input.nextDouble(); // Read the first number
System.out.println("Enter number 2"); // Ask the user to enter number 2
double number2 = input.nextDouble(); // Read the second number
double sum=number1 + number2; // Add the numbers
double difference = number1 - number2; // Subtract number 2 from number1
System.out.printf("\nSum = %f\n", sum); // Print the sum
System.out.printf("Difference = %f", difference); // Print the difference.
}
} // end main
My applications use this boilerplate to execute inside an object. If you start like this, you can add methods as you need them.
public class Demo
{
public static void main (String[] args)
{
final Demo app = new Demo ();
app.execute ();
}
private void execute ()
{
// Do stuff here.
}
}
Whoever gave you this assignment is using wrong and confusing terms, because linear programming is something else. But that's a different topic.
Even though this program is not complex, we can introduce some classes by modelling the flow of the program and/or the math operations.
Here is one idea... we could have a class called Operands, that has a method to read the numbers from the input while it prints instructions to the output. Then it stores these two numbers.
So something like this (I am using static class here instead of just class in case you will put this inside your public class addNumbers)
static class Operands {
public final double first;
public final double second;
public Operands(double first, double second) {
this.first = first;
this.second = second;
}
public static Operands readFromIO(InputStream in, PrintStream out) {
Scanner input = new Scanner(in); // Instantiate object input
out.println("Enter number 1"); // Ask the user to enter number 1
double number1 = input.nextDouble(); // Read the first number
out.println("Enter number 2"); // Ask the user to enter number 2
double number2 = input.nextDouble(); // Read the second number
return new Operands(number1, number2);
}
}
Then we could have another class called Calculator, that has a method to set the operands setOperands(Operands operands) and two methods to get the results for the sum and the difference. The methods could be called getSum and getDifference.
static class Calculator {
private double sum = 0;
private double difference = 0;
public void setOperands(Operands operands) {
sum = operands.first + operands.second;
difference = operands.first - operands.second;
}
public double getSum() {
return sum;
}
public double getDifference() {
return difference;
}
}
Then in the main method of the program, we just need to make an instance of the Calculator class and set the Operands on the instance. We read these operators by calling Operands.readFromIO(...). Then we retrieve the sum and the difference from the calculator instance.
So the code in main looks like this
public static void main(String[] args) {
Calculator c = new Calculator();
Operands operands = Operands.readFromIO(System.in, System.out);
c.setOperands(operands);
System.out.printf("Sum = %f\n", c.getSum()); // Print the sum
System.out.printf("Difference = %f\n", c.getDifference()); // Print the difference.
}
This is just one way to do it with some objects.
Another way could be to use an interface called Operation that contains a calculate(Operands operands) method and have 2 more classes Addition and Subtraction implement the interface. Then you would use those two classes to calculate the results.

For loop and if statement within a method

I am new to using java and am having some issues in my java class right now and will be needing help with my specific code. I try to look at others questions on here all the time but it's never exactly what I need. Here are my directions:
Create a Java file called CompoundInterestYourLastName. Write a method called computeBalance() that computes the balance of a bank account with a given initial balance and interest rate, after a given number of years. Assume interest is compounded yearly.
Use a loop to control the iterations through the years in your method.
Your method should return a double value.
In your main method, run the following tests to verify your method is working correctly.
System.out.printf("Your total is $%.2f", computeBalance(1000, .045, 3));
// should return $1141.17
I am using eclipse and my only current error is in the comments. I also want some general tips and let me know if my logic is wrong. It probably is. :D
Here is what I have currently although I have been trying different things:
import java.util.Scanner;
import java.lang.Math;
public class CompoundInterestTidwell {
public static void main(String[] args) {
double compInt = computeBalance(1000, 0.045, 3);
System.out.printf("Your new balance is $%.2f", compInt);
}
// Getting arror for line of code below.
// Error: This method must return a result of type double
public static double computeBalance(int P, double r, int t) {
// Formula for compounding interest
// A = P(1+(r/n))^(n(t))
// The examples to check my math had rate already divided by 100 so I left out r/n.
for(int c = 0; c <= t; c++ ) {
// deleted 'n' from equation because it need to equal 1 anyways.
double compInt = Math.pow(P*(1+r), t);
if (c < t) {
c++;
return compInt;
}
}
}
}
Thanks.
Your function computeBalance doesn't guarantee to return a value, because the only return statement is in an if clause, within a loop (making it two conditions deep).
This is a thing the compiler is warning you about. Basically it scans your code and makes sure that a function declared as double will actually return a valid value of type double and so on.
If you add a return statement at the end of the body in the function (or throw an error) it should compile.
I am not exactly sure what your function does in technical terms, but I've rewritten it so it should return the same value, but should now actually compile.
public static double computeBalance(int P, double r, int t) {
// Formula for compounding interest
// A = P(1+(r/n))^(n(t))
// The examples to check my math had rate already divided by 100 so I left out r/n.
double compInt = 0; // Declare compInt outside the loop.
for(int c = 0; c <= t; c++ ) {
// deleted 'n' from equation because it need to equal 1 anyways.
compInt = Math.pow(P*(1+r), t);
if (c < t) {
c++;
break; // Break instead of return, will immediately
// go to the return statement outside the loop.
}
}
return compInt; // Moved the return statement to outside the loop so
// the function always will return a double.
}

Logic errors within java segment [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
The following Java code segment is supposed to print, as a double, the mean average of a sequence of non-negative integers entered by the user. A negative input signals the end of the sequence (it is not itself part of the sequence). However, the code is not working. I am supposed to find 4 logic errors within this segment. Please help me find the 4 logic errors?? I know one is its integer division.
public class practice
{
public static void main (String[]args)
{
int sum = 0;
int numVals = 0;
Scanner scan = new Scanner(System.in);
System.out.println(("enter next integer (-ve to stop): "));
int i = scan.nextInt();
while (i > 0)
{
sum = sum + i;
numVals = numVals + 1;
}
System.out.println("average = " + sum / numVals);
}
}
I won't give you full solution, however, it'll be helpful if you pay attention to:
int division as you said,
does your loop terminate? Is someone changing i? Hint: No, and
how do you ask for input? Do you see any loops there? Why it's asking you for only one input?
Not an error, but pay attention to Java Naming Conventions, class name should begin with upper case
Since the homework is for logic errors, I could point out other errors.
the class name should start with upper case letter.
the println doesn't need two nested parenthesis.
the sum should be a long rather than an int to avoid overflows.

The correct Recursive backtracking algorithm?

My assignment is to find a way to display all possible ways of giving back change for a predetermined value, the values being scanned in from a txt file. This must be accomplished by Recursive Backtracking otherwise my solution will not be given credit. I will be honest in saying I am completely lost on how to code in the appropriate algorithm. All I know is that the algorithm works something like this:
start with empty sets.
add a dime to one set.
subtract '10' from my amount.
This is a negative number, so I discard that set: it is invalid.
add a nickel to another (empty) set.
subtract '5' from my amount.
This equals 2; so I'll have to keep working on this set.
Now I'm working with sets that already include one nickel.
add a dime to one set.
subtract '10' from my amount.
This is a negative number, so I discard that set: it is invalid.
repeat this with a nickel; I discard this possibility because (2 - 5) is also negative.
repeat this with a penny; this is valid but I still have 1 left.
repeat this whole process again with a starting set of one nickel and one penny,
again discarding a dime and nickel,
and finally adding a penny to reach an amount of 0: this is a valid set.
Now I go back to empty sets and repeat starting with a nickel, then pennies.
The issue is I haven't the slightest clue on how or where to begin, only that that has to be accomplished, or if any other solutions are apparent.
This is my code thus far:
UPDATED
import java.io.*;
import java.util.*;
import java.lang.*;
public class homework5 {
public static int penny = 1;
public static int nickle = 5;
public static int dime = 10;
public static int quarter = 25;
public static int halfDollar = 50;
public static int dollar = 100;
public static int change;
public static void main(String[] args) throws FileNotFoundException {
ArrayList<Integer> coinTypes = new ArrayList<Integer>();
Integer i;
File f = new File (args[0]);
Scanner input = new Scanner(f);
input.nextLine();
while(input.hasNextInt()) {
i = input.nextInt();
coinTypes.add(i);
}
change = coinTypes.get(coinTypes.size()-1);
coinTypes.remove(coinTypes.size()-1);
System.out.println("Found change"); //used for debugging
System.out.println("Change: " + change);
System.out.println(coinTypes);
}
boolean findChange(int change, List<Integer> coinTypes,
List<Integer> answerCoins) {
if(change == 0) {
return true;
}
if(change < 0) {
return false;
} else {
for(Integer coin : coinTypes) {
if(findChange(change - coin, coinTypes, answerCoins)){
answerCoins.add(coin);
return true;
}
}
List<Integer> answer = new ArrayList<Integer>();
boolean canFindChange = findChange(change, coinTypes, answer);
if(canFindChange) {
System.out.println(answer);
} else { System.out.println("No change found");
}
return false;
}
}
Here is the input file that I scan in
java homework5 hwk5sample1.txt
// Coins available in the USA, given in cents. Change for $1.43?
1 5 10 25 50 100
143
OUTPUT
Found change
Change: 143
[1, 5, 10, 25, 50, 100]
So using the numbers in my coinTypes ArrayList, I need a generic code algorithm to show all possible ways of receiving, for example, 143 ($1.43) back in change using the coins in the file with all pennies being the last way to show it.
Please do not think I want you to write me the algorithm, I am simply wanting help writing one otherwise I will learn nothing. Thank you all for any answers or help you can give it means a lot to me! Please let me know if i missed anything or you need more info
The example that you walk through seems to be mostly correct. The only error is this: again discarding a dime and nickel, which should be again discarding a *penny* and nickel (but I think that's just a typo.)
To write a recursive backtracking algorithm, it is useful to think of the recursive call as solving a subproblem of the original problem. In one possible implementation of the solution, the pseudocode looks like this:
/**
* findChange returns true if it is possible to make *change* cents of change
* using the coins in coinTypes. It adds the solution to answerCoins.
* If it's impossible to make this amount of change, then it returns false.
*/
boolean findChange(int change, List<Integer> coinTypes, List<Integer> answerCoins) {
if change is exactly 0: then we're done making change for 0 cents! return true
if change is negative: we cannot make change for negative cents; return false
otherwise, for each coin in coinTypes {
// we solve the subproblem of finding change for (change - coin) cents
// using the recursive call.
if we can findChange(change - coin, coinTypes, answerCoins) {
// then we have a solution to the subproblem of
// making (change - coins) cents of change, so:
- we add coin to answerCoins, the list of coins that we have used
- we return true // because this is a solution for the original problem
}
}
//if we get to the next line, then we can't find change for any of our subproblems
return false
}
We would call this method with:
List<Integer> answer = new ArrayList<Integer>();
boolean canFindChange = findChange(change, coinTypes, answer);
if(canFindChange) {
System.out.println(answer); // your desired output.
}
else {
System.out.println("Can't find change!");
}

exponential growth in java, return type array of doubles

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.

Categories