Home > Blockchain >  How to solve Index 1 out of bounds for length 1
How to solve Index 1 out of bounds for length 1

Time:01-13

I have a method jsonProductItems() which return a map with String key and value.

public Map<String, String> jsonProductItems() throws IOException {
        List<String> products = new ArrayList<>();
        Map<String, String> productsAndIdentifier = new LinkedHashMap<>();
        for (Item item : example.getItems()) {
            products.add(item.getName());
        }
        for (int i = 0; i < products.size(); i  ) {
            productsAndIdentifier.put(indetifier.get(i), products.get(i));
        }
        System.out.println();
        
        return productsAndIdentifier;
    }

When in the same class in other method I want to do a matrix. When value from matrix is equal with a key from map returned by jsonProductItems() method, will print value of this key. But at line if(("" sumByRemainder.get(i) j).equals(entry.getKey())) have java.lang.IndexOutOfBoundsException: Index 1 out of bounds for length 1. How to solve this problem? And why in this case it appear?

for (int i = 0; i <= rows; i  ) {
            System.out.print(sumByRemainder.get(i)   " ");
            for (int j = 1; j <= columns; j  ) {

                if (i == 0) {
                    System.out.print(" "   j);
                    System.out.print(" ");
                } else {
                    indetifier.add(""   sumByRemainder.get(i)   j);
                    for (Map.Entry<String, String> entry : jsonProductItems().entrySet()) {
                        if((""   sumByRemainder.get(i)   j).equals(entry.getKey())){
                            System.out.println(jsonProductItems().get(entry.getKey()));
                        }else{
                            System.out.print(""   sumByRemainder.get(i)   j   " ");
                        }
                    }

CodePudding user response:

As some of the variables you have used seems unknown here for the other people like me, I think this code snippet is the culprit for your problem:

for (int i = 0; i <= rows; i  ) {
     System.out.print(sumByRemainder.get(i)   " ");
     for (int j = 1; j <= columns; j  ) {
      //... your code
    }
}

You can try the loops limit like this:

for (int i = 0; i < rows; i  ) {
            System.out.print(sumByRemainder.get(i)   " ");
            for (int j = 1; j < columns; j  ) {
            // you code here
      }
}

Just give a check in your looping limit for both of the loops.

CodePudding user response:

The wrong is at line indetifier.add("" sumByRemainder.get(i) j);. I use indetifer values, before put values in it....

CodePudding user response:

Length of 1 means there is only an element at index 0 - so you should do something like (i - 1)

  •  Tags:  
  • Related