我开始学习Java。。。
第一个代码不是我想要的返回结果。

import java.util.Scanner;
public class Yusuf
{
    public static void main(String args[])
    {
        Scanner text = new Scanner(System.in);
        int a,b;
        System.out.print("Enter first number:");
        a = text.nextInt();
        System.out.print("Enter second number:");
        b = text.nextInt();
        System.out.print("a + b = " + a+b);
    }
}


此代码的结果是“ a + b = 1525”(如果a = 15和b = 25(例如,我给出随机数))

为什么上述代码无法正常工作,例如以下代码:

import java.util.Scanner;
public class Yusuf
{
    public static void main(String args[])
    {
        Scanner text = new Scanner(System.in);
        int a,b,c;
        System.out.print("Enter first number:");
        a = text.nextInt();
        System.out.print("Enter second number:");
        b = text.nextInt();
        c = a+b;
        System.out.print("a + b = " + c);
    }
}


该代码返回相同数字的40。
有什么不同?绝对我需要使用其他变量?

最佳答案

与字符串一起使用时,+运算符会进行字符串连接。如果使用+将数字添加到字符串的末尾,则数字将首先转换为字符串。

您的声明:

System.out.print("a + b = " + a+b);


接受字符串"a + b",并将a的值作为字符串连接,然后将b的值作为字符串连接。

如果这样做,它将按照您想要的方式工作:

System.out.print("a + b = " + (a+b) );


(a+b)的额外括号将导致在字符串串联发生之前对该加法进行评估(作为int加法)。

10-07 19:22
查看更多