2

Ok I'm having some problems reading elements from a string, I'm given some user inputted file and I read every line into an arraylist. Now I need to access each line and read these integers from it and set them to int variables. There will be multiple integers per line though see sample below. Can someone help with this?

1 5
1 4
2 3
3 1
10 13
100 203
etc...

So for the first line I want to do something like:

first line:
int i = string.element1 // 1
int j = string.element2 // 5

...etc...

last line:
int i = string.element1 // 100
int j = string.element2 // 203

2 Answers 2

3

Try using the split() method to get Strings and then convert them to int via parseInt():

int i = 0, j = 0;
String string = "100 203";
String[] parts = string.split(" ");

i = Integer.parseInt(parts[0]);
j = Integer.parseInt(parts[1]);
Sign up to request clarification or add additional context in comments.

Comments

3
ArrayList<String> yourArray...; //this is your array list containing all lines from your file
for(String data : yourArray){
    String[] nums = data.split(" ");
    Integer num1 = Integer.parseInt(nums[0]);
    Integer num2 = Integer.parseInt(nums[1]);
}

Something like that?

Comments

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.