Program Input and Output 程序输入与输出
Learning Objectives 学习目标
- Read user input data interactively using the Scanner class.
- Format double floating-point decimal outputs using printf placeholders.
- Construct a complete billing program that calculates tax rates and grand totals.
- 使用 Scanner 类以交互方式读取用户输入数据。
- 使用 printf 占位符格式化双精度浮点小数输出。
- 构建一个计算税率和总和的完整账单程序。
2 · Interactive Console Input (Scanner Class)
In Java, reading keyboard inputs is managed by the Scanner utility class (located in package java.util). Using Scanner involves three steps:
在 Java 中,读取键盘输入由 java.util 包中的 Scanner 工具类进行管理。使用 Scanner 包含三个步骤:
-
Import:导入: Write reference statement at the top of the file:
import java.util.Scanner;在文件顶部编写引用语句:import java.util.Scanner; -
Declaration:声明: Create and bind Scanner object to input system:
Scanner input = new Scanner(System.in);创建 Scanner 对象并绑定到输入流系统:Scanner input = new Scanner(System.in); -
Reading:读取: Invoke input reading methods:
int count = input.nextInt();ordouble val = input.nextDouble();调用输入读取方法:int count = input.nextInt();或double val = input.nextDouble();
3 · Formatting Program Output (printf)
The standard System.out.println() prints values raw, which often yields too many decimal places for monetary values. Instead, use System.out.printf() (formatted print) to control spacing and alignment:
标准的 System.out.println() 只是原始打印数据,这通常会导致金额值出现过多的小数位。相反,使用 System.out.printf()(格式化打印)来控制输出格式与宽度:
| Placeholder占位符 | Data Type对应数据类型 | Description & Example描述与示例 | Formatted Output格式化输出结果 |
|---|---|---|---|
| %d | int / long | System.out.printf("Count: %d", 25); |
Count: 25 |
| %f | double / float | System.out.printf("Price: %f", 3.5); |
Price: 3.500000 |
| %.2f | double / float | System.out.printf("Price: %.2f", 3.5); |
Price: 3.50 (rounded to 2 decimal places) |
| %s | String | System.out.printf("Name: %s", "Chee"); |
Name: Chee |
| %n | None | System-independent newline character (equivalent to ).系统无关的换行符(相当于 )。 | (new line / 换行) |
4 · Executable Program Logic Flow
When structuring interactive codes, the logic must run in sequential order: import utilities → declare class → declare Scanner → prompt user for input → read data → process formulas → format and output results → close scanner. 在结构化交互式代码中,逻辑必须按顺序执行:导入类库 → 声明类与主方法 → 声明 Scanner → 提示用户输入 → 读取数据 → 运行公式计算 → 格式化并输出结果 → 关闭 scanner。
Applied Case Study: Interactive Cafe Billing应用案例研究:交互式咖啡店账单
Company: Kompas Coffee House.
We write an interactive program that prompts the cashier for purchase details: quantity ordered, unit item price, and calculates total sales including a 6% service tax.
公司: Kompas Coffee House。
我们编写一个交互式程序,提示收银员输入商品购买明细:订购数量、商品单价,并计算包含 6% 服务税的总销售额。
Billing Register Source Code收银系统程序源代码
import java.util.Scanner; public class CoffeeRegister {{ public static void main(String[] args) {{ Scanner input = new Scanner(System.in); final double TAX_RATE = 0.06; // 6% service tax System.out.print("Enter item price (RM): "); double unitPrice = input.nextDouble(); System.out.print("Enter quantity: "); int quantity = input.nextInt(); double subtotal = unitPrice * quantity; double serviceTax = subtotal * TAX_RATE; double grandTotal = subtotal + serviceTax; System.out.println("\n--- KOMPAS COFFEE HOUSE RECEIPT ---"); System.out.printf("Unit Price: RM %.2f%n", unitPrice); System.out.printf("Quantity: %d units%n", quantity); System.out.printf("Subtotal: RM %.2f%n", subtotal); System.out.printf("Tax (6%%): RM %.2f%n", serviceTax); System.out.printf("Total Due: RM %.2f%n", grandTotal); input.close(); }} }}
💡 Hint / 提示
Notice in the printf format: we escape percent character with double percent (%%) to print a literal % on the screen. %n issues a platform-specific newline.请注意在 printf 格式中:我们使用双百分号 (%%) 才能在屏幕上打印字面量 %。%n 发送平台相关的换行符。
✅ Show Expected Console Flow / 显示预期控制台运行
Enter item price (RM): 12.50 Enter quantity: 3 --- KOMPAS COFFEE HOUSE RECEIPT --- Unit Price: RM 12.50 Quantity: 3 units Subtotal: RM 37.50 Tax (6%): RM 2.25 Total Due: RM 39.75
Check Your Understanding自我检测
Q1. Which import statement is required to use Scanner class in Java?要使用 Java 的 Scanner 类,需要哪个导入语句?
Q2. Which statement correctly declares and instantiates Scanner object?哪个语句正确声明并实例化了 Scanner 对象?
Q3. Which printf format placeholder rounds a double variable value to exactly two decimal places?哪个 printf 格式占位符将双精度浮点变量值四舍五入为正好两位小数?
Q4. What does %n do inside System.out.printf()?在 System.out.printf() 中,%n 起什么作用?