Java中從鍵盤擷取輸入值

來源:互聯網
上載者:User

1.從控制台接收一個字元,然後將其列印出來

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

        System.out.print("Enter a Char:");

        char i = (char) System.in.read();

        System.out.println("your char is :"+i);

}

雖然此方式實現了從鍵盤擷取輸入的字元,但是System.out.read()只能針對一個字元的擷取,同時,擷取進來的變數的類型只能是

char,當我們輸入一個數字,希望得到的也是一個整型變數的時候,我們還得修改其中的變數類型,這樣就顯得比較麻煩。

2.從控制台接收一個字串,然後將其列印出來。在這個題目中,我們需要用到BufferedReader類和InputStreamReader類

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

 

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        String str = null;

        System.out.println("Enter your value:");

        str = br.readLine();

        System.out.println("your value is :"+str);

}

這樣我們就能擷取我們輸入的字串。

3.這種方法我認為是最簡單,最強大的,就是用Scanner類

public static void main(String [] args) {

        Scanner sc = new Scanner(System.in);

        System.out.println("請輸入你的姓名:");

        String name = sc.nextLine();

        System.out.println("請輸入你的年齡:");

        int age = sc.nextInt();

        System.out.println("請輸入你的工資:");

        float salary = sc.nextFloat();

        System.out.println("你的資訊如下:");

        System.out.println("姓名:"+name+"/n"+"年齡:"+age+"/n"+"工資:"+salary);

}

這段代碼已經表明,Scanner類不管是對於字串還是整型資料或者float類型的變數,只需做一點小小的改變,就能夠實現功能!無疑他是最強大的!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.