variable "double" giving me error, and program is doing infinte loop? - java

I need to ask the user how many times he want to put his notes, then do a loop
how many times he need to put his note and finally calculate the moyenne, but im putting that double a = a+n; means that it calculate the notes number, and finally in s.o.p, im putting to divide the notes number on how much he asked first.
java is giving me error, any help?
Here is my code:
package minmax;
import java.util.Scanner;
public class MinMax {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int x, y, z;
System.out.println("Combien de notes vous avez? ");
x = in .nextInt();
for (y = 0; y < x; y++) {
do {
System.out.println("Mettez votre note :");
z = in .nextInt();
}
while (z < 20 || z > 0); {
double a = a + n;
}
}
System.out.println("Votre moyenne est : " + (a / x));
}
}

Fixes and suggestions:
Variables have to be initialized first (strictly without referring themselves), "updates" (referring themselves, the a=a+something, a++, a+=something kind of things) can happen only afterwards
In Java you usually bring variable declaration and usage close to each other, and remember that you can declare and initialize a variable in a single statement.
In the case of using a do-while loop, do not bracket+indent lines following the while(...);, such following lines are on the same level as the do-while loop itself
Whitespace preceding . looks strange, unless you break an expression into several lines
Put them together:
package minmax;
import java.util.Scanner;
public class MinMax {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Combien de notes vous avez? ");
int x = in.nextInt();
double a = 0;
for (int y = 0; y < x; y++) {
int z;
do {
System.out.println("Mettez votre note :");
z = in.nextInt();
}
while (z < 0 || z > 20);
a = a + z;
}
System.out.println("Votre moyenne est : " + (a / x));
}
}
(Plus a=a+n became a=a+z for the obvious reason of z containing the number from the user, and the comparison directions had to be swapped - assuming that you want numbers between 0...20)

Simple:
double a = a + n;
You can't define a variable and initialize it with itself.
Meaning: it is not possible to declare a, but also assign a value to a that requires a.
In other words: the code you wrote really makes no sense. Maybe you should simply put: double a = 0 somewhere above that statement, and then only do: a = a + n further down.
And of course: also use real names. a, n, those names mean nothing. Use something that tells the human reader about the intent of these variables.

Related

How to write a java program that computes the value of e^x

