我正在尝试通过扫描程序获取用户输入,并在HackerRank上提交此代码并获得上述异常。我尝试在我的机器上运行相同的测试用例,并且没有捕获Exception,代码工作正常。我不是在Java中了解流,帮我找出错误。
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();
}
}
}
答案 0 :(得分:2)
NoSuchElementException将被抛出,因为您要从输入(扫描程序)读取数据到达最终的数据。因此,您必须通过检查hasNext()是true还是false来读取输入(Scanner)。
希望这会对你有所帮助。
答案 1 :(得分:0)
Scanner in = new Scanner(System.in);
之后使用
while (in.hasNext())
{
/// do the operation
}