使用 Formatter 在 Java 程式中顯示帶列的表格
在本文中,我們將學習如何使用 Java 中的 Formatter 在輸出中顯示帶列的表格。該表格將包含標題,並顯示浮點數陣列的不同計算結果。第一列將顯示原始數字,第二列將顯示向上取整後的數字,第三列將顯示向下取整後的數字。
問題陳述
編寫一個 Java 程式,使用 Formatter 在輸出中顯示帶列的表格。
輸入
double arr[] = { 1.7, 2.5, 3.1, 4.5, 5.7, 6.9, 7.7, 8.9, 9.1 };
輸出
The point list...
Points1 Points2 Points3
1.70 2.00 1.00
2.50 3.00 2.00
3.10 4.00 3.00
4.50 5.00 4.00
5.70 6.00 5.00
6.90 7.00 6.00
7.70 8.00 7.00
8.90 9.00 8.00
9.10 10.00 9.00
使用 Formatter 顯示帶列的表格的步驟
以下是使用 Formatter 顯示帶列的表格的步驟:-
- 我們將從匯入 Formatter 類 開始,該類來自 java.util 包。
- 建立一個雙精度值陣列,用作資料。
- 之後初始化一個 Formatter 物件來幫助格式化輸出。
- 使用 format() 方法 建立包含三列的表格標題。
- 迭代數字陣列,並再次使用 format() 方法 格式化每一行,顯示 原始值、上限值 和 下限值。
- 在輸出中顯示格式化的表格。
使用 Formatter 在 Java 程式中顯示帶列的表格
以下是使用 Formatter 在輸出中顯示帶列的表格的示例:-
import java.util.Formatter;
public class Demo {
public static void main(String[] argv) throws Exception {
double arr[] = { 1.7, 2.5, 3.1, 4.5, 5.7, 6.9, 7.7, 8.9, 9.1 };
Formatter f = new Formatter();
f.format("%15s %15s %15s
", "Points1", "Points2", "Points3");
System.out.println("The point list...
");
for (double d : arr) {
f.format("%14.2f %14.2f %15.2f
", d, Math.ceil(d), Math.floor(d));
}
System.out.println(f);
}
}
輸出
The point list... Points1 Points2 Points3 1.70 2.00 1.00 2.50 3.00 2.00 3.10 4.00 3.00 4.50 5.00 4.00 5.70 6.00 5.00 6.90 7.00 6.00 7.70 8.00 7.00 8.90 9.00 8.00 9.10 10.00 9.00
程式碼說明
在這個程式中,我們首先匯入 Formatter 類並定義一個浮點數陣列。初始化一個 Formatter 物件來幫助將輸出格式化為帶列的表格。我們使用 format() 方法 將列標題設定為 “Points1”、“Points2” 和 “Points3”。然後,對於陣列中的每個數字,我們使用 Math.ceil() 和 Math.floor() 計算其上限值和下限值,並在相應的列中與原始數字一起顯示它們。format() 方法確保每個值都與兩位小數正確對齊。最後,格式化的輸出列印到控制檯。
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP