【发布时间】:2020-02-10 01:40:28
【问题描述】:
创建一个可用于将两个整数相加的程序。一开始,要求用户给出两个要相加的整数。然后程序会打印出描述数字相加的公式。
示例输出:
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 分钟才能接受。