刷题过程中遇到数据的读入扫描,发现网上资料比较杂,总结下。
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); } } }
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
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); } }