Java中的Scanner(详解常见⽤法)
OJ中遇到的问题和例⼦:
double nextDouble() , float nextFloat() , int nextInt() 等与nextLine()连⽤时都存在遗留的换⾏符影响nextLine()读取输⼊的问题,解决的办法是:在
加⼀个nextLine()语句,将被next()去掉的Enter结束符过滤掉。
每⼀个 next()、nextDouble() 、 nextFloat()、nextInt() 等语句之后加⼀个nextLine()语句,将被next()去掉的Enter结束符过滤掉
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNext()) {
int n = in.nextInt();
/* nextLine()是扫描器执⾏当前⾏,并返回跳过的输⼊信息,特别需要注意
如果没有该⾏,则执⾏第⼀个in.nextLine()命令时的返回值是int n = in.nextInt()的值*/
HashSet<String> set = new HashSet<String>();
for (int i = 0; i < n; i++) {
String line =
String[] arr = line.split(" ");
for (int j = 0; j < arr.length; j++) {
set.add(arr[j]);
}
}
System.out.println("sum:" + set.size());
}
}
⼀、扫描控制台输⼊
这个例⼦是常常会⽤到,但是如果没有Scanner,你写写就知道多难受了。
当通过new Scanner(System.in)创建⼀个Scanner,控制台会⼀直等待输⼊,直到敲回车键结束,把所输⼊的内容传给Scanner,作为扫描对象。如果要获取输⼊的内容,则只需要调⽤Scanner的nextLine()⽅法即可。
/**
* 扫描控制台输⼊
*/
public class TestScanner {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("请输⼊字符串:");
while (true) {
String line = s.nextLine();
if (line.equals("exit")) break;
System.out.println(">>>" + line);
}
}
java中split的用法
}
请输⼊字符串:
234
>>>234
wer
>>>wer
bye
>>>bye
exit
Process finished with exit code 0
⼆、如果说Scanner使⽤简便,不如说Scanner的构造器⽀持多种⽅式,构建Scanner的对象很⽅便。
可以从字符串(Readable)、输⼊流、⽂件等等来直接构建Scanner对象,有了Scanner了,就可以逐段(根据正则分隔式)来扫描整个⽂本,并对扫描后的结果做想要的处理。
三、Scanner默认使⽤空格作为分割符来分隔⽂本,但允许你指定新的分隔符
使⽤默认的空格分隔符:
public static void main(String[] args) throws FileNotFoundException {
Scanner s = new Scanner("123 asdf sd 45 789 sdf asdfl,sdf.sdfl,asdf    ......asdfkl    las");
//                s.useDelimiter(" |,|\\.");
while (s.hasNext()) {
System.out.());
}
}
123
asdf
sd
45
789
sdf
asdfl,sdf.sdfl,asdf
......asdfkl
las
Process finished with exit code 0
将注释⾏去掉,使⽤空格或逗号或点号作为分隔符,输出结果如下:
123
asdf
sd
45
789
sdf
asdfl
sdf
sdfl
asdf
asdfkl
las
Process finished with exit code 0
四、⼀⼤堆API函数,实⽤的没⼏个
(很多API,注释很让⼈迷惑,⼏乎毫⽆⽤处,这个类就这样被糟蹋了,启了很不错的名字,实际上做的全是龌龊事)下⾯这⼏个相对实⽤:
delimiter()
返回此 Scanner 当前正在⽤于匹配分隔符的 Pattern。
hasNext()
判断扫描器中当前扫描位置后是否还存在下⼀段。(原APIDoc的注释很扯淡)
hasNextLine()
如果在此扫描器的输⼊中存在另⼀⾏,则返回 true。
next()
查并返回来⾃此扫描器的下⼀个完整标记。
nextLine()
此扫描器执⾏当前⾏,并返回跳过的输⼊信息。
五、逐⾏扫描⽂件,并逐⾏输出
看不到价值的扫描过程
public static void main(String[] args) throws FileNotFoundException {
InputStream in = new FileInputStream(new File("C:\\AutoSubmit.java"));
Scanner s = new Scanner(in);
while(s.hasNextLine()){
System.out.Line());
}
}
public class AutoSubmit {
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
...在此省略N⾏
Process finished with exit code 0
Java对字符串⽀持还是⽐较弱的,尽管Java⼀直在努⼒。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。