英文:
Assigning Matrix Values using For Statement - Java
问题
public class Solution {
public static void main(String[] args) {
Scanner prompt = new Scanner(System.in);
int[][] array = new int [prompt.nextInt()+1][prompt.nextInt()];
// Create matrix
for (int a = 0; a < array.length; a++){
for (int b = 0; b < array[a].length; b++){
array[a][b] = prompt.nextInt(); /*This is the line 14*/
}
}
for (int h=0; h < array.length; h++){
for(int c=0; c < array[h].length; c++){
System.out.printf("%5d",array[h][c]);
}
System.out.println("");
} } }
英文:
I am working on HackerRank that is a platform that allows students to upload their Homeworks code, then the platform runs some random tests on our code. On this opportunity, my teacher has asked me to create a matrix on base from the input from HackerRank and then fill it also with more inputs from this platform.
I have created this code to create a matrix with the dimensions on which HackerRank wants and also refill it with the values generated of the platform but seems to have an error on my code and I don't see it.
It gives me this error:
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:14)
My code:
public class Solution {
public static void main(String[] args) {
Scanner prompt = new Scanner(System.in);
int[][] array = new int [prompt.nextInt()+1][prompt.nextInt()];
// Create matrix
for (int a = 0; a < array.length; a++){
for (int b = 0; b < array[a].length; b++){
array[a][b] = prompt.nextInt(); /*This is the line 14*/
}
}
for (int h=0; h < array.length; h++){
for(int c=0; c < array[h].length; c++){
System.out.printf("%5d",array[h][c]);
}
System.out.println("");
} } }
答案1
得分: 1
当Scanner抛出NoSuchElementException时,这意味着你正试图从扫描器中读取内容,而此时已经到达输入的末尾。
在for循环中的nextInt之前尝试使用hasNextInt。
英文:
When a Scanner Throws a NoSuchElementException it means that you're trying to read from the scanner when you've already reached the end of the input.
Try using hasNextInt just before the nextInt in the for loop.
答案2
得分: 0
NoSuchElementException
在这种情况下表示没有更多的标记可供读取。您在输入上提供了足够的值吗?
参见:https://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html#nextInt--
英文:
NoSuchElementException
in this case indicates that there are no more tokens to be read. Did you provide enough values on the input?
See: https://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html#nextInt--
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论