Created
December 21, 2023 17:07
-
-
Save Archonic944/4e8ef2e97943fb4d96cebcf52ad876c2 to your computer and use it in GitHub Desktop.
A utility that allows you to parse space-separated, multi-line values from a Scanner as a table.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Arrays; | |
import java.util.Scanner; | |
public class ParseUtility { | |
static String[] asArray(String line){ | |
return line.split(" "); | |
} | |
static int[] asIntArray(String line){ | |
return asIntArray(asArray(line)); | |
} | |
static int[] asIntArray(String[] line){ | |
return Arrays.stream(line).mapToInt(Integer::parseInt).toArray(); | |
} | |
Scanner scanner; | |
public String[][] table; | |
public ParseUtility(Scanner scanner){ | |
this.scanner = scanner; | |
} | |
/** | |
* Takes in new data of the specified length. Must be called before other operations; previous data will be replaced. | |
* @param length amount of rows to take from the scanner | |
*/ | |
public void readTable(int length){ | |
table = new String[length][]; | |
for(int i = 0; i<length; i++){ | |
table[i] = scanner.nextLine().split(" "); | |
} | |
} | |
public int integerAt(int row, int column){ | |
return Integer.parseInt(strAt(row, column)); | |
} | |
public int[] intArrayAt(int row){ | |
return asIntArray(table[row]); | |
} | |
public String strAt(int row, int column){ | |
return table[row][column]; | |
} | |
} |
Thanks, Archonic!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice one, Archonic!