zoukankan      html  css  js  c++  java
  • Scanner类的next()方法和nextLine()方法的异同点

    通过一段代码就可以明白其中的奥妙!!

     1 import java.util.Scanner;
     2 
     3 public class next_nextLine {
     4     public static void main(String[] args) {
     5         Scanner s = new Scanner(System.in);
     6 
     7         System.out.println("输入第一个字符串:");
     8         String s1 = s.nextLine();
     9         System.out.println(s1);
    10 
    11         System.out.println("输入第二个字符串:");
    12         String s2 = s.next();
    13         System.out.println(s2);
    14 
    15     }
    16 }

    输出结果:

    结论:

    next()方法不能读取空白符,读到空白字符就结束!(包括tab、空格、回车)

    nextLine()方法可以读取空格,遇到回车符结束!

    再来看一段代码

     1 import java.util.Scanner;
     2 
     3 public class next_nextLine {
     4     public static void main(String[] args) {
     5         Scanner s = new Scanner(System.in);
     6 
     7         System.out.println("输入第一个字符串:");
     8         String s1 = s.next();//交换next()和nextLine()方法的位置
     9         System.out.println(s1);
    10 
    11         System.out.println("输入第二个字符串:");
    12         String s2 = s.nextLine();
    13         System.out.println(s2);
    14 
    15     }
    16 }

    输出结果:

    结论:

      根据之前的结论,next()方法读取到空白符就结束,nextLine()读取到回车结束也就是“ ”,那么我们上面遇到的问题就是next()读取到空白符前的数据就结束了,把回车“ ”留给了nextLine(),所以nextLine()没有给你输入的机会,就直接结束了。

    解决办法:在next()下面再加一个nextLine()

     1 import java.util.Scanner;
     2 
     3 public class next_nextLine {
     4     public static void main(String[] args) {
     5         Scanner s = new Scanner(System.in);
     6 
     7         System.out.println("输入第一个字符串:");
     8         String s1 = s.next();//交换next()和nextLine()方法的位置
     9         System.out.println(s1);
    10 
    11         s.nextLine();
    12 
    13         System.out.println("输入第二个字符串:");
    14         String s2 = s.nextLine();
    15         System.out.println(s2);
    16 
    17     }
    18 }

    输出结果:

  • 相关阅读:
    UE4 WCF RestFul 服务器 读取JSON 数据并解析 简单实例
    Android aidl Binder框架浅析
    AIDL
    android 五种存储方式
    Android进程间通信机制
    Service全面总结
    Android平台中关于音频播放
    Android广播机制
    Cursor,CursorAdapter中的观察者模式解析
    ContentProvider和Uri详解
  • 原文地址:https://www.cnblogs.com/sunbr/p/11622942.html
Copyright © 2011-2022 走看看