使用scanner类将数字转换并生成到集合中
时间: 2024-03-15 21:47:44 浏览: 23
好的,我可以帮你解决这个问题。你可以使用Scanner类从用户输入中读取数字,并将其转换成集合中的整数。以下是一个示例代码:
```java
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
List<Integer> numbers = new ArrayList<>();
System.out.println("请输入数字,输入-1结束输入:");
int input = scanner.nextInt();
while (input != -1) {
numbers.add(input);
input = scanner.nextInt();
}
System.out.println("输入的数字如下:");
for (int number : numbers) {
System.out.println(number);
}
}
}
```
在这个示例中,我们创建了一个Scanner对象来读取用户的输入。我们使用一个while循环来持续读取输入,直到用户输入-1为止。在每次循环中,我们将输入的数字添加到一个ArrayList中。最后,我们遍历ArrayList并输出所有输入的数字。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)