long blogs

进一步有进一步惊喜


  • Home
  • Archive
  • Tags
  •  

© 2025 long

Theme Typography by Makito

Proudly published with Hexo

javaScanner输入数据

Posted at 2019-09-07 笔记 基础 

Scanner类

Scanner类一般是用来接收从控制台传进去的数据的。但是往往不能使用Scanner从控制台获得想要的数据。。

1、想要获得控制台传进来的一个数组对象。

需求描述将1 2 3 4 5 6 7从控制台转成数组对象。

使用如下的代码是跳不出来循环的

1
2
3
4
5
6
7
8
9
10
Scanner cin = new Scanner(System.out);
int[] array = new int[100];
int len = 0;
while(cin.hasNextInt()){
int read = cin.nextInt();
array[len] = read;
++len;
}
// 以下的代码不会被执行
// 要对数组进行操作。。

另外一种思路:
将控制台的输入当成一个字符串。获得该字符串之后再进行解析。
用空格进行正则分割.然后再依次的赋值

1
2
3
4
5
6
7
8
9
10
11
12
int[] arr = new int[100];
Scanner scanner = new Scanner(System.in);
String str = scanner.nextLine();
scanner.close();
// 自己解析字符串
String strArray = str.split(" ");
int len = 0;
for(int i=0;i<len;i++) {
arr[i] = Integer.parseInt(strArray[i]);
}
// 对数组进行操作
// 可以执行下面的代码

Share 

 Previous post: java基础 Next post: Redis笔记 

© 2025 long

Theme Typography by Makito

Proudly published with Hexo