Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 Introduction to Java Programming Lecture 6 Program Input : BufferedReader & Scanner.

Similar presentations


Presentation on theme: "1 Introduction to Java Programming Lecture 6 Program Input : BufferedReader & Scanner."— Presentation transcript:

1

2 1 Introduction to Java Programming Lecture 6 Program Input : BufferedReader & Scanner

3 Program Input : Scanner Java 5 及之後的版本提供了一個 class 叫做 Scanner , 可以讓我們從鍵盤取得使用者的輸入. Scanner 是在 java.util 這個 package 中。使用前須先 import java.util 語法如下 : import java.util.Scanner; public class MyProgram { Scanner scan = new Scanner(System.in); ….. } 其中 System.in 代表的是輸入裝置 ( 鍵盤 ) 2

4 3 Scanner 的一些 Methods String nextLine() 讀進然後 return 使用者的輸入的字串直到碰到 “Enter” 鍵 為止 int nextInt() 讀進然後 return 使用者輸入的整數 double nextDouble() 讀進然後 return 使用者輸入的 double  2003 Prentice Hall, Inc. All rights reserved.

5 Scanner Example Scanner scan = new Scanner(System.in); System.out.println("Please input your birth month:"); String month = scan.nextLine(); System.out.println("Please input your birth day number:"); int dayNumber = scan.nextInt(); 會發生甚麼事 : 如果我們要求使用者輸入整數但是輸入 卻是字串 ? 4

6 5 Program Input : BufferedReader To use BufferedReader, need to import 3 classes import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.IOException; Or simply use import java.io.* 語法 : BufferedReader myReader = new BufferedReader(new InputStreamReader(System.in), 1); 5

7 6 BufferReader Example import java.io.*; // 這裡用到三個類別 : //BufferedReader InputStreamReader IOException public class Input{ public static void main(String[] args){ BufferedReader myReader = new BufferedReader(new InputStreamReader(System.in), 1); try{ System.out.print("What's your name : "); String s = myReader.readLine(); System.out.print("Hello, " + s); }catch(IOException e){ // 例外處理可放在這裡 }


Download ppt "1 Introduction to Java Programming Lecture 6 Program Input : BufferedReader & Scanner."

Similar presentations


Ads by Google