0

Am trying to create an array which holds the String arrays created from a utilising the String.split() method on a string which is input through a loop.

int N = in.nextInt();
String [][] defibDetails = new String[N][];
in.nextLine();
for (int i = 0; i < N; i++) {
    String DEFIB = in.nextLine();
    String [] details = DEFIB.split(";");
    defibDetails[i][]=details;
}
System.out.println(defibDetails[0][0]);

I would like the System.out to be the substring of DEFIB before the first ; where loop counter i = 0. Thanks for any thoughts.

7
  • Do you know the size of your total input? String arrays need to be given a predetermined size. Have you thought of using lists. List<List<String>> details = new ArrayList<>(); Is the 'in' object in your code the Scanner class? Commented Jul 20, 2016 at 16:05
  • Read the error message you get from the compiler, fix the error (it should be defibDetails[i] = details;, and you will have the expected behavior. You can't expect a program to do something if it doesn't even compile. Commented Jul 20, 2016 at 16:13
  • Unfortunately the length varies. Am open to using any form of collection but quite new to Java and don't know the best for a given application. Looked at lists but couldn't work out the 2d syntax for getting the value back. Would it be list.get(0).list.get(0) ? Commented Jul 20, 2016 at 16:23
  • nizet the code is actually for a 2d array so I don't think I want to do that unless you can expand on why? Commented Jul 20, 2016 at 16:25
  • No. list.get(0) returns a List<String>. Sna dyou can call get(0) on a List<String> to get its first element. So it's list.get(0).get(0). But you can use two instructions to make it clearer: List<String> firstList = list.get(0); String firstString = firstList.get(0); Commented Jul 20, 2016 at 16:27

1 Answer 1

1

The error is here: defibDetails[i][] ; it should be like this: defibDetails[i] You've got a two dimensional array, so fist dimension is particular array of "array of arrays". Second is particular element of this array. So defibDetails[i] means array #i, defibDetails[i][j] means element j in array i.

int N = in.nextInt();
String [][] defibDetails = new String[N][];
in.nextLine();
for (int i = 0; i < N; i++) {
    String DEFIB = in.nextLine();
    String [] details = DEFIB.split(";");
    defibDetails[i]=details; // <<<<<<<<
}
System.out.println(defibDetails[0][0]);

http://ideone.com/Dr9Aci

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. Thought since it was 2d needed to use constant 2d notation. Has fixed the issue.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.