博客
关于我
JAVA流程控制01——用户交互Scanner和scanner的进阶使用
阅读量:250 次
发布时间:2019-03-01

本文共 1832 字,大约阅读时间需要 6 分钟。

Java流程控制——用户交互Scanner和Scanner的进阶使用

Scanner对象

在Java编程中,Scanner类是处理用户输入的强大工具。它提供了两种主要方法来获取输入:next()和nextLine()。在使用这些方法之前,我们需要先检查是否有输入数据可以读取。这可以通过hasNext()和hasNextLine()方法实现。

next()与nextLine()的区别

next()方法

  • 特点
    • 一定要读取到有效字符才可以结束输入。
    • 输入的有效字符之前遇到的空白会被自动去掉。
    • 只有在读取到有效字符后,才会将其后面的空白作为分隔符或结束符。
    • 不能得到带有空格的字符串。

nextLine()方法

  • 特点
    • 以回车(Enter)为结束符,返回的是输入的回车字符。
    • 之前的所有字符,包括空白,都可以被获取。

示例

示例1:读取单行输入

Scanner scanner = new Scanner(System.in);System.out.println("请输入一个数字:");String input = scanner.nextLine();System.out.println("您输入的内容是:" + input);

示例2:读取多行输入

Scanner scanner = new Scanner(System.in);System.out.println("请输入多个数字,每行一个:");while (scanner.hasNext()) {    String input = scanner.next();    System.out.println("您输入的内容是:" + input);}

关闭资源

记住,Scanner类是资源密集型的。使用完毕后,必须及时关闭:

scanner.close();

扩展:不加判断直接使用

有时候,我们可以直接使用Scanner类来获取输入,而无需判断是否有输入。这种方法简单易懂:

Scanner scanner = new Scanner(System.in);System.out.println("请输入数字(按回车结束):");String input = scanner.nextLine();System.out.println("您输入的内容是:" + input.replace(" ", ""));

Scanner的进阶使用

示例:判断输入类型

Scanner scanner = new Scanner(System.in);System.out.println("请输入一个数:");String input = scanner.nextLine();double number = Double.parseDouble(input);if (number % 1 == 0) {    System.out.println("这是一个整数:" + number);} else {    System.out.println("这是一个小数:" + number);}

示例:计算总和与平均数

Scanner scanner = new Scanner(System.in);System.out.println("请输入多个数字(每行一个,按回车结束):");List
numbers = new ArrayList<>();while (scanner.hasNext()) { String input = scanner.next(); if (scanner.hasNextLine()) { numbers.add(Double.parseDouble(input)); } else { break; }}double sum = numbers.stream().mapToDouble(Double::doubleValue).sum();double average = sum / numbers.size();System.out.println("总和为:" + sum);System.out.println("平均数为:" + average);

通过以上方法,您可以灵活地处理用户输入,实现各种交互场景。记得在使用完Scanner后,及时关闭资源以避免内存泄漏。

转载地址:http://oqov.baihongyu.com/

你可能感兴趣的文章
npm报错Cannot find module ‘webpack‘ Require stack
查看>>
npm报错Failed at the node-sass@4.14.1 postinstall script
查看>>
npm报错fatal: Could not read from remote repository
查看>>
npm报错File to import not found or unreadable: @/assets/styles/global.scss.
查看>>
npm报错TypeError: this.getOptions is not a function
查看>>
npm报错unable to access ‘https://github.com/sohee-lee7/Squire.git/‘
查看>>
npm淘宝镜像过期npm ERR! request to https://registry.npm.taobao.org/vuex failed, reason: certificate has ex
查看>>
npm版本过高问题
查看>>
npm的“--force“和“--legacy-peer-deps“参数
查看>>
npm的安装和更新---npm工作笔记002
查看>>
npm的常用操作---npm工作笔记003
查看>>
npm的常用配置项---npm工作笔记004
查看>>
npm的问题:config global `--global`, `--local` are deprecated. Use `--location=global` instead 的解决办法
查看>>
npm编译报错You may need an additional loader to handle the result of these loaders
查看>>
npm设置淘宝镜像、升级等
查看>>
npm设置源地址,npm官方地址
查看>>
npm设置镜像如淘宝:http://npm.taobao.org/
查看>>
npm配置安装最新淘宝镜像,旧镜像会errror
查看>>
NPM酷库052:sax,按流解析XML
查看>>
npm错误 gyp错误 vs版本不对 msvs_version不兼容
查看>>