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(), <span style="font-size:18px;">nextByte(),nextDouble(),nextFloat,nextInt(),nextLine(),nextLong(),nextShort() //用法类似</span>
- 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);
- }
- }