Supplementary knowledge
The Java Scanner class
java.util.Scanner is a new feature of Java5. We can get user input through the Scanner class.
The toString() method is used to return the value of the Number object represented by a string.
table of Contents
1. Get an array of unlimited length from the keyboard
import java.util.Scanner;
public class InputArrayNoLimitLength {
public static void main(String[] args) {
System.out.println("请输入几个数并用逗号隔开:");
Scanner sc = new Scanner(System.in);//从键盘接收数据
String str = sc.next().toString();//next()方式接收字符串
System.out.println(str);
String[] arr = str.split(",");
for(int j = 0; j<arr.length;j++) {
System.out.print(arr[j]+" ");
}
}
}
Output result
2. Obtain a limited-length array from the keyboard
import java.util.Scanner;
public class InputArrayLimitLength {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
System.out.println("请输入"+n+"个数:");
Scanner sc = new Scanner(System.in);
int[] b=new int[n];
for(int i=0;i<b.length;i++){
b[i]=sc.nextInt();
System.out.print(" " + b[i]);
}
}
}