Java如何实现Scanner输入整数并输出加法公式?
输出包含输入数字的加法公式解决方案
你只需要在现有代码基础上添加输出语句,将输入的两个整数和求和结果按公式格式打印即可。以下是两种常用实现方式:
方法1:字符串拼接
通过字符串拼接组合公式内容,注意求和部分需加括号保证运算优先级:
import java.util.Scanner; public class AdditionFormula { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); 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 + " + " + second + " = " + (first + second)); scanner.close(); // 关闭输入流避免资源泄漏 } }
方法2:格式化输出(推荐)
使用printf做格式化输出,代码更简洁易读,%d作为整数占位符匹配变量:
import java.util.Scanner; public class AdditionFormula { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); 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.printf("%d + %d = %d%n", first, second, first + second); scanner.close(); } }
关键说明
- 字符串拼接时
(first + second)必须加括号:Java中字符串与数字的+是拼接操作,不加括号会先把first转成字符串拼接,导致求和逻辑失效。 printf的%d会按顺序替换为后面的整数变量,%n是跨平台换行符,比\n更通用。
内容的提问来源于stack exchange,提问作者ellebelle1512
相关产品推荐
相关产品推荐

