java - 基本的java打印

标签 java

请注意下面代码段中的打印语句。我的问题是,如果我尝试在 print 语句中添加两个 double ,它会打印错误,但如果我将它们添加到 print 语句之外并将结果存储在一个变量中,我就无法正确打印它。

为什么这行得通并打印出正确的结果?

public static void main(String argsp[]){
        Scanner input = new Scanner(System.in);

        double first, second, answer;

        System.out.println("Enter the first number: ");
        first = input.nextDouble();

        System.out.println("Enter the second number: ");
        second = input.nextDouble();

        answer = first + second;

        System.out.println("the answer is " + answer);

    }

为什么这样打印出错误的结果?

public static void main(String argsp[]){
        Scanner input = new Scanner(System.in);

        double first, second;

        System.out.println("Enter the first number: ");
        first = input.nextDouble();

        System.out.println("Enter the second number: ");
        second = input.nextDouble();

        System.out.println("the answer is " + first+second);

    }

最佳答案

这是因为你在第二部分基本上做的是:

System.out.println("the answer is " + String.valueOf(first) + String.valueOf(second));

这就是编译器解释它的方式。因为当您将 String 提供给方法时,+ 运算符不是计算,而是连接

如果你想在一行中完成,这样做:

System.out.println("the answer is " + (first + second)); //Note the () around the calculation.

关于java - 基本的java打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10738148/

相关文章:

java - 如何获取一周中的哪一天、每月的第一天?

Java ws Jboss 7 SOAP 头

java - 将泛型类型乘以二 - 二叉树方法

java - Selenium - Maven/TestNG : how can we add testng parameters in Java class while adding "main method" to create executable/runnable. jar 文件?

java - 从文本文件读取数据并将其添加到android中的arraylist的最佳方法

java - 如何查询 CursorLoader?

java - 如何列出jar中资源中的目录

java.lang.ClassNotFoundException : org. springframework.context.ApplicationContext

Java 泛型 : wildcard extends class and include that class

java - 我需要将信息传递给一个类,然后返回到Java中的主类