编辑:我的问题是为什么当网站编译器给出错误时IntelliJ给出正确的答案。
我回答了其中一种编码练习,但是它不适用于网站编译器。同时它在我的IDE(IntelliJ)中运行。练习:
Input String:
5 //How many intigers to add to list
12 0 1 78 12 //Intigers to add
2 //How many commends to execute
Insert //Commend insert
5 23 //Add int 23 at index 5
Delete //Commend delete
0 //Which index to delete
Output String:
0 1 78 12 23 //Result String
我的答案:
int N = 0; //number of intigers
Scanner scanner = new Scanner(System.in);
N = scanner.nextInt();
List <Integer> L = new ArrayList<>();
for (int i = 0; i < N; i++) {
L.add(scanner.nextInt());
}
scanner.nextLine();
int Q = 0; //number of commends
Q = scanner.nextInt();
String str = "";
scanner.nextLine();
for (int i = 0; i < Q; i++) {
str = scanner.nextLine();
if(str.equals("Insert")){
Scanner scanIns = new Scanner(System.in);
int indexToInsert = scanIns.nextInt();
int numberToInsert = scanIns.nextInt();
L.add(indexToInsert,numberToInsert);
}else if (str.equals("Delete")){
Scanner scanDelete = new Scanner(System.in);
int numToDel = scanDelete.nextInt();
L.remove(numToDel);
}
}
String formattedString = L.toString()
.replace(",", "")
.replace("[", "")
.replace("]", "")
.trim();
System.out.println(formattedString);
我的回答是正确的(与问题示例相同),但仍然收到运行时错误:
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at Solution.main(Solution.java:25)
答案 0 :(得分:0)
我只是在自己的安装上运行了您的代码。有效。 I also just ran it on the TutorialsPoint Java IDE and it worked as well.
正确完成输入后,您的代码也可以在此处正常运行,但是输入中的丝毫错误都会导致java.util.NoSuchElementException
。
重新检查您的在线输入,以确保它们是正确的。我在插入后放置了一个空格,它会跳到最后而没有让我删除。不必是明显的输入错误。
要考虑的另一件事是,在线IDE可能会转义字符以防止恶意输入。这可能会导致输入问题。