Scanner类的方法更加灵活多样,得到了更多的应用。 最近刷题遇到String数组输入的情况,发现Scanner方法nextLine()、next()、nextInt()的一些区别。要求先输入一个正整数n,然后输入n个字符串,代码如下: import java.util.Scanner;
public class MyCode2{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int n=0;
while(sc.hasNext()){
n = sc.nextInt();
String[] s = new String[n];
int count=0;
while(count回车->....”,第一个回车后程序不等你输入而直接输出“s[0]:”,因为nextLine()首先读到的是上次输入遗留在缓冲区里的第一个回车,然后直接返回空。当输入过程为“3->空格->abc->回车->dfg....”,nextLine()返回的是“空格abc”。调用nextLine()输入字符串前调用一次nextLine()清除缓存,即 import java.util.Scanner;
public class MyCode2{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int n=0;
while(sc.hasNext()){
n = sc.nextInt();
String[] s = new String[n];
int count=0;
sc.nextLine();
while(count |