【问题标题】:Print the formula used to describe the addition of two numbers打印用于描述两个数字相加的公式
【发布时间】:2020-02-10 01:40:28
【问题描述】:

我卡在U of Helsinki Java MOOC

创建一个可用于将两个整数相加的程序。一开始,要求用户给出两个要相加的整数。然后程序会打印出描述数字相加的公式。

示例输出:

Give the first number:
5
Give the second number:
4
5 + 4 = 9

我试图让系统打印““第一”+“第二”是“结果”。出于某种原因,我被这个原本简单的问题难住了。我的代码总是抛出错误。我做错了什么在最后一行?

import java.util.Scanner;

public class AdditionFormula {

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

    // write your program here
    System.out.println("Give the first number: ");
    int first = Integer.valueOf(scanner.nextLine());
    
    System.out.println("Give the second number: ");
    int second = Integer.valueOf(scanner.nextLine());
    
    //System.out.println("first" " + " Integer.valueOf(first) + Integer.valueOf(second));
    System.out.println(first + " + " + second " = " + (first + second));
}

【问题讨论】:

  • 1.使用Integer.parseInt 而不是Integer.valueOf 以避免装箱开销。 2.这只是一个错字。 3.错误信息告诉你问题是什么。
  • 这些基本上是同义词吗?教程中没有介绍parseInt,不过我可以试试。
  • 它们的作用完全相同(如果我没记错的话,valueOf 在内部调用了parseInt),但是valueOf 返回一个Integer 对象,而parseInt 返回一个int
  • 这看起来像是过早的微优化,否则会是 discouraged,但在某些情况下避免自动装箱/拆箱的速度优势可能很显着。
  • 谢谢,对不起。我需要等待至少 20 分钟才能接受。

标签: java addition


【解决方案1】:

您提供的代码无法编译

改成

System.out.println(first + " + " + second + " = " + (first + second));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多