2006/03/01

Java 學習筆記 (2) - 標準輸入

J2SE 5.0 中,可以使用 java.util.Scanner 依據空白字元來取得使用者輸入。


取得字串:


InputString.java


[java]import java.util.Scanner;

public class InputString {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Please input a string: ");
System.out.printf("The String is %s!", scanner.next());
}
}[/java]





結果:



Please input a string: sokoyo
The String is sokoyo!




取得整數:


InputInteger.java


[java]import java.util.Scanner;

public class InputInteger {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Please input a string to interger: ");
System.out.printf("I get a interger %d!!",
scanner.nextInt());
}
}[/java]




結果:



Please input a string to interger: 100
I get a interger 100!!




nextInt() 會將取得的字串試著轉為整數,同樣可以使
用 nextFloat()、nextBoolean() ... 轉成適合的型態。






要取得包含空白字元的完整字串,可以使用 java.io.BufferedReader。
使用 BufferedReader 的 readLine() 時必須處理 IOException,readLine() 會傳
回 Enter 之前的所有字元,不包含 Enter 字元。


InputStrings.java


[java]import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;

public class InputStrings {
public static void main(String[] args) throws IOException {
BufferedReader buf = new BufferedReader(
new InputStreamReader(System.in));

System.out.print("Please input a sentence: ");
String text = buf.readLine();
System.out.println("The sentence is: " + text);
}
}[/java]




結果:



Please input a sentence: This is a sentence.
The sentence is: This is a sentence.







此外,輸入也與輸出類似,可以使用 "<" 從檔案導入資料。

No comments:

Post a Comment