1. 大概就是下面的模式
Scanner scanner = new Scanner(System.in);
String s = scanner.nextLine();
Scanner sc = new Scanner(s);
while(sc.hasNextInt()){
arr[i++] = sc.nextInt();
}
2.输入整数
这里以输入一组整数为例,当输入回车就结束输入,打印出数组内容
import java.util.Scanner;
public class Test01 {
public static void main(String[] args) {
int[] arr = new int[max];
int i = 0;
Scanner scanner = new Scanner(System.in);
String s = scanner.nextLine();
Scanner sc = new Scanner(s);
while(sc.hasNextInt()){
arr[i++] = sc.nextInt();
}
System.out.print("[");
for(int j=0;j<i;j++){
if(j==i-1)
System.out.print(arr[j]);
else
System.out.print(arr[j]+", ");
}
System.out.println("]");
}
public static final int max = 1000;
}
输出结果:
3. 输入字符串
知道了模式是怎样的,也知道了如何输入一组整数,以回车结束输入,那么字符串也是一样的道理
import java.util.Scanner;
public class Test01 {
public static void main(String[] args) {
// int[] arr = new int[max];
// int i = 0;
//
// Scanner scanner = new Scanner(System.in);
// String s = scanner.nextLine();
// Scanner sc = new Scanner(s);
// while(sc.hasNextInt()){
// arr[i++] = sc.nextInt();
// }
String[] arr = new String[max];
int i=0;
Scanner scanner = new Scanner(System.in);
String s = scanner.nextLine();
Scanner sc = new Scanner(s);
while (sc.hasNextLine()){
arr[i++] = sc.nextLine();
}
System.out.print("[");
for(int j=0;j<i;j++){
if(j==i-1)
System.out.print(arr[j]);
else
System.out.print(arr[j]+", ");
}
System.out.println("]");
}
public static final int max = 1000;
}
输出结果: