Scanner类用法
2016-04-22 14:55
85 查看
Scanner类主要用于获取控制台输入,当通过new Scanner (System.in) 创建一个Scanner,控制台会一直等待输入,直到敲回车键结束,把所有的内容传给Scanner,作为扫描对象。如果要获取输入的内容,则只需调用Scanner的nextLine()方法即可。
Scanner是SDK1.5新增的一个类,可是使用该类创建一个对象.
Scanner reader=new Scanner(System.in);
然后reader对象调用下列方法(函数),读取用户在命令行输入的各种数据类型
next.Byte(),nextDouble(),nextFloat,nextInt(),nextLine(),nextLong(),nextShot()
上述方法执行时都会造成堵塞,等待用户在命令行输入数据回车确认.例如,拥护在键盘输入
12.34,hasNextFloat()的值是true,而hasNextInt()的值是false, NextLine()等待用户输入一个文
本行并且回车,该方法得到一个String类型的数据。
delimiter() 返回此 Scanner 当前正在用于匹配分隔符的 Pattern。
hasNext() 判断扫描器中当前扫描位置后是否还存在下一段。(
hasNextLine() 如果在此扫描器的输入中存在另一行,则返回 true。
next() 查找并返回来自此扫描器的下一个完整标记。
nextLine() 此扫描器执行当前行,并返回跳过的输入信息。
例子:
Calculate a + b
import java.util.Scanner;
public class AsumB {
public static void main(String[] args){
Scanner reader = new Scanner(System.in);
while(reader.hasNextInt() == true){
int a = reader.nextInt();
int b = reader.nextInt();
int sum = a+b;
System.out.println(sum);
}
}
}
Scanner是SDK1.5新增的一个类,可是使用该类创建一个对象.
Scanner reader=new Scanner(System.in);
然后reader对象调用下列方法(函数),读取用户在命令行输入的各种数据类型
next.Byte(),nextDouble(),nextFloat,nextInt(),nextLine(),nextLong(),nextShot()
上述方法执行时都会造成堵塞,等待用户在命令行输入数据回车确认.例如,拥护在键盘输入
12.34,hasNextFloat()的值是true,而hasNextInt()的值是false, NextLine()等待用户输入一个文
本行并且回车,该方法得到一个String类型的数据。
delimiter() 返回此 Scanner 当前正在用于匹配分隔符的 Pattern。
hasNext() 判断扫描器中当前扫描位置后是否还存在下一段。(
hasNextLine() 如果在此扫描器的输入中存在另一行,则返回 true。
next() 查找并返回来自此扫描器的下一个完整标记。
nextLine() 此扫描器执行当前行,并返回跳过的输入信息。
例子:
Calculate a + b
Input
The input will consist of a series of pairs of integers a and b,separated by a space, one pair of integers per line.Output
For each pair of input integers a and b you should output the sum of a and b in one line,and with one line of output for each line in input.Sample Input
1 5
import java.util.Scanner;
public class AsumB {
public static void main(String[] args){
Scanner reader = new Scanner(System.in);
while(reader.hasNextInt() == true){
int a = reader.nextInt();
int b = reader.nextInt();
int sum = a+b;
System.out.println(sum);
}
}
}
相关文章推荐
- LeetCode 73. Set Matrix Zeroes
- Node 究竟是什么
- win10+boost for gcc
- 将制作好的系统安装到硬盘上
- xmarin.android for vs2015使用百度地图api3.6.1
- iOS----自定义UIView,绘制一个UIView
- 1001. 害死人不偿命的(3n+1)猜想 (15)
- 最牛x的滚动插件 – jquery的iscroll插件(附上下拉刷新消息demo)
- The method getJspApplicationContext(ServletContext) is undefined for the type JspFactory的解决方法
- iOS UserAgent 设置
- CSS3过渡
- CQRS架构简介
- POJ1067 取石子游戏(威佐夫博弈)
- getopts详解
- 二叉树算法引发的指针参数传递和引用的思考
- android项目中,测试Socket连接时遇到的问题
- 使用PowerDesigner画ER图详细教程
- Socket编程int与byte array之间互相转换
- Apriori关联分析
- c++ 指针、引用、内存管理、函数(引用、重载、内敛)——c++复习(一)