当前位置:网站首页>03Scanner类的使用(控制台输入)
03Scanner类的使用(控制台输入)
2022-04-23 06:28:00 【夜夜夜空】
一、next()和nextLine()
Scanner用完一定要关闭,scanner.close()
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入");
if (scanner.hasNext()){
System.out.println(scanner.next());
}
System.out.println("请输入");
if (scanner.hasNext()){
System.out.println(scanner.next());
}
}
输出结果:
请输入
jj
jj
请输入
kk
kk
public static void main1(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入");
if (scanner.hasNextLine()){
System.out.println(scanner.nextLine());
}
}
- next()
1.一定要读取到有效字符后才能结束输入,空格不属于有效字符
2.对于有效字符前的空白或空格,自动去除
3.有效字符后遇到空白,自动识别为分隔符,后面的内容作为下一个next的内容
4.不可能存在空白和空格 - nextLine()
1.空格为有效字符
2.可以输入空白
二、hasNextXxx()和nextXxx()
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入");
if (scanner.hasNextInt()){
System.out.println(scanner.nextInt());
}
System.out.println("请输入");
if (scanner.hasNextInt()){
System.out.println(scanner.nextInt());
}
System.out.println("请输入");
if (scanner.hasNextFloat()){
System.out.println(scanner.nextFloat());
}
}
输出结果:
请输入
11 22 1.2
11
请输入
22
请输入
1.2
多个nextXxx()可以在一行一次性输入,每个参数用空格分隔
三、使用while
float m = 0f;
System.out.println("请输入float");
while (scanner.hasNextFloat()){
m += scanner.nextFloat();
System.out.println("请输入float");
}
System.out.println("最后m="+m);
当条件成立时,可以一直输入,直到条件不成立
版权声明
本文为[夜夜夜空]所创,转载请带上原文链接,感谢
https://blog.csdn.net/zixuanyankai/article/details/123119570
边栏推荐
猜你喜欢
Mongodb 启动警告信息处理
canvas学习第一篇
防抖和节流
SAP DEBUG调试FOR IN、REDUCE等复杂的语句
对复杂字典Dictionary<T1,T2>排序问题
How to judge whether a point is within a polygon (including complex polygons or a large number of polygons)
BTREE, B + tree and hash index
Authorization server (simple construction of authorization server)
SAP 导出Excel文件打开显示:“xxx“的文件格式和扩展名不匹配。文件可能已损坏或不安全。除非您信任其来源,否则请勿打开。是否仍要打开它?
Configure NPM
随机推荐
Date object (JS built-in object)
C# 文本文件的查找及替换(WinForm)
unity UGUI判断点击在UI上和3D物体上的解决方案
unity 屏幕自适应
FUEL: Fast UAV Exploration using Incremental Frontier Structure and Hierarchical Planning
SAP SALV14 后台输出SALV数据可直接保存文件,发送Email(带排序、超链接、筛选格式)
SAP PI/PO功能运行状态监控检查
C#操作注册表全攻略
将单行文字自动适应到目标矩形框内
NodeJS(四) 字符读取
颜色转换公式大全及转换表格(31种)
ABAP 7.4 SQL Window Expression
取得所有点列表中的最大值GetMaxPoint
对js中argumens的简单理解
C reads the registry
Mobile game performance optimization
js之DOM事件
js之函数的两种声明方式
C# 读取注册表
Unity ugui determines the solution of clicking on the UI and 3D objects