First Ever Java Program Incorrect Output
Sorry for really stupid question, I'm learning a new language and taking this code:
public class Exercise01 {
int i;
char c;
public static void main(String[] args) {
Exercise01 E = new Exercise01();
System.out.println("i = " + E.i);
System.out.println("c = [" + E.c + "]");
}
}
/* Output:
i = 0
c = [
*/
Why the output does not produce "]" character? Has it something to do with Unicode?
PostEdited: the variable E.c开发者_高级运维 was not initialized for experimentation purpose.
It may be that the place your program is outputting to, a console or a window, is getting confused by the U+0000 character which is the value of E.c.
It works fine for me.
Initialize E.c and try again.
You are trying to print the null character as your char c
hasn't need initialised. i.e. \0
Interestingly you can't copy and paste this character easily as most C code sees this as an end of string marker.
I see the ]
when I run the code.
Try changing your code with
char c = '?';
gives me an output of
i = 0
c = [?]
One way to reproduce this problem is to run on unix
java Main | more
which outputs
i = 0
c = [
Probably has to do with the fact that E.c isn't initialized to anything
I think it is because c
is not initialized and therefore holds \0
, i.e. "end of line". So, println
prints until end of line and does not print your ]
You should initialize your char C as well as the int i. Good code practice: It is important to initialize your variable once you declare a variable!
精彩评论