1 / 10

InputStream Console Scanner

輸入. 輸入. InputStream Console Scanner. InputStream 讀取資料. 較舊的 Java 開發模組必須使用標準序列輸入 ( import java.io.* ) new InputStream ( System.in ) 並將輸入的資料指定由 『 暫存區 』 儲存 new BufferedReader (new InputStream ( System.in )) 由暫存區變數執行 readLine 方法讀入資料 public class 類別名稱 {

brent
Download Presentation

InputStream Console Scanner

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 輸入

  2. 輸入 InputStream Console Scanner

  3. InputStream讀取資料 • 較舊的Java開發模組必須使用標準序列輸入 (import java.io.*) new InputStream(System.in) • 並將輸入的資料指定由『暫存區』儲存 new BufferedReader(new InputStream(System.in)) • 由暫存區變數執行readLine方法讀入資料 public class 類別名稱 { public static void main(String args[]) throws IOException { BufferedReaderbuf; buf = new BufferedReader(new InputStreamReader(System.in)); String str = buf.readLine(); } }

  4. 範例 • 使用者輸入一串文字,存於字串變數並輸出。 import java.io.*; public class 類別名稱 { public static void main(String args[]) throws IOException { BufferedReaderbuf; buf = new BufferedReader(new InputStreamReader(System.in)); System.out.print(“請輸入一字串:”); String str = buf.readLine(); System.out.println(str); } }

  5. Console讀取資料 • JDK6新增java.io.Console類別 import java.io.Console; • 宣告console物件 Console console = System.console(); • 使用物件執行readLine方法讀入資料 String str = console.readLine(); • 讀取資料預設為字串,其他資料型態須強制轉換。 • 只能用『命令提示字元』視窗輸入。

  6. 範例 • 使用者輸入二個數字,相加後輸出。 public static void main(String args[]){ Console a = System.console(); System.out.print(“請輸入數字1:”); int num1= Integer.parseInt(a.readLine()); System.out.print(“請輸入數字:”); int num2= Integer.parseInt(a.readLine()); System.out.println(“sum=”+(num1+num2)); } 讓Jcreator可由命令提示字元輸入資料:Configure →Option →JDKTools → Run Application→ Default → Edit →取消capture output

  7. 練習 • 讓使用者輸入兩個數字,使用console輸入功能讀取資料,加總之後輸出結果。範例一: 範例二:

  8. Scanner讀取資料 • Scanner類別 import java.util.Scanner; • 宣告scanner物件 Scanner sc = new Scanner(System.in); • 使用sc物件讀取資料 • 字串:String str = sc.next(); • 整數:int num = sc.nextInt(); • 浮點數:double num = sc.nextDouble(); • 布林:booleanbl = sc.nextBoolean();

  9. Scanner讀取資料 • 優點 • Scanner物件可讀取多種資料型態,不須強制轉換 • 可在Jcreator的General Output中直接輸入,不一定得用命令提示字元的視窗。

  10. 練習 • 宣告一個scanner物件,讀取不同型態的資料。

More Related