步骤:
1.导包:在首行import java.util.Scanner;
2.声明一个Scanner实例 Scanner sc=new Scanner(System.in)
3.获取数据
整形:int num=sc.nextInt(); //换行,空格做结束
字符串:String s=sc.nextLine(); //换行做结束
使用nextLine()方法时,不将空格看做是两个字符串的间隔,而是看作字符串的一部分,返回时,它作为String类型一并返回
使用next()方法时,将空格看作是两个字符串的间隔
使用nextInt()方法时,与next()方法类似,只是它的返回值是int类型的,依旧将空格看作是两个输入的数据的间隔
所以nextInt和nextLine不能连在一起写因为结束的标志回车是一样的,
当用nextInt()读取缓冲区数据时,遇到回车或者空格,数据就会被读取走,但是回车符或者空格会被留下。当再调用nextLine()时,因为nextLine()是以回车符结束,当被调用后,刚好缓冲区还有被nextInt()“吃”剩下的回车符,所以还没等接着输入第二个参数,nextLine()就已经结束。因为只读取到一个回车符,所以pile的参数自然为空,从而导致后序程序出现异常。
解决方案:
把nextInt()换成nextLine(),再转换成int类型,就完美解决。
String s1 = in.nextLine();
int count = Integer.parseInt(s1);
String pile = in.nextLine();
String[] piles = pile.split(" ");
在读取前,一定需要hasNext和hasNextLine判断是否还有输入的数据。它们的区别为:
hasNext()方法判断输入(文件、字符串、键盘等输入流)是否还有下一个输入项,若有,返回true,反之false。
1
2
3
|
Scanner sc = new Scanner( new File( "test.txt" )); System.out.println(sc.hasNext()); |
若test.txt为空(空格、tab、回车),则输出结果为false;若该文件不为空输出true。
当输入为键盘时,该方法出现阻塞(block),也即等待键盘输入。输入源没有结束,又读不到更多输入项。
1
2
3
|
Scanner sc = new Scanner(System.in); System.out.println(sc.hasNext()); |
运行上面的程序,控制台等待键盘输入,输入信息后输出结果为true。
1
2
|
输入:Hello true |
由上面的知识,则如下代码则不难理解:
1
2
3
4
|
Scanner sc = new Scanner(System.in); while (sc.hasNext()) { System.out.println( "Input from keyboard:" + sc.next()); } |
sc.hasNext()始终等待键盘输入,输入信息后,sc.next()打印出该信息。
当读入最后一个数据的时候,并不是跳出,而是阻塞在了while中,一直执行
原因:
hasNext(),是如果此扫描器的输入中有另一个标记,则返回 true。在等待要扫描的输入时,此方法可能阻塞。扫描器将不执行任何输入。所以循环会一直下去。
解决方案:
此时,可以设置一个终止符,调用hasNext()的重载方法hasNext(String patten):如果下一个输入与从终止符相匹配,则返回 true。扫描器不执行任何输入。
//例:以“0”作为终止符
Scanner in = new Scanner(System.in);
while (!in.hasNext("0")) {
System.out.println(in.next());
}
1
2
3
4
5
1
2
3
4
5
2 每次读取一行数据
import java.util.Scanner;
public class Test2 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
//是否还有下一行
while (sc.hasNextLine()) {
String str = sc.nextLine();//读取一行,保留空格
System.out.println("输出:"+str);
}
sc.close();
}
}
运行结果:
123 456 789
输出:123 456 789
111 111 111
输出:111 111 111
3 每次读取一个数据
import java.util.Scanner;
public class Test2 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
//是否还有下一个元素
while (sc.hasNext()) {
String str = sc.next();//读取一个元素,不保留空格
System.out.println("输出:"+str);
}
sc.close();
}
}
运行结果:
123 456 798
输出:123
输出:456
输出:798
111 111 111
输出:111
输出:111
输出:111
想退出循环可以参考https://mp.csdn.net/postedit/88424076
---------------------
作者:春卷同学
来源:CSDN
原文:https://blog.csdn.net/Rex_WUST/article/details/88572001
版权声明:本文为博主原创文章,转载请附上博文链接!
---------------------
作者:熊仙森
来源:CSDN
原文:https://blog.csdn.net/qunqunstyle99/article/details/82874288
版权声明:本文为博主原创文章,转载请附上博文链接!