Java 獲取鍵盤輸入

讀取整數型


public static void main(String[] args) {
		
		Scanner sc = new Scanner(System.in);//in java.io.inputStream
	        int a=0, b=0;
	        while(sc.hasNextInt())
	        {
	            a = sc.nextInt();
	            b = sc.nextInt();
	            System.out.println(a);
	            System.out.println(b);
	        }
			
			
	}

input:

1 2

output:

1

2


讀取字符型

public static void main(String[] args) {
		
		Scanner sc = new Scanner(System.in);//in java.io.inputStream
	      String str ;
	        while(sc.hasNext())
	        {
	           str = sc.nextLine();
	            System.out.println(str);
	        }
			
			
	}


input :

ni hao

output :

ni hao


要是直接輸入一次就結束的就可去掉循環體。需要重複輸入的就像代碼中一樣即可。

發佈了91 篇原創文章 · 獲贊 40 · 訪問量 12萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章