[Java] Scanner类的几个方法

  通过 Scanner 类可以获取用户的输入,创建 Scanner 对象的基本语法如下:

Scanner sc = new Scanner(System.in);

 

nextInt()、next()和nextLine()

  nextInt(): it only reads the int value, nextInt() places the cursor(光标) in the same line after reading the input.(nextInt()只读取数值,剩下”\n”还没有读取,并将cursor放在本行中)

  next(): read the input only till the space. It can’t read two words separated by space. Also, next() places the cursor in the same line after reading the input.(next()只读空格之前的数据,并且cursor指向本行) 
  next() 方法遇见第一个有效字符(非空格,非换行符)时,开始扫描,当遇见第一个分隔符或结束符(空格或换行符)时,结束扫描,获取扫描到的内容,即获得第一个扫描到的不含空格、换行符的单个字符串。

  nextLine(): reads input including space between the words (that is, it reads till the end of line \n). Once the input is read, nextLine() positions the cursor in the next line. 
  nextLine()时,则可以扫描到一行内容并作为一个字符串而被获取到。

public class NextTest{  
    public static void main(String[] args) {  
        String s1,s2;  
        Scanner sc=new Scanner(System.in);  
        System.out.print("请输入第一个字符串:");  
        s1=sc.nextLine();  
        System.out.print("请输入第二个字符串:");  
        s2=sc.next();  
        System.out.println("输入的字符串是:"+s1+" "+s2);  
    }  
}  

  

请输入第一个字符串:abc
请输入第二个字符串:def
输入的字符串是:abc def
View Code
//s1、s2交换
public class NextTest {
	    public static void main(String[] args) {  
	        String s1,s2;  
	        Scanner sc=new Scanner(System.in);  
	        System.out.print("请输入第一个字符串:");  
	        s1=sc.next();  
	        System.out.print("请输入第二个字符串:");  
	        s2=sc.nextLine();  
	        System.out.println("输入的字符串是:"+s1+" "+s2);  
	    }  
}

  

请输入第一个字符串:abc
请输入第二个字符串:输入的字符串是:abc 
View Code

  nextLine()自动读取了被next()去掉的Enter作为他的结束符,所以没办法给s2从键盘输入值。

  如double nextDouble() , float nextFloat() , int nextInt() 等与nextLine()连用时都存在这个问题,解决的办法是:在每一个 next()、nextDouble() 、 nextFloat()、nextInt() 等语句之后加一个nextLine()语句,将被next()去掉的Enter结束符过滤掉。

public class NextTest{  
    public static void main(String[] args) {  
        String s1,s2;  
        Scanner sc=new Scanner(System.in);  
        System.out.print("请输入第一个字符串:");  
        s1=sc.next();  
        sc.nextLine();
        System.out.print("请输入第二个字符串:");  
        s2=sc.nextLine();  
        System.out.println("输入的字符串是:"+s1+" "+s2);  
    }  
}

  

请输入第一个字符串:abc
请输入第二个字符串:def
输入的字符串是:abc def
View Code

参考来源:Java中Scanner用法总结

猜你喜欢

转载自www.cnblogs.com/yongh/p/9124905.html
今日推荐