【发布时间】:2017-02-20 03:17:18
【问题描述】:
我刚开始学习 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();
}
所以给定的' ' 用于空格,代码仅用于计算两个给定数字的总和
例如这两个数字是 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 一样,当我将空间与' ' 放在一起时
基本上,我在问' ' 是怎么回事?
【问题讨论】:
-
' '代表一个字符,而" "是一个字符串。一个 char 有一个数值(ASCII 值),这就是为什么' ' + int返回一个 int -
你为什么要写类似
num1 + ' ' + "+"的东西?甚至这个"Enter the first number:"+' '?这只会让阅读变得更加困难 -
正如我已经提到的,''是空格,所以“输入第一个数字:”+''将输出为“输入第一个数字:(空格)”,但可以缩短为“输入第一个数字:”我是初学者,所以:P
标签: java function methods addition