Issue
In Java System.out.println(1+' '+2);
In Eclipse the result is 35
I cannot understand. Isn't the answer should be 1 2 ? I thought that ' ' means blank. println(1+2) should be 3. From the reason above I thought the reason above println(1+' '+2) would be 1 2.
why?? how?? 35?? instead of 1 2 ?
refer the whole code import java.util.Scanner;
public class Main{ public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
for(int i=1; i<=n; i++)
for(int j=1; j<=m; j++)
System.out.println(i+' '+j);
}
}
Solution
Take a look at the Unicode standard (or an ASCII chart to get the idea; there you'll find the first 128 characters of Unicode) and you'll see that each character maps to a certain numeric value. The value of the space character is 32. Trying to add it to integers casts it to its numeric value, so you end up with i + 32 + j, or 1 + 32 + 2, which is indeed 35.
The reason this happens is that ' is used to denote chars, and in Java, addition of a char and an int results in an int as described above.
What you want to do here is to create a string, denoted by ", and concatenate values to it. 'c' is a char, but "c" is a string, and if you add integers to it, the result will be a string -- one with the string corresponding to that integer concatenated to it: so "c"+1 will be "c1".
TL;DR: the fix here is to modify it to i + " " + j. The takeaway is that it's important to keep the concept of casting in mind, as well as the fact that characters can be mapped (and cast) to numeric values (in this case, their ASCII values; for more complex situations, as I mentioned, look at Unicode).
Answered By - Shay
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.