这么安排的作用就是把输入输出的部分和算法实现的部分隔开,让我们在做题的时候能够还原核心算法模式下的习惯
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while(sc.hasNext()) {
int a = sc.nextInt();
// 更通用的方法是用nextLine()获取一整行的输入,然后再进行处理
// String a = sc.nextLine();
int result = solution(a);
System.out.println(result);
}
}
public static Integer solution(int a) {
// 此处为对拿到a之后的处理逻辑,假设处理结果为result
return result;
}
}
nextInt和nextLine的注意细节
Scanner sc = new Scanner(System.in);
// 先读取键盘输入的int值
System.out.println("input id :");
int id = sc.nextInt();
// 后读取键盘输入的字符串
System.out.println("input name :");
String name = sc.nextLine();
System.out.println("id = " + id + " name =[" + name + "]");
System.out.println("execute finish !");
运行程序
input id :
0 //键盘输入
input name :
程序输出
id = 0 name =[]
execute finish !
原因如下:
nextInt方法根据分隔符(回车,空格等)只取出输入的流中分割的第一部分并解析成Int,然后把后面的字节传递下去。
所以,第二种情况键盘实际输入是“0+回车”,nextInt读出了“0”,并留下了“回车”,
接着netxLine读到了一个“回车”,这是字符串的结束判定符啊,所以读到的字符串就是空字符串“”。