Java Scanner语法
1.导入: import java.util.Scanner;? 2.创建对象 Scanner scan = new Scanner();//一般变量名为scan或者in 最后关闭,scan.close();和I/O流有关,暂不清楚,照抄先。 3.next() 读取字符串,要读取到有效字符后才结束输入,不能读取空格,即遇到空格就停。 Scanner scan = new Scanner(System.in); String s1 = new String(); String s2 = new String(); String s3 = new String(); s1 = scan.next(); s2 = scan.next(); s3 = scan.next(); System.out.println(s1); System.out.println(s2); System.out.println(s3); if(scan.hasNext()) System.out.println("Yes"); 输入:123 456 789 1011 输出: 123 s1第一次读取到有效字符1,遇到4前的空格结束第一次输入;随后s2遇到第一个有效字符4,遇到空格结束;s3遇到第一个有效字符7,同理遇到空格结束,此时还有未读取的字符在缓冲区里,用hasNext()判断; 4.hasNext() 判断是否还有输入的数据,不能识别空格或回车,还会吃掉空格或者回车,连续的空格加回车一次性全部吸收掉,ACM里用循环读取下一组数据。 5.nextLine() 和next()类似,唯一不同就是,next()遇到空格或者回车就断了,nextLine()遇到回车才断,空格也算是有效字符,从第一个有效字符开始直到回车,中间无论多少空格都能吃下。 package my_acm; import java.util.Scanner; public class MyTest10 { public static void main(String[] args) { Scanner scan = new Scanner(System.in); String s1 = new String(); String s2 = new String(); String s3 = new String(); String s4 = new String(); s1 = scan.next(); s2 = scan.next(); s3 = scan.next(); s4 = scan.nextLine(); System.out.println(s1); System.out.println(s2); System.out.println(s3); System.out.println(s4); if(scan.hasNext()) System.out.println("Yes1"); if(scan.hasNextLine()) System.out.println("Yes2"); } } /**输入:123 456 789 1011 12 13 14 15 输出: 123 456 789 1011 12 13 14 15 s4把9后面的全部字符全部都吃下去了,没有未读取的字符 */ 6.hasNextLine() 可以判断空格和回车,但是不会吃掉任何字符。 import java.util.Scanner; public class MyTest10 { public static void main(String[] args) { Scanner scan = new Scanner(System.in); String s1 = new String(); String s2 = new String(); String s3 = new String(); String s4 = new String(); s1 = scan.next(); s2 = scan.next(); s3 = scan.next(); System.out.println(s1); System.out.println(s2); System.out.println(s3); if(scan.hasNext()) System.out.println("Yes1"); if(scan.hasNextLine()) System.out.println("Yes2"); scan.close(); } } import java.util.Scanner; public class MyTest10 { public static void main(String[] args) { Scanner scan = new Scanner(System.in); String s1 = new String(); String s2 = new String(); String s3 = new String(); String s4 = new String(); s1 = scan.next(); s2 = scan.next(); s3 = scan.next(); System.out.println(s1); System.out.println(s2); System.out.println(s3); if(scan.hasNextLine()) System.out.println("Yes2"); if(scan.hasNextLine()) System.out.println("Yes3"); if(scan.hasNext()) System.out.println("Yes1"); scan.close(); } }
7.其他类型的输入 nextDouble(); nextLong(); nextInt(); nextFloat(); nextByte(); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |