JAVA中Scanner的用法

——简单例子——

1
2
3
4
5
6
7
8
9
10
11
public class TestScanner {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("请输入字符串:");
while (true) {
String line = s.nextLine();
if (line.equals("exit")) break;
System.out.println(">>>" + line);
}
}
}

Attention

1.Scanner默认使用空格作为分割符来分隔文本,但允许你指定新的分隔符
2.一大堆API函数:
(API(Application Programming Interface,应用程序编程接口)是一些预先定义的函数,目的是提供应用程序与开发人员基于某软件或硬件得以访问一组例程的能力,而又无需访问源码,或理解内部工作机制的细节。)
delimiter()
返回此 Scanner 当前正在用于匹配分隔符的 Pattern。
hasNext()
判断扫描器中当前扫描位置后是否还存在下一段。
hasNextLine()
如果在此扫描器的输入中存在另一行,则返回 true。
next()
查找并返回来自此扫描器的下一个完整标记。
nextLine()
此扫描器执行当前行,并返回跳过的输入信息。

关于scanner的练习题

1.HDOJ<1000>-A+B problem

request: Each line will contain two integers A and B. Process to end of file.For each case, output A + B in one line.

1
2
3
4
5
6
7
8
9
10
11
12
13
import java.util.*;
public class Main
{
public static void main(String args[])
{
Scanner str = new Scanner(System.in);
while(str.hasNext())
{
int a = str.nextInt(),b = str.nextInt();
System.out.println(a+b);
}
}
}

2.HDOJ<1001>-Sum Problem

request: In this problem, your task is to calculate SUM(n) = 1 + 2 + 3 + … + n.The input will consist of a series of integers n, one integer per line.
For each case, output SUM(n) in one line, followed by a blank line. You may assume the result will be in the range of 32-bit signed integer.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import java.util.*;
public class Main
{
public static void main(String args[])
{
Scanner str = new Scanner(System.in);
while(str.hasNext())
{
int n = str.nextInt(),sum=0;
for(int i=1;i<=n;i++)
sum+=i;
System.out.println(sum);
System.out.println();
}
}
}

关于Scanner的链接

链接