Skip to content

Instantly share code, notes, and snippets.

@Archonic944
Created December 21, 2023 17:07
Show Gist options
  • Save Archonic944/4e8ef2e97943fb4d96cebcf52ad876c2 to your computer and use it in GitHub Desktop.
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.
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];
}
}
@Archonic944
Copy link
Author

Nice one, Archonic!

@Archonic944
Copy link
Author

Thanks, Archonic!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment