Java鍵盤錄入的兩種方式

karspb發表於2021-09-09

方法一:使用BufferedReader包裝鍵盤錄用

這種方法只能從控制檯接收字串,而無法接收其他資料型別,如果想接收其他資料型別,要對其進行轉換:

package com.itheima;

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

public class Test {
    public static void main(String[] args) throws IOException {
        //BufferedReader包裝鍵盤錄入
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        //把鍵盤錄入的資料存在字串str中
        String str=br.readLine();
        //把錄入的資料輸出到控制檯
        System.out.println(str);
                //轉換資料型別
        int num = Integer.parseInt(str);  // 假設str想接收的是整型
        double x = Double.parseDouble(str);  // 假設str接收的是double型
    }
}

方法2:使用Scanner
Scanner類是最強大的,不管是對於字串還是整型資料或者float型別的變數,只需做一點小小的改變,都能夠實現功能!

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);
}

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/2001/viewspace-2798609/,如需轉載,請註明出處,否則將追究法律責任。

相關文章