【问题标题】:2d arraylist NoSuchElementException二维数组列表 NoSuchElementException
【发布时间】:2016-06-15 18:20:07
【问题描述】:

我正在尝试创建一个 2D ArrayList 并向其添加值。出于某种原因,我不断收到NoSuchElementException

这是我要解决的问题: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");

    }
}

【问题讨论】:

    标签: java exception arraylist runtime-error runtimeexception


    【解决方案1】:

    当您尝试从输入读取但没有可用输入时会发生该异常。一种解决方法是使用 hasNextInt() 方法来确保有可用的可读输入。 例如)

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

    这可能是输入说当前行有三个数字的结果,而实际上只有两个。

    1
    3 1 4 <= would cause exception. 
    

    【讨论】:

    • 但同时在逻辑上没有意义,因为我的 2 循环应该只根据每行的第一个数字循环。
    • 所以我应该从当前空间中读取 int。例如,如果我的行有 3 6 5 2 循环应该可以正常工作
    • 我也遇到了超时错误。我不知道为什么会这样
    猜你喜欢
    • 1970-01-01
    • 2015-11-29
    • 1970-01-01
    • 1970-01-01
    • 2013-08-27
    • 1970-01-01
    • 2020-06-11
    • 2012-12-13
    • 1970-01-01
    相关资源
    最近更新 更多