[英]Scanner.nextLine() return null
I had written this code :我写了这段代码:
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;
}
}
}
Input which is entered:输入的输入:
1
aa
ab
but the value of variable a is null ..WHY??但是变量 a 的值为 null ..WHY?? Please explain .Also please correct the code so that it reads full input.
请解释。也请更正代码,以便它读取完整的输入。
That's because you are entered 1 followed by an enter .那是因为您输入了 1 ,然后输入了 enter 。 So your nextLine method call just reads return key while nextInt just reads integer value ignoring the return key.
因此,您的 nextLine 方法调用仅读取返回键,而 nextInt 仅读取忽略返回键的整数值。 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());
when you use当你使用
int test=scan.nextInt();
the carriage return that you push after entering the Integer does not get read off the input stream, so what you can do is输入整数后按下的回车不会从输入流中读取,所以你可以做的是
int test=scan.nextInt();
scan.nextLine();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.