• 用户交互Scanner学习


        /**
         * 学习Scanner类
         *java.util.Scanner是Java5的新特征,用来获取用户的输入,实现程序与人的交互;
         * 基本语法:
         * Scanner s = new Scanner(System.in);
         * 通过Scanner类的next()与nextLine()方法获取输入的字符串,在读取前我们一般需要使用
         * hasNext()与hasNextLine()判断是否还有输入的数据
         *
         */
    package JavaBasics;
    
    import java.util.Scanner;
    
    public class Demo2 {
    
        public static void main1(String[] args) {
    
            //创建一个扫描器对象,用于接收键盘数据
            Scanner scanner = new Scanner(System.in);
            System.out.println("使用next方式接收:");
    
            //判断用户有没有输入字符串
            if (scanner.hasNext()){
                //使用next方式接收
                String s = scanner.next();
                System.out.println("输出的内容为:"+s);
            }
    
            //凡是属于IO流的类如果不关闭会一直占用资源,要养成好习惯用完就关闭
            scanner.close();
        }
    
        public static void main(String[] args) {
    
            //创建一个扫描器对象,用于接收键盘数据
            Scanner scanner = new Scanner(System.in);
            System.out.println("使用nextLine方式接收:");
    
            //判断用户有没有输入字符串
            if (scanner.hasNextLine()){
                //使用next方式接收
                String s = scanner.nextLine();
                System.out.println("输出的内容为:"+s);
            }
    
            //凡是属于IO流的类如果不关闭会一直占用资源,要养成好习惯用完就关闭
            scanner.close();
        }
      
    }
    1)使用next()结果;

    使用next方式接收:
    Hello word
    输出的内容为:Hello


    2)使用nextLine()结果;

    使用nextLine方式接收:
    hello word
    输出的内容为:hello word


    /** * next()和nextLine()区别; * next(): * 1、一定要读取到有效字符后才可以结束输入; * 2、对输入有效字符之前遇到的空白,next()方法会自动将其去掉; * 3、只有输入有效字符后才将输入的空白作为分隔符或者结束符; * 4、next()不能得到带有空格的字符串; * * nextLine(); * 1、以Enter为结束符,也就是说,nextLine()方法返回的是输入回车之前的所有字符; * 2、可以获取空白; */
  • 相关阅读:
    js获取url参数
    css3 text-shadow字体阴影讲解
    css3 box-shadow阴影(外阴影与外发光)讲解
    【leetcode刷题笔记】Palindrome Partitioning II
    【leetcode刷题笔记】Minimum Window Substring
    【leetcode刷题笔记】Interleaving String
    【leetcode刷题笔记】Wildcard Matching
    【leetcode刷题笔记】Regular Expression Matching
    【leetcode刷题笔记】Insert Interval
    【leetcode刷题笔记】Multiply Strings
  • 原文地址:https://www.cnblogs.com/xie-qi/p/14018856.html
Copyright © 2020-2023  润新知