简体   繁体   中英

Two Dimensional Array Java TSP

I need to figure out how to get the following data into two ArrayLists or arrays...

THIS THAT OTHER

 1     2     3 
 4     5     6 
 7     8     9

I need the column titles to go into one array or ArrayList, and the integer values to go into a two dimensional array or ArrayList.

Here is my attempt at the Strings:

cities = new ArrayList<String>();
String newCities;
newCities = (inFile.nextLine());
String[] stringArray = newCities.split(" ");
for (int i = 0; i < stringArray.length; i++){
    cities.add(stringArray[i]);
}
System.out.println(cities);

I can't figure out how to do the integer values.

Finally, this is for the implementation of a Traveling Salesman Problem so if you can think of a better way to handle this data, let me know! Thanks for your time!

Use Scanner class instead, with its nextInt() method:

Scanner scanner = new Scanner(YOUR_STRING_WITH_INTS);
while (scanner.hasNext()) {
     yourInt = scanner.nextInt()
     yourArrayList.add(yourInt);
}

and remember to close the scanner afterwards

scanner.close();

If you want to add this to an array, scan every line, and use an index variable to count which line it is. You know that you have 3 integers in every line, so using your index, write to adequate "row" of the table.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM