to test myself in Java, I wrote up a program where I needed to display the contents of double[] measurements
, containing: {8.0, 7.7474, 7.4949, 7.7474, 8.0, 7.7474, 7.4949, 7.7474, 8.0}. A simple enhanced for loop and a println()
seems to work fine, but
for(double measure: measurements)
{
System.out.println(measure + '"');
}
prints out 42, 41.7474, 41.4949, etc. Exactly 34 more than the value of measure
. Changing the code to
for(double measure: measurements)
{
System.out.println(measure + '\"');
}
prints out 18,17.7474, 17.4949, etc. Exactly 10 more than the correct value. It only prints correctly when the println
statement is split into two lines:
System.out.print(measure);
System.out.println("\"");
Why is it that the first two examples add to the value of measure
? I'm fairly new to programming, but it seems to me that they would all have worked because Java uses both apostrophes and quotes to declare a string. Why does splitting it into two statements work correctly while connotating the two add to the value of measure
? Thanks!
It's because you are printing the result of the expression measure + '"'
. At the moment, you're performing an addition between a double
and a char
. If you instead use "
instead of '
it will work.
Like this: System.out.println(measure + "\"");
Another option is to first convert measure
to a string. That's rarely the best alternative, but the whole gist here is that you need to know the types of the operands and what the resulting type of the operation will be. Addition between a double
and a char
will result in a double
. Addition between a double
(or int
or char
among others) and a String
will result in a String
.