While statement trouble Java - java

While I was working on a program that simulates a dice, I encountered a problem.
This is the code I wrote (I know it is not good programing at all but I'm learning). It works and of course I know that there is unnesecary parts in it, but is not the problem.
double x ;
String z ;
x = Math.random() ;
z = Double.toString(x) ;
z = z.substring(2, 3) ;
while (x>6 || x<1) {
x =Math.random() ;
z = Double.toString(x);
z = z.substring(2, 3) ;
x = Integer.parseInt(z );
}
z = Double.toString(x );
z = z.substring(0, 1) ;
JOptionPane.showMessageDialog(null, "Antal prickar: "+z);
The problem is that saw that I erlier had an if statement in the while loop and it worked a couple of weeks ago and now when I rewrote the code it is not working.
double x ;
String z ;
x = Math.random() ;
z = Double.toString(x) ;
z = z.substring(2, 3) ;
while (x>6 || x<1) {
if (x>6) {
x =Math.random() ;
z = Double.toString(x);
z = z.substring(2, 3) ;
x = Integer.parseInt(z );
}
}
z = Double.toString(x );
z = z.substring(0, 1) ;
JOptionPane.showMessageDialog(null, "Antal prickar: "+z);
Can anyone explain why it is not working because I should be able to put the if statement inside the while loop without it giving me errors right?

Assuming your previous code was working (and skipping comments on style etc.) the main problem seems to be the added if-statement.
Consider the case where x = 0:
while( x > 6 || x < 1) will run since the condition is satisfied (x is smaller than 1).
if(x > 6) is not satisfied though (x is not greater than 6) and thus x will never be updated, resulting in an endless loop.
Btw, I'd not use Math.random() but rather create a new instance of Random and then call nextInt(6) + 1 to get a random integer between 1 and 6 (both inclusive):
Random rand = new Random(); //you might want to store this elsewhere and reuse the instance
int dice = rand.nextInt(6) + 1; //done, random integer between 1 and 6

It seems you are using java.lang.Math.random() to generate a number between and 1 and 6. As that random() call returns a value normalized in the 0.0 to 1.0 interval, you choose the first decimal as your candidate value and in the case it is off limits, you repeat the random() call to get a new candidate number.
In the second snippet you sent post (the one you say is not working), the formatting shows that the while loop only contains the if statement, and this statement will only do something if x > 6, but x will never be over 6 as the value is between 0 and 1.
You might be missing this line in the first block before the while loop:
x = Integer.parseInt(z );
And the if condition within the loop shall be removed.
Edit: to produce a random value between 1 and 6 the simpliest piece of code I can thing about is:
new java.util.Random().nextInt(6) + 1

Related

for X terms, find P = (2! /1) + (!4/2) - (!6/3) ... and my code works for every test but one

For this formula:
I had to make a method to automate it, and I've received 4 examples to try it out.
x = 1 > p = 2
x = 3 > p = -226
x = 4 > p = 9854
however, when I insert 11 the answer should be 3.0198773447 and I receive -1.78316945E8 instead :/
here is my code:
System.out.println("Insira o numero: ");
int x = input.nextInt();
int fat = 1;
int contador = 0;
int contador1 = 0;
double p = 0;
for(double i = 1; i <=x; i++){
fat = 1;
contador++;
contador1 = contador* 2;
for(double j = 1; j <= contador1; j++){
fat *=j;
}
if(contador <=1){
p += fat / contador;
}
if(contador % 2 ==0 && contador > 1){
p += fat / contador;
}else if( contador % 2 != 0 && contador > 1){
p -= fat / contador;
}
}
System.out.println(p);
If you type in 11, that means contador1 will become as high as 22 (you will loop 11 times, every loop you first increment contador, and contador1 is twice that, so, 22. In other words, you'll end up having to calculate 22!.
The int type does not hold any arbitrary integer. It can only hold integers between -2^31 and +2^31-1. If you try to go beyond those bounds, it just loops around. Witness it in action:
int x = Integer.MAX_VALUE; // a constant representing 2^31-1.
int y = x + 1;
System.out.println(x);
System.out.println(y);
// Prints: 2147483647
// -2147483648
Where'd that minus come from? That's that whole 'loops around' thing. 22! is much lager than than this upper bound. Hence, your code doesn't work and it also explains why your algorithm tosses a negative number in there.
You could choose to use long instead which can hold it, but long, too, has limits - 2^63-1 to be precise. You could use double which goes ever further (up to about 1e308 which is a lot more than 2^63), but doubles are not accurate and the lack of accuracy gets worse as you move further away from 0. Past 2^53 or so, the distance between 2 representable numbers in the double range is more than 1, meaning, +1 no longer does anything (all operations on double values are rounded to the nearest representable double after every operation).
More generally trying to do 'math' on really large numbers is a non-trivial affair, and your basic + and / can no longer get the job done. Look up the API of BigDecimal which guarantees you perfect accuracy at the cost of, naturally, performance. You could use that, and get perfect answers. Though it'll take a while.

Tricky basic java operations [duplicate]

This question already has answers here:
How do the post increment (i++) and pre increment (++i) operators work in Java?
(14 answers)
Closed 3 years ago.
I got these 2 different codes in Java that I can't understand how they produce these specific outputs.
They seemed to work in 2 different logic and I can't figure it out!
int a = 5;
int b = 4;
a -= (b++) + ++a; // For more confusing results replace -= with += and see how the logic changes.
System.out.println(a); // Output: -5
and
int c = 8;
c += ++c;
System.out.println(++c); // Output: 18
How does each situation work and how are they producing these specific outputs?
The major difference here is what post and pre increment are. These determine whether the value is increased before evaluation, or afterward.
Here is how the first case breaks down mathematically:
a = 5 - (4 + 6), which reduces to -5.
Note that a is increased from ++a AKA preincrement before the math is done, however b is calculated as 4. Another thing to note is the a used from the -= uses the original a value, regardless of post or pre increment.
The second equation reduces to this mathematically:
c = 8 + 9 which reduces to 17.
The output prints 18 because your System.out.print(++c) increments it one more time before output due it being preincrement. Note if the print statement used c++, the value would print to 17.
The chart for operator precedence can be found here. Note that assignment has lower precedence than the unary/postfix operators.
It's all about the Operator Precedence in Java. Check that table and figure out which operation takes place first and which last.
It is equivalent to:
int a = 5;
int b = 4;
a -= (b++) + ++a; // => 5 -= (4) + 6
int c = 8;
c += ++c; // => 9 += 9
The main diff is thet:
++a and ++c increments the value and immediately returns it.
b++ returns the value and then increments it.
There is a difference in the order of ++. While both increase the variable, ++a will pass the original value to the operation chain your in middle of; while a++ would pass the new value. So for your first example:
++a --> a is now 6; but the equation is using 5:
a -= (b++) + 5;
b++ --> b is now 5;
a -= 5 + 5;
a -= 10;
? = 5 - 10;
a = a - 5 + 5;
a = 5 - 5 + 5;
a = -10;
(You should have enough to trace the second example).
For a list of operations try this. Some more increment examples are here.
A minimal example is `
int x=3,y=3;
x += ++x;
y+= y++;
at the x x is 7 and y is 6. Precedence alone is not enough to explain the behaviour. Using precedence the second line would be x += (++x), i.e. increment x and return its value, (x is now 4); next we have x+=4 which would return 8.
Instead, it seems better to treat x += w as a short hand for x = x + w, this rewriting happens before evaluation. In our case the rewriting is x = x + ++x interpreted as x = (x + (++x)). So interpreted as
x = ( 3 + (++x))
x = ( 3 + 4 ) x is 4
x = 7 x is 7
A simlar system works to the y equation giving y = 6 at the end.

Java math equation solver [not normal equations]

I need a method in java which returns a solve for an equation this equation without code is like this :
get a number(Z)
and an angle(C) in radians
then find the value of X which is the solution for this equation:
a = Integer( z*cos(c) ) // temp must be integer
//now we have the value of a
// we put it in b
b = a
//now we look for the value of x that solves this equation
b =? Integer( X/cos(C) ) // X also must be integer
X = ?? // we must get X the solves the equation above
Example: consider
Z = 15
C = 140 // full angles will be casted ..it will be rooted to ~-0.0629*PI
temp = Integer( 15*cos(140) // -2.96 )
temp <-- -2 //after parsing to integer
-2 = Integer ( X )/cos(140)
what is X ?
I tried to implement this method in java but most of the times it stuck finding a result
this code doesn't find a direct solution like i want it tests numbers till it gets it but in many of times it can't find a result and keeps looping to the infinity . Also it is so slow in finding the result and i call that function more than 500,000 times in the program
int Rounding(int z, int c){
int offset = 20 ;
int x;
int test = (int) ( z*Math.cos(c) - offset );
int solution;
while(true){
solution = (int) ( test/Math.cos(c) );
if(solution == z){
x = solution;
break;
}else{
test++;
}
/*
if(solution > z){
offset ++;
solution = (int) ( z*Math.cos(c) - offset );
}
*/
}
return x;
}
/*Note : the function will return x only when it solves this : */
int returned_Z = (int) ( x/Math.cos(c) )
// returned_Z must be equal to z
After that that variable x will be stored in a file ...
then when the file opens this variable x will be returned to z with this function :
int returning(int x, int c){
int z = (int) ( x/Math.cos(c) );
return z;
}
From your posting, we have
temp = Integer( 15*cos(140) // -2.96 )
Find X such that
temp = Integer ( X/cos(140) )
We can solve this for X without the integer conversions.
X = 15 / cos^2(140)
or, in general
X = Z / cos^2(C)
This will give you an exact solution for X; you may apply the integer intermediate requirement if needed for some other purpose.
Update per OP comment
You have a defined mathematical relationships between X, temp, and Z. Truncating the intermediate result breaks some of that relationship. In short, if you restrict X to integers, you cannot guarantee that you get exactly Z when you apply the inverse operations.
In particular, you have a transcendental function cos; you cannot dictate that it will be the ratio of your integers temp and X or X and Z. There do exist point solutions for cos that are known rational numbers, but very few.
If I misunderstand the problem -- I realize that we have some translation problem -- then please update your question to specify the correct problem.
Actually the eqn has infinite number of solutions. Say temp = 2. And you write:
2 = Integer ( ( X )/cos(140) )
If we take Integer() for all real numbers in the range 2.0 <= num < 3.0, it results in 2. That's why infinite number of solutions possible. For example, if we take 2.5 from the range:
2 = Integer (2.5) is true
so we can write,
x / cos(140) = 2.5
=> x = 2.5 * cos(140)
= −1.915111108
If we take another 2.3 from the range:
x = −1.761902219
Since there infinite number of real numbers in the range 2.0 <= num < 3.0, the number of solutions is infinite too.
So you can't just expect a single solution for x. If you do, then use:
int Rounding(int z, int c){
int test = ( z*Math.cos(c) );
int x = (int) ( test*Math.cos(c) );
return x;
}
This will give you a correct answer. But as I said before, there are infinite number of solutions for x.

I don't understand why this working

public static void main(String args[]){
Scanner s = new Scanner(System.in);
int x;
int y;
int z = 0;
x = s.nextInt();
y = s.nextInt();
while(y != 0){
z += x;
y--;
}
System.out.println(z);
}
This is all.
This code calculates x*y but doesn't use *.
It was just a (task ?) somebody told me. And my question is why this is working with negative numbers. That x can be negative is obvious but why can y be.
Edit: I wrote this code on my own so I know why it works without *. That's not the question. I can input 5 for x and -5 for y and i get -25. But why? Everytime he adds one more time x to z y goes 1 down. But after the 5th time it stops.
If you put the "z" print inside the while you will understand.
This code makes overflow. Reach the maximum value that the int permit and decrease again from there
This code makes multiple sums. So it can sum the number 2, 3 times, and thats how it does 2*3.
The y can be negative because the if is seeing != than 0, not < than 0.

Diffrence between x++ and ++x? [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Is there a difference between x++ and ++x in java?
I am reading the official Java tutorial and I don't get the difference between postfix and prefix (++x vs x++). Could someone explain?
++x: increment x; the value of the overall expression is the value after the increment
x++: increment x; the value of the overall expression is the value before the increment
Consider these two sections:
int x = 0;
System.out.println(x++); // Prints 0
// x is now 1
int y = 0;
System.out.println(++y); // Prints 1
// y is now 1
I personally try to avoid using them as expressions within a larger statement - I prefer standalone code, like this:
int x = 0;
System.out.println(x); // Prints 0
x++;
// x is now 1
int y = 0;
y++;
System.out.println(y); // Prints 1
// y is now 1
Here I believe everyone would be able to work out what's printed and the final values of x and y without scratching their heads too much.
There are definitely times when it's useful to have pre/post-increment available within an expression, but think of readability first.
++x increments x and then returns the value
x++ returns the value of x and then increments the variable
For example:
int x = 0;
int A = ++x; // A = 1
int B = x++; // B = 1
int C = x; // C = 2
Well, you get enough answers, I'm going just to worry you... Both post- and pre-increment operators can confuse code, so sometimes it is better to use just x+1 then you and other people definitely know what is going on there. Some examples:
int x = 5;
x = ++x;
System.out.println( x ); // prints 6
x = x++;
System.out.println( x ); // prints 6!
x = ++x + x++;
System.out.println( x ); // prints 14!
two last incrementing can be a source of problems to debug then (was watching that few times in my life...). x = x++ - it is evaluated before incrementing... So be careful!
++x is pre-incrementing and x++ is post-incrementing. With post-incrementing the value is increased after evaluation and with pre-incrementing the value is increased before evaluation.
Well, standing alone it's the same. but, if there are other operands involved - ++x will advance x and then apply the other operands, and x++ will first use x and then advance it.
Basically, ++x adds 1 to x before x is evaluated, while x++ adds 1 afterwards. It makes sense if you use it as an argument.
Let's start with x
int x = 3;
If we call System.out.println on x using the infix operator:
System.out.println(++x);
x will first increase to 4 and the println will output, "4". It is pretty much the same if we did:
x+=1;
System.out.println(x);
Let's imagine x equals 3 again. If we call System.out.println on x using the postfix operator:
System.out.println(x++);
It will first output the current value of x, "3", and then increase x. So it's like:
System.out.println(x);
x+=1;
Hope that helps.

Categories

Resources