I'm trying to figure out how to answer this question for my Java class, using only while loops:
Write an application that computes the value of mathematical constant e^x by using the following formula. Allow the user to enter the number of terms to calculate. e^x = 1 + (x/1!) + (x^2/2!) + (x^3/3!) + ...
I can't figure out how I would do this without also asking the user for a value for x? Below is the code that I created for calculating x with the number of terms and just the number 1 for the exponent of each fraction. Any help is appreciated
import java.util.Scanner;
public class FactorialB {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int counter = 0;
float answer = 0;
System.out.print("Enter number of terms: ");
int n = scanner.nextInt();
while (counter < n) {
double factorial = 1;
int factCounter = counter;
while (factCounter > 1) {
factorial = factCounter * factorial;
factCounter--;
}
answer += 1 / factorial;
counter++;
}
System.out.printf("e = %f%n", answer);
}
}
Firstly the question you seem to be asking:
There is no way to make a program that will give e for a specific number unless you ask the user for that number.
However it might be that they just want you to make a method that provides the solution (if it were called) independently of user input. (because the code to get user input isn't very interesting, what is interesting is how you reach the result).
An alternative way to provide x and n are for instance passing them as commandline arguments. (args[] in your main would be a way to provide them)
I would create a separate method that receives x and n that covers the main calculation:
e^x = 1 + (x/1!) + (x^2/2!) + (x^3/3!) + ...
And separate methods that cover 'calculating a single term (x^1/1!), (x^2/2!), etc' and 'factorialize(n)'
public void calculatePartialE_term(int x, int n) {
if (n == 0) {
return 1; // this will allow you to use a while loop, covers the n = 0 case
} else {
// removed the implementation, but basically do
// x^n/n! here for whatever value of n this term is calculating.
}
}
public int calcualteNFactorial(int n) {
// assert n >= 1
// use a while loop to calculate n factorial
}
the benefit of doing this in a separate methods is that you can prove / verify the working of calculatePartialE_term or calcualteNFactorial independently of one another.
now you can simply write a while loop based on x and n to do something like
public int calculateE_to_x(int x, int n) {
int current = 0;
int sum = 0;
while (current <= n) {
sum += calculatePartialE_term(x, current);
}
}
I wouldn't expect your teacher to expect you to show code that handles user input but even if that is the case it will be easier for them to verify your work if the actual work (of calculating) is done in a separate method.

Trying to multiply two numbers together using only addition

so I'm trying to make a very simple program but I think I am over thinking it. I want to multiply two numbers together without using multiplication, only addition. I know I will have to add X to itself Y times in order to achieve this, but the way my for-loop is now, it simply adds X to itself once and never again. I know that this algorithm is in the wrong place, but I am unsure where else to put it or what else to do. Any help would be appreciated!
import java.util.Scanner;
public class multiply {
public static void main(String[] args) {
int x = 0;
int y = 0;
int answer = 0;
Scanner scan = new Scanner (System.in);
System.out.println("Please enter a value for x");
x = scan.nextInt();
System.out.println("Please enter a value for y");
y = scan.nextInt();
for(int i = 0; i < y; i++){
answer = x+x;
}
System.out.println(x + " multiplied by " + y + " equals " + answer);
}
}
This is incorrect
answer = x+x;
should be:
answer = x + answer;
or
answer += x
Your problem is that you are reassigning in each iteration of , you actually need to do like this
Try this
answer += x;

Simulating Logarithms by repeated Integer division

I'm trying to write a program that simulates logarithms by repeated integer division. A user inputs a base number and a value X that they want to take the log of. The code runs through a loop and increments a count after each successive division. The code is set to stop after the value of X gets smaller than the base because I'm only using int type variables.
This code works fine for some numbers and bases but for others it gives the wrong value. It does " log_2(64) is 6 " however it doesn't do log_10 of 100. It gives a count of 10.
public static void main(String[] args) {
Scanner inScan = new Scanner(System.in);
int base;
int X;
int response;
int n=0;
do{
System.out.println("Java Lab 3 Logarithm Solver.");
System.out.println("Please enter a base > 1");
base = inScan.nextInt();
System.out.println("Please enter a number, X>0.");
X = inScan.nextInt();
if (X > 0 && base > 1){
System.out.println("Logarithm base " +base+ " of " +X+" is ");
for ( ; X>base ;n++){
X=(X/base);
}
System.out.println(n);
} else {
System.out.println("Invalide numbers.");
}
System.out.println("Would you like to go again? Press 1, press 0 to quit");
response = inScan.nextInt();
} while (response == 1);
}
}
You are declaring n as a global variable; I suspect that if you check your tests, this algorithm works only the first time through every time you compile and run it. Instead of having n as global, declare it in your for loop like
for(int n = 0; X < base; n++)
since it looks like you need the value of n later, I suggest having a variable with a wider scope, perhaps declared in the do-while loop, to store the n in, like
do
{
int numberOfTimesThroughLoop = 0;
...
for(...)
{
x = x/base;
numberOfTimesThroughLoop = n;
}
}
as a side note, most of the time variables (even single letter variable, like your 'X') being with a lower case character

Reason for error: var might not have been initiazed

