• 【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()只读取数值,剩下” ”还没有读取,并将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 ). 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用法总结

  • 相关阅读:
    Go语言实现:【剑指offer】跳台阶
    Go语言实现:【剑指offer】斐波那契数列
    Go语言实现:【剑指offer】栈的压入、弹出序列
    Go语言实现:【剑指offer】替换空格
    Go语言实现:【剑指offer】表示数值的字符串
    Go语言实现:【剑指offer】第一个只出现一次的字符位置
    Go语言实现:【剑指offer】把字符串转换成整数
    Go语言实现:【剑指offer】翻转单词顺序列
    robot framework使用小结(二)
    robot framework使用小结(一)
  • 原文地址:https://www.cnblogs.com/yongh/p/9124905.html
Copyright © 2020-2023  润新知