我写了这段代码:
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 ..为什么?请解释一下。另请更正代码,以便它读取完整的输入。
最佳答案
那是因为您输入了 1 ,然后输入了 Enter 。因此,您的 nextLine 方法调用仅读取返回键,而 nextInt 仅读取整数值,忽略返回键。为了避免这个问题:
读取输入后,您可以调用如下内容:
int test=scan.nextInt();
scan.nextLine();//to read the return key.
如果您也想避免这种情况,那么我建议您阅读整行,然后将其转换为整数。比如:
int test=Integer.parseInt(scan.nexLine());
关于java - Scanner.nextLine() 返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28623651/