zoukankan      html  css  js  c++  java
  • java.util.Scanner 总结

     java.util.Scanner 用来取得用户的输入:

    Scanner scan=new Scanner(System.in);//System.in in表示inputStream
    int a=scan.nextInt();
    
    String a=scan.nextLine();
    
    double a=scan.nextDouble();
    java.util.Scanner的总结
    //构造方法(常用的三个)
    //Scanner(File source)
    //Scanner(InputStream source)
    //Scanner(String source)
    
    //对比两种方式的比较
    //Scanner sc=new Scanner(System.in); 
    //BufferedReader br=new BufferedReader(new InputStreamReader(System.in)) 
    
    //方法
    //useDelimiter(Pattern pattern)改变token的分割方式,默认的是空格,传Pattern对象
    //useDelimiter(String pattern)改变token的分割方式,默认的是空格,传String
    
    //hasNext();查看是否有token的分割段
    //hasNextInt();查看是否有int类型的token的分割段
    //nextInt();返回下一个int的数值
    //nextLine();返回一行
    
    //hasNext(Pattern pattern);返回下一个pattern类型的token
    
    public class ScannerTest {
        public static void main(String[] args){
            String str = "1.1 22.2 s 4 5.3 6 7.5 8 9";
            Scanner scanner = new Scanner(str);
            //scanner.useDelimiter("\\.");
            while(scanner.hasNext()){
                if(scanner.hasNext(Pattern.compile("\\d\\.\\d"))){
                    System.out.println(scanner.next());
                }else{
                    scanner.next();//要调用一下next()相关的方法才会到下一个token
                }
            }            
        }
    }
    
    结果:
    1.1
    5.3
    7.5
    
    
    public class ScannerTest {
        public static void main(String[] args){
            String str = "1.2 s.4 5 6.7 8 9";
            Scanner scanner = new Scanner(str);
                      //token以.分割
            scanner.useDelimiter("\\.");
            while(scanner.hasNext()){
                System.out.println(scanner.next());
            }            
        }
    }

    The main use of java.util.Scanner is to read values from System.in or a file.

    Many Scanner methods fit a simple patternnextXYZ() scans and returns a value of type XYZ.hasNextXYZ() returns true if something of type XYZ is available to be read next.

     scanner.close() close the inputStream.

    参考:

    http://www.leepoint.net/notes-java/summaries/summary-scanner.html

  • 相关阅读:
    mvc中使用Hangfire处理后台任务
    mvc中图片的保存和显示
    WebVTT 及 HTML5 <track> 元素简介
    vs2015发布网站至azure web应用服务
    jquery上传大文件至azure blob存储
    dapper利用DynamicParameters构建动态参数查询
    aspnetcore的那些actionresult们
    vs2015 debugger,unable to attach to application iisexpress.exe
    ASP.NET’s compilation system
    Introducing .NET Standard
  • 原文地址:https://www.cnblogs.com/youxin/p/2601351.html
Copyright © 2011-2022 走看看