您的位置:首页 >如何在Java中使用回车结束输入?
发布于2023-04-28 阅读(0)
扫一扫,手机访问
在编写java程序的时候,我们想通过输入回车来完成这一行的输入,这是一个非常常见的问题,但是如果我们是用Scanner ,然后通过nextInt()方法调用的时候,不会停止输入,回打出一个空行,然后等着你继续输入下一个数字。
我们可以设置两个Scanner 第一个以行为单位读取数据,这样就相当于是用回车(enter)当作结束符,
然后把读取到的字符串传入第二个Scanner, 然后在进行处理
ArrayList<Integer> arr = new ArrayList() ;
System.out.println("Enter a space separated list of numbers:");
Scanner in = new Scanner(System.in);
String line = in.nextLine();
Scanner in2 = new Scanner(line);
while(in2.hasNextInt()){
arr.add(in2.nextInt());
}
System.out.println("The numbers were:"+arr.toString());只需要把nextInt 或者hasnextint等函数改成你所需要的函数名就可以实现 不同的输入,但是是以回车(enter)为结尾了。
题目

在论坛找到这种方法:
Scanner s =new Scanner(System.in);
String str="";
do {
str=s.nextLine();
if(s.hasNextLine())
break;
}while(true);
System.out.println(str);经实践,此法不通:

需要两个回车才能结束输入。
Scanner s= new Scanner(System.in); String str=s.nextLine(); Scanner st=new Scanner(str); ArrayList a =new ArrayList(); while(st.hasNextInt()) a.add(st.nextInt()); System.out.println(a);

将字符串作为输入流,空格为间隔符:
源码:

this调用下面构造函数:

售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
正版软件
正版软件
正版软件
正版软件
正版软件
1
2
3
7
9