简体   繁体   English

2D arraylist NoSuchElementException

[英]2d arraylist NoSuchElementException

I am trying to create a 2D ArrayList and add values to it. 我正在尝试创建一个2D ArrayList并为其添加值。 For some reason I keep getting a NoSuchElementException . 由于某些原因,我一直收到NoSuchElementException

Here is the problem I am trying to solve: https://www.hackerrank.com/challenges/java-arraylist 这是我要解决的问题: https : //www.hackerrank.com/challenges/java-arraylist

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    public static void main(String[] args) {
        /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
               Scanner input = new Scanner(System.in);
               int TestCases = input.nextInt();
               ArrayList<ArrayList<Integer>> listOfLists = new ArrayList<ArrayList<Integer>>();

               List<ArrayList<Integer>> Sdarraylist = new ArrayList<ArrayList<Integer>>();

                //ArrayList<ArrayList<String>> 2darraylist = new ArrayList<>();
                //ArrayList<String> 1darraylist=new ArrayList<>();

               for(int i=0;i<TestCases;i++){

                   ArrayList<Integer> Fdarraylist=new ArrayList<Integer>();
                   //size of Arraylist
                   int NumbersOnCurrentLine = input.nextInt();
                   for(int j=0;i<NumbersOnCurrentLine;j++){
                     //add numbers on the current line to the list
                     Fdarraylist.add(input.nextInt());
                   }
                 Sdarraylist.add(Fdarraylist);
               }                
// data.add(new ArrayList<String>());
 //data.get(0).add("String");

    }
}

That exception occurs when you try to read from an input, but no input is available. 当您尝试从输入中读取但没有输入可用时,将发生该异常。 One workaround would be to use use the hasNextInt() method to make sure there is readable input available. 一种解决方法是使用hasNextInt()方法来确保有可读的输入。 ex) 例如)

if (input.hasNextInt()) {
    Fdarraylist.add(input.nextInt());
}

This could be the result of the input saying there are three numbers on the current line, when in reality there are only two. 这可能是输入的结果,即当前行上有三个数字,而实际上只有两个。

1
3 1 4 <= would cause exception. 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM