一、readline簡介
readline是Java中一個常用的用戶輸入工具,在控制台中運行Java程序時常常需要和用戶進行交互,這時候就需要使用readline完成用戶輸入。
readline可以進行各種類型的用戶輸入形式,如整型、字符串等
二、使用readline完成整型輸入
import java.io.*; public class Test { public static void main(String args[]){ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); try{ System.out.print("請輸入整數:"); int num = Integer.parseInt(br.readLine()); System.out.println("您輸入的整數是:"+num); }catch(IOException | NumberFormatException e){ System.out.println("數據輸入錯誤:"+e.getMessage()); } } }
以上代碼中,首先由BufferedReader類接收控制台的輸入數據,然後使用readLine()方法讀取輸入的數據,最後使用Integer.parseInt()方法將輸入的字符串轉換為整型。需要注意的是,在使用readLine()方法獲取控制台輸入數據時,必須捕獲IOException異常,並使用NumberFormatException來檢查輸入是否為字符串。最後,將輸入的整型數據輸出。
三、使用readline完成字符串輸入
import java.io.*; public class Test { public static void main(String args[]){ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); try{ System.out.print("請輸入字符串:"); String str = br.readLine(); System.out.println("您輸入的字符串是:"+str); }catch(IOException e){ System.out.println("數據輸入錯誤:"+e.getMessage()); } } }
以上代碼與讀取整型數據的代碼類似,只不過讀取的是字符串數據。
四、使用readline完成字符輸入
import java.io.*; public class Test { public static void main(String args[]) throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); try{ System.out.print("請輸入字符:"); char c = (char) br.read(); System.out.println("您輸入的字符是:"+c); }catch(IOException e){ System.out.println("數據輸入錯誤:"+e.getMessage()); } } }
讀取字符數據需要使用BufferedReader類的read()方法,然後將讀取的數據強制轉換為字符類型。
五、總結
本文詳細介紹了如何在Java中使用readline完成用戶輸入,包括整型、字符串和字符類型數據的讀取。對於每一種類型的數據讀取,本文都提供了詳細的Java代碼示例,希望可以為Java開發工程師提供幫助。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/181560.html