The user should enter the values to x and y, and if x is greater than 5 and and when y= 0 , then z should be equivalent to x+y. However, when I compile it gives me an error saying that z might not have been initialized.
import java.util.Scanner;
public class add {
public static void main(String[] args ){
Scanner input = new Scanner (System.in);
System.out.print("Enter a value for x");
int x = input.nextInt();
System.out.print("\nEnter a value for y ");
int y = input.nextInt();
int z;
if (x > 5){
if (y == 0)
z = x + y;
System.out.println("The answer is " + z);
}
else
System.out.println("The answer is only" + x);
}
}
There is an execution path where z doesn't get initialized, but you attempt to print it. If x is greater than 5, but y isn't 0, then z is not initialized, but you refer to z when printing it.
Use braces to create an inner block for your inner if statement, so z is only referenced if it's initialized:
if (x > 5){
if (y == 0) {
z = x + y;
System.out.println("The answer is " + z);
}
}
Also, proper indenting helps to identify visually what's part of a block and what's not.
Your 'if' statement is misleading:
if (y == 0)
z = x + y;
What if y != 0? In that case, z is not initialized.
The next line
System.out.println("The answer is " + z);
doesn't apply to the y==0 statement, as you don't have braces {}.
You probably meant to write something like:
if (x > 5) {
if (y == 0) {
z = x + y;
System.out.println("The answer is " + z);
}
}
Note the "{" after the if statement.
As you are not using braces for if condition, your z will not initialized.
To solve such kind problems always keep in mind that if you are calculating something with integer variable do initialize them with some value (here, 0 is the best).
Then you can access that variable anywhere in the code without any initialization error.
To rid of this problem, you have two ways
One way:
just simply initialize your z variable like:
int z=0;
Second way:
Try to put braces for if condition like:
if (y == 0){
z = x + y;
System.out.println("The answer is " + z);
}
You need to assure the compiler that z will get a value no matter what.
You may want to assign it a default value when declaring it.
Something along these lines:
int z = 0; // just an example
int z has no value, try the code at the bottom then give it a 0 or input.nextInt();
int z = 0;
or
int z = input.nextInt();

run an entire program a certain number of times via input

So my current code effectively runs the "random walk" problem and then uses the pythagorean theorem to figure out actual distance in units walked but now I need to modify my program so that I can do a certain number of trials of said walk and then calculate the mean square distance. Not really looking for just an answer, I really also need an explanation so that I may be able to learn and recreate, I think I just need another while loop but I'm not sure where to put it.
import javax.swing.JOptionPane;
String a = JOptionPane.showInputDialog("Enter # of footsteps.");
int z = Integer.valueOf(a);
int x= 0; // starting x position
int y= 0; // starting y position
double r;
int counterZ = 0;
if (z < counterZ ){
System.out.println("Error");
}
while ( z > counterZ){
r=Math.random();
if (r<0.25){
x=x+1;
}
else if(r > .25 && r<0.50){
x=x-1;
}
else if(r > .5 && r<0.75){
y=y+1;
}
else{
y=y-1;
}
counterZ = counterZ + 1;
System.out.println("(" + x + "," + y + ")");
}
System.out.println("distance = " + round(sqrt((x*x)+(y*y))));
Correct me if i am wrong, My understanding is that you want to run the walk cycle a certain number of times and calculate the average distance walked on the sum of the distance of the cycles. If that is the case, then all you have to do is this,
int noc = Integer.valueOf(JOptionPane.showInputDialog("Enter # of cycles: "));
String a = JOptionPane.showInputDialog("Enter # of footsteps.");
int z = Integer.valueOf(a);
int sum = 0;
double avg = 0.0;
for(int i=0;i<noc;i++) {
sum+= randomWalk(z);
}
avg=(double)sum/noc;
System.out.println("the average distance walked in "+ noc + "cycles is "+avg);
the randomWalk() method should be like the following if you are calling it from the main method without creating an object for the class randomWalk() is residing in.
public static int randomWalk(int z) {
//place your code here, starting from the `int x=0;`
//at last instead of printing the distance walked use the following code
return (int) Math.round(Math.sqrt((x*x)+(y*y)));
}
you have also missed to call the methods round() and sqrt() using there class Math. I have correct them for you as Math.round() and Math.sqrt(). without the class name you will get a compiler error like Symbol not found. i also assume you have imported the java.lang.Math class into your program.
I'd suggest starting by indenting the code tidily so that it is more understandable.
To address your question directly, I'd suggest modifying the program so that the substance of the progam is embedded in a method (you might call it randomWalk(), perhaps) and the main() method just calls randomWalk() and does the I/O. Having done that, it would be very easy to modify the main() method to call randomWalk() many times from within a while loop.

Categories