-5

i built this function that takes a line of code and puts it into an arraylist and returns that list. problem is when I try to input the string into the list when I debugged the code it showed me that what was being inserted was- [[Ljava.lang.String;@1786f9d5] -how can I fix this? my code is:

    public static List<String[]> GetAll(String st){
        String[] list = st.split("bags contain | contain |bags, | bag, | bags\\.| bag\\.");//ways to split it-shouldn't be changed
            List<String[]> newlist = new ArrayList<>();
            for (int i = 1; i < list.length; ++i) {
                if (!list[i].equals("no other")) {
                    int n = Integer.parseInt(list[i].split(" | \\s")[0]);
                    for (int j = 0; j < n; ++j) {
                        newlist.add(list[i].split(" \\s[0-9],\\s "));//here is the problem I think when I try to remove the number from the string
                }
        }
        }
        if(newlist.size()>1) {
            return newlist;
        }
        return new ArrayList<>();
    }

    public static void main(String[] args) {
        HashMap<String,List<String[]>> hm = new HashMap<>();// can kinda ignore the hashmap
        String input=reader.nextLine();
        while(!input.equals("-1")){
             hm.put(GetName(input),GetAll(input));
            input=reader.nextLine();
        }
}
    public static String GetName(String st){
        return st.split("bags")[0].stripTrailing();

    }
    static boolean isInArr(String[] arr,String looking){
        for (String s:arr){
            if(s.strip().equals(looking.strip())){
                return true;
            }
        }
        return false;
    }

some examples, each line in a new string, the first few words should be ignored as well:

sidenote. here "shade/name color"(at the beginning of the string before "contain") is not relevant so the function overall should skip over it- meaning in the arraylist which is returned "shade/name color" will not appear

here "dull indigo" is not relevant so the function overall should skip over it st= "dull indigo bags contain 2 faded black bags, 2 faded red bags, 4 dim bronze bags."

--> function should return [faded black, faded black, faded red, faded red, dim bronze, dim bronze, dim bronze, dim bronze]

here "pale blue" is not relevant so the function overall should skip over it st= "pale blue bags contain 2 pale fuchsia bags, 5 mirrored bronze bags, 2 faded fuchsia bags."

-- function should return [pale fuchsia, pale fuchsia, mirrored bronze, mirrored bronze, mirrored bronze, mirrored bronze, mirrored bronze, faded fuchsia, faded fuchsia]

here "light lime" is not relevant so the function overall should skip over it st= "light lime bags contain 4 pale lime bags, 5 plaid green bags, 3 clear turquoise bags, 3 plaid yellow bags."

--> function should return [pale lime, pale lime, pale lime, pale lime, plaid green, plaid green, plaid green, plaid green, plaid green, clear turquoise, clear turquoise, clear turquoise, plaid yellow, plaid yellow, plaid yellow]

here "faded turquoise" is not relevant so the function overall should skip over it- meaning in the arraylist which is returned "faded turquoise" will not appear st= "faded turquoise bags contain 3 mirrored silver bags."

--> function should return
[mirrored silver bags, mirrored silver bags, mirrored silver bags]

here "drab magenta" is not relevant so the function overall should skip over st= "drab magenta bags contain 2 clear tomato bags. "

--> function should return
[clear tomato, clear tomato]

and so on when I try to put tostring()- newlist.add(list[i].split(" \s[0-9],\s ").toString()); --then the .add() is an error. how can I fix this when the listarray is string type array and get the "name color" it gives me the string and not the weird array hex string

help would be appreciated, help in improving the question or the clarity of my explanation is also welcome. thanks

Rocky cohn
  • 71
  • 1
  • 13
  • 2
    [What's the simplest way to print a Java array?](https://stackoverflow.com/q/409784), [How do I print my Java object without getting “SomeType@2f92e0f4”?](https://stackoverflow.com/q/29140402) – Pshemo Dec 07 '20 at 21:24

4 Answers4

3

String#split returns a String[]. If you try to print it directly, you will get a similar output. You can print an array using Arrays.toString(array) or some other ways. Given below is an example:

import java.util.Arrays;

public class Main {

    public static void main(String[] args) {
        String[] arr = { "Hello", "World" };
        System.out.println(arr);
        System.out.println(Arrays.toString(arr));

        // Another way
        System.out.println(String.join(",", arr));
    }
}

Output:

[Ljava.lang.String;@3b22cdd0
[Hello, World]
Hello,World

In your code, you can put this print statements as follows:

for (int j = 0; j < n; ++j) {
    // ...
    String [] arr = list[i].split(" \\s[0-9],\\s ");
    System.out.println(Arrays.toString(arr));
    newlist.add(arr);
    // ...
}

However, your debugger should be able to show the elements as shown below:

enter image description here

Update:

This update is based on another requirement posted by the OP in the following comment:

in one example it returns- [2 dark blue] --i dont want the number 2 and the space, I want it to be [dark blue, dark blue]

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Main {

    public static void main(String[] args) {
        List<String[]> list = GetAll("light red bags contain 1 bright white bag, 2 muted yellow bags.");
        list.stream().forEach(e -> System.out.println(Arrays.toString(e)));
    }

    public static List<String[]> GetAll(String st) {
        String[] list = st.split("bags contain | contain |bags, | bag, | bags\\.| bag\\.");
        List<String[]> newlist = new ArrayList<>();
        for (int i = 1; i < list.length; ++i) {
            if (!list[i].equals("no other")) {
                int n = Integer.parseInt(list[i].split(" | \\s")[0]);
                for (int j = 0; j < n; ++j) {
                    int index = list[i].indexOf(' ');
                    if (index != -1) {
                        newlist.add(new String[] { list[i].substring(index).trim() });
                    }
                }
            }
        }
        if (newlist.size() > 1) {
            return newlist;
        }
        return new ArrayList<>();
    }
}

Output:

[bright white]
[muted yellow]
[muted yellow]
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
3

For your desired output you should try to match instead of split:

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

....

public static List<String> GetAll(String st){
    Pattern p = Pattern.compile("\\d+\\s\\w+\\s\\w+");
    Matcher m = p.matcher(st);
    List<String> list = new ArrayList<>();
    while(m.find()){
        String found = m.group();
        //get the number by removing everything which is not a digit
        int i = Integer.parseInt(found.replaceAll("[^\\d]+", ""));
        //add n copies of the matched string after removing the digit
        list.addAll(Collections.nCopies(i, found.replaceAll("\\d+", "").trim()));
    }
    System.out.println(list);
    return list;
}

Same question but different approach from someone else, might be worth a look

Eritrean
  • 15,851
  • 3
  • 22
  • 28
2

When you try to turn something into a String and get something like [Ljava.lang.String;@1786f9d5] with an @ and then a bunch of hex digits, it means you tried to convert an object into a String and the object doesn't have a toString() method/function. Make sure what you are putting in is a String, or can be turned to one with a toString() method/function.

Yhrrs
  • 51
  • 8
0

I will not give you the whole implementation, nevertheless i don't have it on that machine :) All I want to point out is that you are on the right track. Unfortunately you are complicating your solution too much! Instead of returning an array that contains the same string several times, you should return a Map<String, Integer>. Here is something similar to the code that I used earlier today.

public static void main(String... args) {

    Map<String,Map<String,Integer>> inputMap = parseInputString(input);

    System.out.println(inputMap);
}

private static Map<String,Map<String,Integer>> parseInputString(String input) {

    String keyDelimiter = " bags contain ";
    String valuesDelimiter = " (bag|bags)(\\.|,\\s)";
    String noValuesEnding = "no other bags.";

    return Arrays.stream(input.split("\n"))
                 .filter(line -> !line.endsWith(noValuesEnding))
                 .map(line -> line.split(keyDelimiter))
                 .collect(Collectors.toMap(
                     line -> line[0],
                     line -> Arrays.stream(line[1].split(valuesDelimiter))
                                   .collect(Collectors.toMap(
                                       value -> value.substring(value.indexOf(" ") + 1),
                                       value -> Integer.parseInt(value.substring(0, value.indexOf(" ")))))));
}
dbl
  • 1,109
  • 9
  • 17