15-Scanner 对象







Scanner 对象

之前的基本语法中没有实现程序和人的互动。JAVA 存在一个工具类 java.util.ScannerJAVA5 的新特征。可以通过 Scanner 类来获取用户的输入。

next()


public class Demo_1 {
    public static void main(String[] args) {
        //创建一个扫描器对象,用于接受键盘数据
        Scanner scanner = new Scanner(System.in);
        System.out.println("使用next方式接收");
        //判断用户有没有输入字符串
        if (scanner.hasNext()){
            //使用next方式接收
            String Str = scanner.next();
            System.out.printf("输入的内容为:" + Str);
        }
        //关闭scanner
        //凡是属于IO流的类如果不关闭会一直占用资源
        scanner.close();
    }
}
  • next()

    • 一定要读取到有效字符后才可以结束输入

    • 对输入有效字符之前遇到的空白,next() 方法会自动将其去除

    • 只有输入有效字符后才将其后面输入的空白作为分隔符或者结束符

    • next() 不能得到带有空格的字符串

nextLine()


public class Demo_02 {
    public static void main(String[] args) {
        //创建一个扫描对象,用于接收键盘数据
        Scanner scanner = new Scanner(System.in);
        System.out.println("使用nextLin方式接收");
        //判断用户有没有输入字符串
        if (scanner.hasNextLine()){
            //使用nextLine方式接收
            String str = scanner.nextLine();
            System.out.println("输出内容为:" + str);
        }
        scanner.close();
    }
}
  • Enter 为结束符,也就是说 nextLine() 方法返回的是输入回车之前的所有字符

  • 可以获得空白

public class Demo_03 {
    public static void main(String[] args) {
        //创建新的扫描对象 scanner 用于接收用户的输入
        Scanner scanner = new Scanner(System.in);
        //告诉用户可以输入数据
        System.out.println("请输入数据:");
        //将用户输入的数据赋值给 str 变量
        String str = scanner.nextLine();
        //输出用户输入的数据
        System.out.println("你输入的数据为:" + str);
        //关闭scanner
        scanner.close();
    }
}


暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