My program is supposed to run a formula and print out the end product when a counter reaches 100,200,500,and when a variable hits a certain value. Currently it prints out
Exception in thread "main" java.lang.ArithmeticException: / by zero
Which I understand is because before the counter takes effect and bumps up the variable it attempts to divide by zero which causes that. When I do change the variable it stops at 100 and prints out "The value of π at 100 is: 0.0".
Here's the code:
int i = 1;
int counter = 0;
double pi = 4/((2*i)*(2*i+1)*(2*i+2));
while(counter <= 100 ){
i++;
counter ++;
if(i==100){
System.out.println("The value of \u03C0 at 100 is: "+ pi);
}
if (i==200){
System.out.println("The value of \u03C0 at 200 is: " +pi);
}
if (i==500){
System.out.println("The value of \u03C0 at 500 is:"+pi);
}
if(pi==3.14159 ){
System.out.println("The number of iterations to get to 3.14159 is "+counter+". \u03C0 = 3.141599074");
}
}
Your logic has some problems. Have you followed your code through with a debugger? If you look at your code,
int i = 1;
int counter = 0;
double pi = 4/((2*i)*(2*i+1)*(2*i+2));
happens once, before the while loop actually changes i. Move pi into the while loop to update pi with a new i. Debuggers are your friend.
Another place where a debugger would be your friend would be in the while loop proper. Follow that through and see what happens when your logic approaches your testing conditionals. Your first excitement I predict will be around counter = 99 and the next couple of loops through, or not :)
You might want to consider some if-else blocks for your multiple tests, or you could also use a switch statement for your counter tests.
Try
...
for (counter = 1; counter <= 500; counter++, i++) {
double pi = (double) 4/((2*i)*(2*i+1)*(2*i+2));
if (counter % 100 == 0) {
System.out.println("The value of \u03C0 at " + counter + " is: "+ pi);
}
if(pi == 3.14159 ){
System.out.println("The number of iterations to get to 3.14159 is "+counter+". \u03C0 = 3.141599074");
}
}
Related
Considering two variables:
"n" is any arbitrary value.
"i" is the number of times a value is increased in a sum before it reaches the value of "n".
So for instance if the value n = 344 is chosen, then i = 26 because:
26 + 25 + 24 + ... + 3 + 2 + 1 = 351
26 is how many times the variable "i" gets added together in a descending order before it either is equal to n = 344 or the first time it surpasses.
public class Trstuff{
public static void main (String [] arg) {
int n = 4;
int i = computeIndex(n);
System.out.print(i);
}
public static int computeIndex(int n) {
int i = 1;
int sum = 0;
for(i = 1; sum <= n; i++) {
sum = sum + i;
}
return i;
}
}
My goal is to choose any "n" value and then have the program return the variable "i" to me.
As my program stands, I thought it should be correct, but somehow it's not. Here is the example with n = 4.
The result should be that "i = 3" because:
1 + 2 = 3
1 + 2 + 3 = 6
So the ascending value of "i" in the loop is added 3 times before the loop supposedly should stop because of the expression "sum <= n" in the loop.
However, when I run the program it returns the value 4 instead. I simply cannot figure out what is wrong and why my program gives me 4 instead of the correct answer, 3?
Read the for loop as follows:
for every value of i while sum smaller or equal to n, add i to sum and increment i
The last part of the line and increment i is executed after the sum of sum + i, but before the next check which checks if sum is smaller or equal to n, with as result that i always is one larger than expected.
The solution could be to use a different exit (different solutions exist):
public static int computeIndex(int n) {
int i = 1;
int sum = 0;
while true {
sum = sum + i;
if sum<n {
i++;
} else break;
}
return i;
}
the sum of p consecutive integers starting at 1 is p*(p+1)/2
so basically you need to solve x^2+x-2*n = 0, with solution
x = 0.5*(sqrt(1+8n)-1)
This question already has answers here:
What is a debugger and how can it help me diagnose problems?
(2 answers)
Closed 4 years ago.
I am coding this simple pi calculator for my Java class as a part of us learning about basic loops and it seems like everything is OK except the values printed for pi is infinity when it should be 3.14...something according to the number of iterations. I read that this could be maybe related to a double variable dividing by 0 and it's giving a weird infinity output instead of a normal Java runtime exception?
Here's my code:
package lab05;
public class Lab05 {
public static void main(String[] args) {
// Variable declarations
double pie = 3;
double savepie = 0;
double term = 0;
double savei = 0;
double sign = 1;
boolean isRangeFound = false;
int i;
// For loop
for (i=0; i <= 1000;) { // Only up to 1000 iterations before loop must end.
term = (sign * 4) / ((2*i) * (2*i+1) * (2*i+2));
pie = pie + term;
sign = (-1 * sign);
if (isRangeFound==false && (pie >=3.14159265 & pie < 3.14159266)) {
savepie = pie;
savei = i;
isRangeFound = true;
}
if (i == 200||i == 500||i == 1000) {
System.out.print("The value of \u03C0 is: ");
System.out.printf("%.10f",pie);
System.out.print(" when i = " + i);
System.out.println(" ");
}
i++;
}
// Final output statement
System.out.println ("The number of iterations to get to 3.14159265 is " + savei + ".");
System.out.printf("\n\u03C0 = %.10f",savepie);
System.out.println(" ");
}
}
Here's my output in Netbeans:
The value of π is: Infinity when i = 200
The value of π is: Infinity when i = 500
The value of π is: Infinity when i = 1000
The number of iterations to get to 3.14159265 is 0.0.
π = 0.0000000000
BUILD SUCCESSFUL (total time: 0 seconds)
Here's the link to the instructions that I should follow with a Visual Logic flowchart that I tried to follow to the T. Thanks.
https://www.dropbox.com/s/2m26a32afedk9yu/Lab05%20Assignment%281%29.pdf?dl=0
You need to start your loop when i=1? The way you have it, when i=0, then term will be infinity (due to the divide-by-zero), and so pie will be infinity as well.
I'm trying to find the factorial of 9 down to 0, only using one while loop, but my idea isn't outputting a value.
I figured out the way to do it using two while loops:
int i;
count = 9;
while (count >= 0){
value = count;
i = count-1;
while (i > 0){
value = value * i;
i--;
}
System.out.print(value + ", ");
}
This worked but I've tried to change it to use only one while loop and got this:
int i;
for (count = 9; count < 0; count--){
value = count;
i = count-1;
while (i > 0){
value = value * i;
i--;
}
System.out.print(value + ", ");
}
I'm not completely sure if I'm using the for statement correctly but I think I am, or at least I think it should output something so I can debug it.
Could someone give me a hint in the right direction?
This will give you all the factorials from 9 down to 1 :
int i=1;
int value=1;
String res = "";
while (i <= 9){
value = value * i;
res = value + ((i>1)?",":"") + res;
i++;
}
System.out.print(res);
Output :
362880,40320,5040,720,120,24,6,2,1
Perhaps it's cheating, since I'm calculating the factorials in ascending order from 1! to 9!, but I'm reversing the order of the output in order to get the required result.
Edit :
If you also want 0! to be printed, a small change can do the trick :
int i=1;
int value=1;
String res = "";
while (i <= 10){
res = value + ((i>1)?",":"") + res;
value = value * i;
i++;
}
System.out.print(res);
Output :
362880,40320,5040,720,120,24,6,2,1,1
First, the reason why your second loop doesn't work is that you have the wrong condition in the for. The condition in the middle is one that will cause the loop to continue, not to stop. So what you were saying was "start from 9, and work while the number is less than 0". But of course, your number is greater than zero to begin with.
Second, I believe using a for loop is a little bit of cheating, because a for loop is just a specific case of while loop.
Now to the problem of the factorial itself. You know that a factorial n! is defined as (n-1)!*n.
The basic loop for calculating one specific factorial is:
int n = 5;
int factorial = 1;
while ( n > 0 ) {
factorial *= n;
n--;
}
System.out.println( "Factorial is: " + factorial );
This will give you the factorial of five. But it's not exactly based on the formula we are talking about. There is another way to calculate it, starting from 1:
int n = 5;
int factorial = 1;
int count = 1;
while ( count <= n ) {
factorial *= count;
count++;
}
System.out.println( "Factorial is " + factorial );
The interesting part about this way of doing it is that in every stage of the loop, factorial is actually the value (count-1)! and we are multiplying it by count. This is exactly the formula we were talking about.
And the good thing about it is that just before you did it, you had the value of the previous factorial. So if you printed it then, there you'd get a list of all the factorials along the way. So here is a modified loop that prints all the factorials.
int n = 9;
int factorial = 1;
int count = 0;
while ( count < n ) {
System.out.println( "Factorial of " + count + " is " + factorial );
count++;
factorial *= count;
}
System.out.println( "Factorial of " + n + " is " + factorial );
Note that I modified it a little more so that it will work with zero. The factorial of zero is a special case so we shouldn't multiply by zero - that will make all the factorials wrong. So I changed the loop to multiply only after I increase count to 1. But this also means that you have to print the final factorial out of the loop.
Just first assign value=i, then run your loop. You can get the factorial with only while loop.
Important: Because n!=n*(n-1)!, therefore, i-- should must be perform before value = value * i.
public static void main(String args[]) {
int value=5;
int i=value;
while (i > 1){
i--;
value = value * i;
}
System.out.print(value);
}
Update: If you want to count factorial of 0 to 9, then use this code: (It includes factorial of 0 also)
public static void main(String args[]){
int countLowest=0;
int countHighest=9;
int value=1;
while (countLowest<= countHighest){
if(countLowest==0)
value = value * (countLowest+1);
else
value=value*countLowest;
countLowest++;
System.out.println("Factorial of "+(countLowest-1)+" is "+value);
}
}
Result:
Factorial of 0 is 1
Factorial of 1 is 1
Factorial of 2 is 2
Factorial of 3 is 6
Factorial of 4 is 24
Factorial of 5 is 120
Factorial of 6 is 720
Factorial of 7 is 5040
Factorial of 8 is 40320
Factorial of 9 is 362880
count = 9;
sum=1;
while (count >= 1){
sum*=count;
--count;
}
System.out.print(sum);
it will give you 9!=362880
I am writing a program to print out a user inputed integer into binary form.
When I run it and input, say the number 5, it crashes and gives me the error:
java.lang.ArrayIndexOutOfBoundsException: 30
at PrintBinaryDigitsFixed.main(PrintBinaryDigitsFixed.java:27)
i.e the line "digits[counter] = number % 2;"
Why am I getting an out of bounds exception? It should assign the remainder to the first element then move on to the second shouldn't it?
I feel like I'm making a glaringly obvious mistake but I can't tell what it is
final int MIN = 0;
final int MAX = (int) (Math.pow(2, 30) - 1);
int[] digits = new int[30]; //array to hold the digits
int number = readInput
("Enter an integer from " + MIN + " to " + MAX, MIN, MAX);
int counter = 0;
int modNumber = 2;
while(modNumber / 2 != 0)
{
digits[counter] = number % 2;
modNumber = number / 2;
counter++;
}
System.out.print(number + " in binary form is ");
listBackwardsFrom(digits, counter);
Thanks
You never change number in your loop, and you assign modNumber = number / 2 in the loop, so from the second iteration onward modNumber is a constant (for most of the first iteration it's 2, but then you assign number / 2 to it); if you reach that point at all, you'll stay there. So the loop continues until counter reaches 30, at which point digits[counter] throws the exception.
So I'm trying to make a program where it averages out your golf scores. I edited a standard averaging calculator to make it work:
import java.util.Scanner;
public class Test {
public static void main(String args[]){
Scanner input = new Scanner(System.in);
int total = 0;
int score;
int average;
int counter = 0;
while (counter >= 0){
score = input.nextInt();
total = total + score;
counter++;
}
average= total/10;
System.out.println("Your average score is "+ average);
}
}
But when I enter scores, I can keep entering infinite scores and it never averages them. It just keeps expecting another score. I know it has something to do with this line:
while (counter >= 0){
but I'm not sure what to do so it works right.
You never find a way to break out of the loop:
while (counter >= 0){
score = input.nextInt();
total = total + score;
counter++;
}
will loop 2 billion times (no I'm not exaggerating) since you don't have another way to break out.
What you probably want is to change your loop condition to this:
int score = 0;
while (score >= 0){
This will break out when a negative score is entered.
Also, you have an integer division at the end. You want to make floating-point, so change the declaration to this:
double average;
and change this line to this:
average = (double)total / 10.;
You need some way to beak out of the loop. For example, entering -1:
int score = input.nextInt();
if (score < 0) { break; }
total += score;
You also seem to have a couple of errors in the calculation of the average:
Don't always divide by 10 - use the value of counter.
Use floating point arithmetic. If you need an int, you probably want to round to nearest rather than truncate.
For example:
float average = total / (float)counter;
You have to specify the counter value, the default value is 0, so the condition in the while is always true, so you will go in an infinite loop.
while (true) {
score = input.nextInt();
if (score == 0) {
break;
}
total = total + score;
counter++;
}
Now your program will realize you're done entering scores when you enter the impossible score 0.