Reading the "?" and ":" operator in Java [duplicate] - java

This question already has answers here:
What is the Java ?: operator called and what does it do?
(17 answers)
Closed 3 years ago.
I'm new to Java and while doing some homework I came across this example:
String result = " ";
for (int r = rows(); r >= 0; r++) {
result += ("___") + (r == 0 ? (" ") : ("_"));
}
for (int y = columns(); y >= 0; y++) {
for (int x = 0; x <= rows(); x++) {
result += ("|") + ((located && theLocation(y, x)) ? (youWin + "S"
+ " ") : (" " + (mysterySpot[y][x] == 'S' ? (" ") :
(mysterySpot[y][x])) + " "));
}
If I understand this correctly, the first for-loop should be equivalent to:
for (int r = rows(); r >= 0; r++) {
result += "___";
if (r == 0) {
result += " ";
}
else {
result += "_";
Am I reading it correctly? For the second part, it looks like there's an if-else statement within another if-else statement. This is the part I'm confused about, what would the code look like if I were to write it out as if-else statements?

Translated into ifs and elses, this looks something like the following.
for (int y = columns(); y >= 0; y++) {
for (int x = 0; x <= rows(); x++) {
if (located && theLocation(y,x)) {
result += "|" + youWin + "S ";
} else if (mysterySpot[y][x] == 'S') {
result += "| ";
} else {
result += "| " + mysterySpot[y][x] + " ";
}
}
}
Note that you should almost never use single-letter variable names, and if you do, you should try to make them meaningful. In this particular case, using y for a column number and x for a row number is the complete reverse of what anyone would expect.
Never write code like the code in this book. My best advice would be to learn from a different book.

So the "?" and the ":" are read like this....
If a is less than b put x else put y.
This statement is shown in code here.
if (a < b){
// Does a thing
x;
}else{
// Does a cooler thing
y;
}
Alternatively, we can write it like so...
a < b ? x : y
So the part before the "?" is asking if it is true. If a is indeed greater than b then do x the ":" is the else statement or the alternative
[the question] ? [option1 if true] : [option2 if false]

Related

Java Ternary operator syntax [duplicate]

This question already has answers here:
Ternary operator, syntax error when using assignment
(4 answers)
Closed 8 years ago.
I have the following piece of code. This is how I understand it.
In the first case, the ternary operator returns the value of y because x=4 and the print statement prints 5, as expected.
In the 2nd case, the ternary operator first assigns the value of y to x and then returns that value. Again, it prints 5, as expected.
In the 3rd case, the ternary operator has x=y to the left of the : and x=z to the right of the :. I would expect this to behave much like the 2nd case. However, this statement does not even compile.
Any help in understanding this will be much appreciated.
public class Test {
public static void main(String[] args) {
int x = 4;
int y = 5;
int z = -1;
x = (x == 4) ? y : z; // compiles and runs fine
System.out.println(x + " " + y + " " + z);
x = (x == 4) ? x = y : z; // compiles and runs fine
System.out.println(x + " " + y + " " + z);
x = (x == 4) ? x = y : x = z; // Does not compile
System.out.println(x + " " + y + " " + z);
}
}
Assignment has lower precedence than a ternary expression, so this expression:
(x==4)?x=y:x = z;
can be thought of as:
((x==4)?x=y:x) = z;
Which obviously won't compile because you can't assign a value to something that isn't a variable.
Add parenthesis to control the order of evaluation
x = (x == 4) ? (x = y) : (x = z); // Does compile.
Note the above is equivalent to
if (x == 4) {
x = (x = y);
} else {
x = (x = z);
}
Which will (as a side effect) of assigning a value to x assign the value assigned to x to x. In other words, your ternary is equivalent to
x = (x == 4) ? y : z;
or
if (x == 4) {
x = y;
} else {
x = z;
}
The ternary is specified in JLS-15.25. Conditional Operator ? :.

BigDecimal multiplication returns 0?

I'm a bit of a newbie at Java and I have to multiply 52 numbers with each other ranging anywhere from 0 to 2000. I already tried using *= without BigDecimal but the result gives me 0.0.
Here is my code:
BigDecimal productOfStock1 = BigDecimal.ZERO;
for(int k = 1; k <= N; k++){
for(int i = 1; i <= n; i++){
if (i == 1){
stockPrice[k][i] = stockZero*Math.pow(e, form + sigma*(randomno.nextGaussian()));
}
else {
stockPrice[k][i] = stockPrice[k][i-1]*Math.pow(e, form + sigma*(randomno.nextGaussian()));
}
//sumOfStock += stockPrice[k][i];
//productOfStock *= stockPrice[k][i];
productOfStock1 = productOfStock1.multiply(BigDecimal.valueOf(stockPrice[k][i]));
System.out.println(/*"Stock at [" + i + "] for N = " + N + " and path number " + k + " is " + */stockPrice[k][i]);
}
}
System.out.println(productOfStock1);
This gives me 0E-637 instead of the big number it is supposed to give me. Any help is appreciated.
BigDecimal productOfStock1 = BigDecimal.ZERO;
you need to initialize it with 1, because
0 * X = 0
(except for X= 1/0 :) )
Don't initialize productOfStock1 to 0, use 1 instead. Otherwise, you'll always be multiplying by 0.

Why is my increment not being calculated right?

I've got a for-loop running, and it asks them for the increment number. But when it outputs the table, it actually doubles the increment. So if I put in 10 for incr it will go up by 20. Please help?
for (double x = fah1; x <= fah2; x+=incr) {
double cel = 5/9.0 * (x-32);
if (x <= 99){
System.out.println(x + " " + df.format(cel);
x+= incr;
}
else {
System.out.println(x + " " + df.format(cel));
x+=incr;
}
}
You are incrementing twice per loop, once in either the if or else, and again at the end in the third statement of the for loop declaration.
Remove the increments in the if and else and rely on the one in the for loop declaration.
You are incrementing twice - once in the for loop declaration and once in the if-then-else statement:
Try changing it to this:
for (double x = fah1; x <= fah2; x+=incr) {
double cel = 5/9.0 * (x-32);
if (x <= 99){
System.out.println(x + " " + df.format(cel);
// Remove the increment from here
}
else
{
System.out.println(x + " " + df.format(cel));
// Remove the increment from here
}
}

while nested in for loop. How does the decrement operator work?

I couldn't figure out how the decrement operator (e--)
works in code below, so i wrote the other class below it
to get the same result. I want to know how the decrement operator
achieves that result in the Power class. - Newbie.
int result, e;
for(int i=0; i < 10; i++) {
result = 1;
e = i;
while(e > 0) {
result *= 2;
e--;
}
System.out.println("2 to the " + i +
" power is " + result);
}
Code written to achieve same result
int result = 1;
for(int i=0; i < 10; i++) {
if (i > 0) {
result*=2;
}
System.out.println("2 to the " + i +
" power is " + result);
}
So the first example is resetting result for each iteration of the main for loop, so it needs to recalculate from scratch each time, where as the second example is keeping the previous computed value. The if in the second example is not needed is it.
The decrement operator modifies the variable on which it's called. So e-- is effectively e = e - 1 (except the overall result of the expression is different, see below).
This code:
result = 1;
e = i;
while(e > 0) {
result *= 2;
e--;
}
starts with result = 1 and then loops for i iterations doubling the value in result. Equivalent code using for which you seem more comfortable with:
result = 1;
for (e = 0; e < i; e++) {
result *= 2;
}
There are two forms of the decrement (and increment) operator: Prefix and postfix, depending on whether the operator is before (prefix) or after (postfix) its operand. Either could be used in the code you were asking about, because the only difference is the result of the expression.
Prefix: Suppose we have x = 5. The expression --x has the value 4: First we decrement x, then we take its new value as the result of the expression.
Postfix: Suppose we had x = 5 (again). The expression x-- has the value 5, with x ending up containing 4: First we grab the current value of x as the result of the expression, then we decrement it (because the -- is after x).
int x, r;
x = 5;
r = --x; // Prefix
System.out.println("r = " + r + ", x = " + x); // "r = 4, x = 4"
x = 5;
r = x--; // Postfix
System.out.println("r = " + r + ", x = " + x); // "r = 5, x = 4"
i figure out that by placing a System.out.println(e) i could "see" the variable "e" behavior in order to make sense of the decrement.
class Power {
public static void main(String args[]) {
int e;
int result;
for(int i=0; i < 10; i++) {
result =1 ;
e = i;
while(e > 0) {
System.out.println(e); // not part of the original program
result *= 2 ;
e--;
System.out.println(e); // not part of the original program
}
//System.out.println("2 to the " + i +
//" power is " + result);
}
This is the output:
C:\Users\enrique\Desktop\Hello.java>java Power: 1, 0, 2, 1, 1, 0, 3
e = 1(iteration 1), 2^1, e (1) decremented to 0, e = 2 (iteration 2), 2^2, e(2) decremented to 1, e = 1 re-enter The while but is ignored as 2^1 is already registered, e (1) decremented to 0, e = 3 (iteration 3), 2^3…

Can't seem to figure out why my loop wont progress

I can't seem to figure out why my for loop is not working. I have been on the for about an hour now and the closest I have come is this. I'm trying to find out how many McNuggets you can buy using the 6, 9, and 20 packs. All I need dopeChecker(x) to do is return a true or a false. I haven't implemented check the next number yet because it wont even find that a 6 pack can be bought yet. I know it's in the loop somewhere but I just can't find out where. This is form the MIT open course ware problem 2. I don't know if you guys have seen it but I'm just letting you know this is where I'm getting my info.
int x = 0, y = 0, z = 0;// These will the the pack of McNuggets that we can buy.
int testFor = 0; //This will be the number of McNuggets we are looking for.
int matches = 0; //This will be the number of consecutive matches we will be looking for.
public void dopeEquation(){
while (matches < 6){//It's 6 Because that is the smallest order of nuggets we can buy.
//Looking for smaller nuggets then we can buy would not make sense.
while (testFor < 6){
testFor++;
}
if (dopeChecker(testFor)){
matches++;
} else{
matches = 0;
System.out.println(x + "," + y +"," + z +"," + testFor + "," + matches);
}
}
}
private boolean dopeChecker(int testFor){
for ( x = 0 ; x*6 <= testFor; x++){
for ( y = 0 ; y*9 <= testFor; y++){
for (z = 0 ; z*20 <= testFor;){
System.out.println(x + "," + y +"," + z +"," + testFor + "," + matches);
if (x*6 + y*9 + z*20 == testFor){
matches++;
System.out.println("match");
return true;
}else{
System.out.println("no match");
}
}
}
}
return false;
}
}
The z variable is always 0, you're not changing it.
Your code goes inside the first while loop:
while (matches < 6){
Then increased testFor to 6 with the following code:
while (testFor < 6){
testFor++;
}
Then goes to dopeChecker:
dopeChecker(int testFor)
Then insde the 3rd loop, for z:
for (z = 0 ; z*20 <= testFor;) {
...
}
z is never incremented, so you need to write this as:
for (z = 0 ; z*20 <= testFor; z++){
}
The following is the innermost for loop. I have commented where the problem is. as you can see, z never gets implemented. therefore, the loop will never terminate, as 0 <= testFor, since TestFor >= 6.
for (z = 0 ; z*20 <= testFor;/* incrementor needed here*/){
System.out.println(x + "," + y +"," + z +"," + testFor + "," + matches);
if (x*6 + y*9 + z*20 == testFor){
matches++;
System.out.println("match");
return true;
}else{
System.out.println("no match");
}
}

Categories

Resources