Scanner.nextLine()返回null

我写过这段代码:

class PerfectPair { public static void main(String args[]) throws IOException{ Scanner scan = new Scanner(System.in); int test=scan.nextInt(); StringBuffer b=null; String a=null; while(test!=0){ a=scan.nextLine(); b=new StringBuffer(scan.nextLine()); System.out.println(a); String reverse=b.reverse().toString(); if((a.length()!=b.length()) || !(reverse.equals(a))){ System.out.println("No"); } else { if((a.length()==b.length()) && (reverse.equals(a))) System.out.println("Yes"); } --test; } } } 

输入的输入:

 1 aa ab 

但变量a的值为null ..WHY ?? 请解释。也请更正代码,以便读取完整输入。

那是因为你输入1然后输入。 因此,您的nextLine方法调用只读取返回键,而nextInt只读取整数值而忽略返回键。 要避免此问题:

阅读输入后,您可以调用以下内容:

 int test=scan.nextInt(); scan.nextLine();//to read the return key. 

如果你想避免这种情况,那么我建议你读完整行然后将其转换为整数。 就像是:

 int test=Integer.parseInt(scan.nexLine()); 

当你使用

 int test=scan.nextInt(); 

在输入整数后你输入的回车不会从输入流中读出,所以你可以做的就是

 int test=scan.nextInt(); scan.nextLine();