Java:從檔案讀取資料

從鍵盤輸入個人「名字、身高、體重」

import java.util.Scanner;
public class E01_GetWtHt {
	public static void main(String[] args){
		Scanner sc = new Scanner(System.in);
		
		System.out.print("請輸入你的名字:");
		String name = sc.nextLine();
		
		System.out.print("請輸入你的身高(公分):");
		int height = sc.nextInt();

		System.out.print("請輸入你的體重(公斤):");
		double weight = sc.nextDouble();

		System.out.printf("%-12s %5d %6.1f\n", name, height, weight);
	}
}

補充資料:從檔案讀取資料

檔案 bmi-1.txt

Bob 180 72.5

參考範例程式 FileRead.java

import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;

public class E02A_FileRead {
	public static void main(String args[]) throws IOException {

		FileReader bmifile = new FileReader("bmi-1.txt");
		Scanner inf = new Scanner(bmifile);

		String name = null;
		int height;
		double weight;

		name = inf.next();
		height = inf.nextInt();
		weight = inf.nextDouble();
		System.out.printf("%-12s %5d %6.1f\n", name, height, weight);
		bmifile.close();
	}
}

檔案中含多筆數字

檔案 Num-n.txt

72.5
99
100
56.7 89.5
80

參考範例程式 FileReadMul.java

public class E02B_FileReadMul {
	public static void main(String args[]) throws IOException {

		FileReader numfile = new FileReader("Num-n.txt");
		Scanner inf = new Scanner(numfile);

		double num;

		while (inf.hasNext()) {
			num = inf.nextDouble();
			System.out.printf("%9.1f\n", num);
		}
		numfile.close();
	}
}

檔案中含多筆資料(文字、整數、浮點數)

檔案 bmi-data.txt

Bob 180 72.5
Obama 179 75.5
Johnson 190 87.2
Jane 162 48.6

參考範例程式 FileBMI.java

import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;

public class E03_FileBMI {
	public static void main(String args[]) throws IOException {

		FileReader bmifile = new FileReader("bmi-data.txt");
		Scanner inf = new Scanner(bmifile);
		
		String name = null;
		int height;
		double weight;

		// Read and sum numbers.
		while (inf.hasNext()) {
			if (inf.hasNextLine()) {
				name = inf.next();
				height = inf.nextInt();
				weight = inf.nextDouble();
				System.out.printf("%-12s %5d %6.1f\n", name, height, weight);
			} else {
				break;
			}
		}
		bmifile.close();
	}
}