java.util.NoSuchElementException-扫描仪读取用户输入的行为异常
我正试图通过扫描器获取用户输入,并在HackerRank上提交此代码,获得上述异常。我试着在我的机器上运行相同的测试用例,没有发现异常,代码运行良好。我没有学到Java中的流,请帮助我找出错误java.util.NoSuchElementException-扫描仪读取用户输入的行为异常,java,Java,我正试图通过扫描器获取用户输入,并在HackerRank上提交此代码,获得上述异常。我试着在我的机器上运行相同的测试用例,没有发现异常,代码运行良好。我没有学到Java中的流,请帮助我找出错误 import java.io.IOException; import java.util.Scanner; public class Solution{ public static void main(String a[]) throws IOException, Exception {
import java.io.IOException;
import java.util.Scanner;
public class Solution{
public static void main(String a[]) throws IOException, Exception {
Scanner in = new Scanner(System.in);
int test = in.nextInt();
Scanner in1 = new Scanner(System.in);
if (test < 1 || test > 10) {
throw new Exception("Illegal test cases");
}
while (test-- > 0) {
// System.out.println("Enter patient dna");
String patient = in1.nextLine().toLowerCase();
// System.out.println("Enter virus dna");
String virus = in1.nextLine().toLowerCase();
int l = virus.length();
int i = 0;
int count = 0;
if (patient.length() > 100000 || virus.length() > 100000) {
throw new Exception("Input length out of bounds");
}
for (i = 0; i < patient.length() - virus.length() + 1; i++) {
String sub = patient.substring(i, i + l);
count = 0;
for (int j = 0; j < sub.length(); j++) {
if (virus.charAt(j) != sub.charAt(j)) {
count++;
}
}
if (count == 0 || count == 1) {
System.out.print(i + " ");
}
}
System.out.println();
}
}
}
import java.io.IOException;
导入java.util.Scanner;
公共类解决方案{
publicstaticvoidmain(字符串a[])抛出IOException,Exception{
扫描仪输入=新扫描仪(系统输入);
int test=in.nextInt();
扫描器in1=新扫描器(System.in);
如果(测试<1 | |测试>10){
抛出新异常(“非法测试用例”);
}
同时(测试-->0){
//System.out.println(“输入患者dna”);
字符串patient=in1.nextLine().toLowerCase();
//System.out.println(“输入病毒dna”);
字符串virus=in1.nextLine().toLowerCase();
int l=virus.length();
int i=0;
整数计数=0;
如果(患者长度()>100000 | |病毒长度()>100000){
抛出新异常(“输入长度超出范围”);
}
对于(i=0;i
将抛出NoTouchElementException,因为您正试图从数据到达末尾的输入(扫描仪)读取数据。因此,您必须通过检查hasNext()是否为真来读取输入(扫描仪)
希望这对你有帮助
Scanner in = new Scanner(System.in);
使用之后
while (in.hasNext())
{
/// do the operation
}
发布整个错误。为什么要重新创建扫描仪?@BitNinja此错误出现在第15行,即::String patient=in1.nextLine().toLowerCase()@AndrewLogvinov,因为第一个扫描程序正在接受整数输入,如果我不重新创建它,它在接受输入时会在运行时意外运行。我也不明白为什么会发生这样的事情,所以这是正确的。您应该添加一些代码,以显示其示例中的解决方案。