Java中從鍵盤輸入的三種方法

來源:互聯網
上載者:User

標籤:cat   nbsp   print   scan   read   inpu   ase   tput   []   

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;

public class EnterTest {

public static void main(String[] args) { //主方法
CharTest(); //調用System.in方法
ReadTest(); //調用ReadTest方法
ScannerTest();//調用ScannerTest方法
}
/**
* System.in和System.out方法
* 缺點一: 該方法能擷取從鍵盤輸入的字元,但只能針對一個字元的擷取
* 缺點二: 擷取的只是char類型的。如果想獲得int,float等類型的輸入,比較麻煩。
*/
public static void CharTest(){
try{
System.out.print("Enter a Char:");
char i = (char)System.in.read();
System.out.println("Yout Enter Char is:" + i);
}
catch(IOException e){
e.printStackTrace();
}

}
/**
* InputStreamReader和BufferedReader方法
* 優點: 可以擷取鍵盤輸入的字串
* 缺點: 如何要擷取的是int,float等類型的仍然需要轉換
*/
public static void ReadTest(){
System.out.println("ReadTest, Please Enter Data:");
InputStreamReader is = new InputStreamReader(System.in); //new構造InputStreamReader對象
BufferedReader br = new BufferedReader(is); //拿構造的方法傳到BufferedReader中
try{ //該方法中有個IOExcepiton需要捕獲
String name = br.readLine();
System.out.println("ReadTest Output:" + name);
}
catch(IOException e){
e.printStackTrace();
}

}
/**
* Scanner類中的方法
* 優點一: 可以擷取鍵盤輸入的字串
* 優點二: 有現成的擷取int,float等類型資料,非常強大,也非常方便;
*/
public static void ScannerTest(){
Scanner sc = new Scanner(System.in);
System.out.println("ScannerTest, Please Enter Name:");
String name = sc.nextLine(); //讀取字串型輸入
System.out.println("ScannerTest, Please Enter Age:");
int age = sc.nextInt(); //讀取整型輸入
System.out.println("ScannerTest, Please Enter Salary:");
float salary = sc.nextFloat(); //讀取float型輸入
System.out.println("Your Information is as below:");
System.out.println("Name:" + name +"\n" + "Age:"+age + "\n"+"Salary:"+salary);
}
}

 

Java中從鍵盤輸入的三種方法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.