java之Scanner详解「建议收藏」

java之Scanner详解「建议收藏」刷题过程中遇到数据的读入扫描 发现网上资料比较杂 总结下 1 包 import java util Scanner 2 使用方法 Scanner reader new Scanner System in 然后 reader 对象调用下列方法 函数 读取用户在命令行输入的各种数据类型 nextByte nextDouble nextFloat nextInt

刷题过程中遇到数据的读入扫描,发现网上资料比较杂,总结下。

1.包:

import java.util.Scanner

2.使用方法:

Scanner reader=new Scanner(System.in);

然后reader对象调用下列方法(函数),读取用户在命令行输入的各种数据类型:

nextByte(),nextDouble(),nextFloat,nextInt(),nextLine(),nextLong(),nextShort()

注:上面由next()方法转化而来,空格,TAB快结束

上述方法执行时都会造成堵塞,等待用户在命令行输入数据回车确认.

例如,拥护在键盘输入

12.34,hasNextFloat()的值是true,而hasNextInt()的值是false. NextLine()等待用户输入一个文

本行并且回车,该方法得到一个String类型的数据。相比nextLine()回车确认,按照行读为string

3.实例

//逐行扫描文件,并逐行输出
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.println(s.nextLine());
}
}
//all out
import java.util.Scanner;

public class testNextline {
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);
}
}
}
//next(), nextByte(),nextDouble(),nextFloat,nextInt(),nextLine(),nextLong(),nextShort()  //用法类似
import java.util.Scanner;

public class hasNextInt {

public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("请输入一个整数");
while(in.hasNextInt()){
int num = in.nextInt();
System.out.println("数字"+num);//输入123 12只能读到123
System.out.println("请输入一个字符串");
String str = in.next();//输入 adc cv只能读到adc

System.out.println("字符串"+str);
}
}
}


4.其他相关方法

下面这几个相对实用:

delimiter()
返回此 Scanner 当前正在用于匹配分隔符的 Pattern。

 public static void main(String[] args) throws FileNotFoundException { 
Scanner s = new Scanner("123 asda bf 12 123 nh l,sf.fl ...adafafa lda");
// s.useDelimiter(" |,|\\.");
while (s.hasNext()) {
System.out.println(s.next());
}
}
123
asda
bf
12
123
nh
l,sf.fl
...adafafa
lda


hasNext()
判断扫描器中当前扫描位置后是否还存在下一段。(原APIDoc的注释很扯淡)
hasNextLine()
如果在此扫描器的输入中存在另一行,则返回 true。
next()
查找并返回来自此扫描器的下一个完整标记(String)。
nextLine()
此扫描器执行当前行,并返回跳过的输入信息。

5. 一个读写实例

import java.util.Scanner;
public class test{
public static int getCount(String str,char c){
int count = 0;
if(str != null && str.length() > 0){
for(int i = 0;i < str.length();i++){
if(c == str.charAt(i)){
count++;
}
}
}else{
count = 0;
}
return count;
}

public static void main(String[] args){
Scanner s = new Scanner(System.in);
String str = s.next();
char c = s.next().charAt(0);
int i = getCount(str,c);
System.out.println(i);
}
}
编程小号
上一篇 2025-04-06 19:11
下一篇 2025-10-06 08:46

相关推荐

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/hz/129424.html