【问题标题】:What's the thing with single inverted comma in Java? [duplicate]Java中的单引号是什么意思? [复制]
【发布时间】: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


【解决方案1】:

因为' ' 是一个字符,所以" " 是一个String

int 添加到String 是连接,将产生String

int 添加到char 是一个带有字符代码(ASCII) 的数字运算,将产生int

【讨论】:

  • 所以表示''是一个带空格的char,空格的值为32。
  • @RedEyedRocker,是的
猜你喜欢
  • 2011-02-27
  • 2012-08-13
  • 1970-01-01
  • 2019-01-23
  • 2014-07-28
  • 2015-02-13
  • 2023-04-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多