Java 中的单引号是怎么回事?
What's the thing with single inverted comma in Java?
我刚开始学习Java编程语言,有一件事我不明白。
因此,以下代码用于计算 2 个给定数字的总和,基本上,这是我的主要方法:
public class Addition{
public static void main(String[]args){
Scanner add = new Scanner ( System.in );
System.out.println("Enter the first number:"+' ');
int num1 = add.nextInt();
System.out.println("Enter the second number:"+' ');
int num2 = add.nextInt();
int calculate = num1 + num2;
System.out.println(num1 + ' ' + "+" + ' ' + num2 + "=" + ' ' + calculate);
add.close();
}
所以给定的 ' '
是针对 space 的,代码只是用于计算 2 个给定数字的总和
例如 2 个数字是 15 和 5。所以输出应该是这样的:
Enter the first number:
15
Enter the second number:
5
15 + 5 = 20
但是没有!输出如下所示:
Enter the first number:
15
Enter the second number:
5
47 + 5 = 20
应该有 15 个而不是 47 个的地方。所以我用这样一个更短的代码替换了代码:
System.out.println(num1 + " + " + num2 + "= " + calculate);
这解决了我的问题,输出显示如我所料,但我想知道。 ' '
是怎么回事?当我把代码写成
(num1 + ' ' + "+" + num2 + "=" + ' ' + calculate)
然后不在输出中显示 num1
的输入值,而是 num1
的值增加 32,就像我在 num1
中添加 32 时一样space 和 ' '
基本上,我想问的是 ' '
有什么问题?
因为' '
是一个字符,所以" "
是一个String
。
将 int
添加到 String
是串联,将导致 String
将int
加到char
是一个带有字符代码(ASCII)的数字运算,结果是int
。
我刚开始学习Java编程语言,有一件事我不明白。
因此,以下代码用于计算 2 个给定数字的总和,基本上,这是我的主要方法:
public class Addition{
public static void main(String[]args){
Scanner add = new Scanner ( System.in );
System.out.println("Enter the first number:"+' ');
int num1 = add.nextInt();
System.out.println("Enter the second number:"+' ');
int num2 = add.nextInt();
int calculate = num1 + num2;
System.out.println(num1 + ' ' + "+" + ' ' + num2 + "=" + ' ' + calculate);
add.close();
}
所以给定的 ' '
是针对 space 的,代码只是用于计算 2 个给定数字的总和
例如 2 个数字是 15 和 5。所以输出应该是这样的:
Enter the first number:
15
Enter the second number:
5
15 + 5 = 20
但是没有!输出如下所示:
Enter the first number:
15
Enter the second number:
5
47 + 5 = 20
应该有 15 个而不是 47 个的地方。所以我用这样一个更短的代码替换了代码:
System.out.println(num1 + " + " + num2 + "= " + calculate);
这解决了我的问题,输出显示如我所料,但我想知道。 ' '
是怎么回事?当我把代码写成
(num1 + ' ' + "+" + num2 + "=" + ' ' + calculate)
然后不在输出中显示 num1
的输入值,而是 num1
的值增加 32,就像我在 num1
中添加 32 时一样space 和 ' '
基本上,我想问的是 ' '
有什么问题?
因为' '
是一个字符,所以" "
是一个String
。
将 int
添加到 String
是串联,将导致 String
将int
加到char
是一个带有字符代码(ASCII)的数字运算,结果是int
。