Java裡面讀取鍵盤輸入的方法有兩種,一種是Scanner,一種是InputStreamReader
首先我們先介紹Scanner
Scanner可以生成一個物件然後用.next方法輸入string,或是用.nextInt方法等等輸入不同的資料型別。這方法會有一個
import java.util.Scanner;
public class scannerDemo {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please type some words:");
String str = input.next();
System.out.println("The words you have typed is:"+str);
System.out.println("Please type an integer x:");
int x = input.nextInt();
int sum=0;
for(int i=1;i<=x;i++){
sum=sum+i;
}
System.out.println("The sum of 1 to x is:"+sum);
input.close();
}
}
首先我們先介紹Scanner
Scanner可以生成一個物件然後用.next方法輸入string,或是用.nextInt方法等等輸入不同的資料型別。這方法會有一個
import java.util.Scanner;
public class scannerDemo {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please type some words:");
String str = input.next();
System.out.println("The words you have typed is:"+str);
System.out.println("Please type an integer x:");
int x = input.nextInt();
int sum=0;
for(int i=1;i<=x;i++){
sum=sum+i;
}
System.out.println("The sum of 1 to x is:"+sum);
input.close();
}
}
