Scanner.nextLine()返回null [英] Scanner.nextLine() return null
本文介绍了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 ??请解释。也请更正代码,以便它读取完整的输入。
but the value of variable a is null ..WHY?? Please explain .Also please correct the code so that it reads full input.
推荐答案
那是因为你输入1然后输入。因此,您的nextLine方法调用只读取返回键,而nextInt只读取整数值而忽略返回键。要避免此问题:
That's because you are entered 1 followed by an enter . So your nextLine method call just reads return key while nextInt just reads integer value ignoring the return key. To avoid this issue:
在阅读输入后,您会调用以下内容:
Just after reading input, you call something like:
int test=scan.nextInt();
scan.nextLine();//to read the return key.
如果你想避免这种情况,那我建议你读完整行然后将其转换为整数。有些事情如下:
If you want to avoid that as well, then i would suggest, you read the whole line and then convert it to integer. Some thing like:
int test=Integer.parseInt(scan.nexLine());
这篇关于Scanner.nextLine()返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文