博客
关于我
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/

你可能感兴趣的文章
order by rand()
查看>>
Orderer节点启动报错解决方案:Not bootstrapping because of 3 existing channels
查看>>
org.apache.axis2.AxisFault: org.apache.axis2.databinding.ADBException: Unexpected subelement profile
查看>>
org.apache.commons.beanutils.BasicDynaBean cannot be cast to ...
查看>>
org.apache.dubbo.common.serialize.SerializationException: com.alibaba.fastjson2.JSONException: not s
查看>>
sqlserver学习笔记(三)—— 为数据库添加新的用户
查看>>
org.apache.ibatis.exceptions.PersistenceException:
查看>>
org.apache.ibatis.exceptions.TooManyResultsException: Expected one result (or null) to be returned
查看>>
org.apache.ibatis.type.TypeException: Could not resolve type alias 'xxxx'异常
查看>>
org.apache.poi.hssf.util.Region
查看>>
org.apache.xmlbeans.XmlOptions.setEntityExpansionLimit(I)Lorg/apache/xmlbeans/XmlOptions;
查看>>
org.apache.zookeeper.KeeperException$ConnectionLossException: KeeperErrorCode = ConnectionLoss for /
查看>>
org.hibernate.HibernateException: Unable to get the default Bean Validation factory
查看>>
org.hibernate.ObjectNotFoundException: No row with the given identifier exists:
查看>>
SQL-CLR 类型映射 (LINQ to SQL)
查看>>
org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
查看>>
org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
查看>>
org.springframework.web.multipart.MaxUploadSizeExceededException: Maximum upload size exceeded
查看>>
org.tinygroup.serviceprocessor-服务处理器
查看>>
org/eclipse/jetty/server/Connector : Unsupported major.minor version 52.0
查看>>