本文目錄一覽:
java編程式控制制台輸入?
方法/步驟
首先我們創建一個Test類並編寫main方法,在main方法中測試java的控制台輸入。我們先介紹java.util.Scanner類,它可以處理控制台輸入的不同數據類型的數據,我們通過new Scanner創建一個Scanner對象,控制台等待輸入,輸入完成後敲回車鍵即可,讀取輸入的內容,使用nextLine()方法即可。如下圖所示,我們編寫一個獲取從控制台輸入字元串的方法,可以通過循環不停的接收,直到達到設定的次數後跳出循環。
請點擊輸入圖片描述
請點擊輸入圖片描述
其他scan.next()和scan.nextLine()用於獲取字元串類型的輸入,另外我們還可以用scan.nextBoolean()用於獲取布爾型的輸入,scan.nextInt()用於獲取數值型的輸入,scan.nextLong()用於獲取long類型的輸入,如下圖所示。
請點擊輸入圖片描述
請點擊輸入圖片描述
我們還可以單獨使用System.in.read()讀取一個字元或一個數字,有下圖可知,儘管控制台輸入的是一個字元串,但是實際上只能讀取一個字元。在讀取數字時,我們輸入的數字是8,但實際上讀取的是56,因為此時獲取的是Unicode編碼,使用try catch捕獲編碼過程中的異常。
請點擊輸入圖片描述
請點擊輸入圖片描述
接下來我們介紹通過位元組流的方式讀取控制台的輸入,我們需要用到BufferedInputStream,首先創建一個BufferedInputStream對象用於接收控制台的輸入,我們創建一個byte數組,長度為1024用於存儲接收的字元串,使用read方法讀取,最後使用new String(byte[])將byte數組轉成字元串進行輸出,代碼中的異常需要處理,我們使用try catch捕獲即可。
請點擊輸入圖片描述
接著我們介紹使用字元流的方式獲取控制台的輸入,創建一個BufferedReader對象,InputStreamReader是位元組到字元的緩存流,我們同樣使用System.in來獲取控制台的輸入,readLine()方法用於讀取輸入的信息,如下圖所示。
請點擊輸入圖片描述
如何從java控制台輸入帶空格的字元串?
/**按行讀取 */import java.io.*;public class SystemInTest {
public static void main(String[] args) { BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in)); String str; try { str = stdin.readLine(); System.out.println(str); } catch (IOException e) { e.printStackTrace(); } }}
Java控制台輸入帶空格的字元串,讀取的時候只要按照行來讀取,就可以獲取到輸入的空格,下面是示例:/**按行讀取 */import java.io.*;public class SystemInTest {public static void main(String[] args) { BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));//建立從控制台輸入的類 String str; try { str = stdin.readLine();//讀取一行 System.out.println(str); } catch (IOException e) { e.printStackTrace(); } }}
import java.util.Scanner;
public class encode2013
{
public static void main(String[] args){
String inString;
String delimiter;
Scanner scan = new Scanner(System.in);
inString=scan.nextLine();
delimiter=scan.next();
inString= inString.replace(” “,delimiter);
System.out.println(inString);
}
java中從控制台讓用戶輸入參數的語句是什麼?
java中從控制台讓用戶輸入參數的語句的方式如下:
1、使用標準輸入串System.in
//System.in.read()一次只讀入一個位元組數據,而我們通常要取得一個字元串或一組數字
//System.in.read()返回一個整數
//必須初始化
//int read = 0;
char read = ‘0’;
System.out.println(“輸入數據:”);
try {
//read = System.in.read();
read = (char) System.in.read();
}catch(Exception e){
e.printStackTrace();
}
System.out.println(“輸入數據:”+read);
2、使用Scanner取得一個字元串或一組數字
System.out.print(“輸入”);
Scanner scan = new Scanner(System.in);
String read = scan.nextLine();
System.out.println(“輸入數據:”+read);
/*在新增一個Scanner對象時需要一個System.in對象,因為實際上還是System.in在取得用戶輸入。Scanner的next()方法用以取得用戶輸入的字元串;nextInt()將取得的輸入字元串轉換為整數類型;同樣,nextFloat()轉換成浮點型;nextBoolean()轉換成布爾型。*/
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/230655.html