当前位置:网站首页>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
边栏推荐
- 系统与软件安全研究(五)
- Redis connection error err auth < password > called without any password configured for the default user
- 解决在docker中部署mysql8, 密码正确但无法登陆MySQL问题
- Mobile game performance optimization
- Custom time format (yyyy-mm-dd HH: mm: SS week x)
- Window10版MySQL设置远程访问权限后不起效果
- js中对象的三种创建方式
- SAP DEBUG调试FOR IN、REDUCE等复杂的语句
- SQL针对字符串型数字进行排序
- Understanding of STL container
猜你喜欢

SAP ECC连接SAP PI系统配置

Ogldev reading notes

移动端布局(3D转换、动画)

Window10版MySQL设置远程访问权限后不起效果

命令行参数传递库argparse的使用

SQL针对字符串型数字进行排序

使用flask时代码无报错自动结束,无法保持连接,访问不了url。

Teach-Repeat-Replan: A Complete and Robust System for Aggressive Flight in Complex Environments

SAP Excel 已完成文件级验证和修复。此工作簿的某些部分可能已被修复或丢弃。

'NPM' is not an internal or external command, nor is it a runnable program or batch file
随机推荐
js之自定义属性以及H5中如何判断自定义属性
js中对象的三种创建方式
Quick sort
Nodejs (VI) sub process operation
MySQL index
FSM finite state machine
SVG中年月日相关的表达式
保研准备经验贴——18届(2021年)中南计科推免到浙大工院
基于NLP的软件安全研究(一)
ABAP CDS VIEW WITH ASSOCIATION示例
ABAP 实现发布RESTful服务供外部调用示例
C# SmoothProgressBar自定义进度条控件
面经的总结
js之排他思想及案例
平面定义-平面方程
给定区段范围内字符串自生成代码
对js中argumens的简单理解
Game assisted script development journey
canvas学习第一篇
NodeJS(四) 字符读取