您的位置:首页 > 其它

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

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);

}
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: