Different lists of data will be entered on command line.
"J,A,V,A"
"4,H,11,V,3,H"
I need to store the first list in a char array. I also want to have the next line in a char array of "H,V,H" and an int array of "4,11,3". What is the best way to go about doing this? I'm hesitant to split on the comma because I don't know if the input is going to be separated by just a comma or a comma and a space. I'm having difficulty since when I use a scanner everything stays in a string, and when I try to split it the string becomes a string array.
I'm having difficulty since when I use a scanner everything stays in a string, and when I try to split it the string becomes a string array.
The following seems to work for me.. Only ran it in the debugger, but it workd on the two lines of input you provided.
import java.lang.System;
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
ArrayList<Integer> ints = new ArrayList<Integer>();
ArrayList<Character> chars = new ArrayList<Character>();
Scanner console = new Scanner(System.in);
while (console.hasNext()) {
String line = console.next();
String[] tokens = line.split("\\s*,\\s*");
for (int i = 0; i < tokens.length; i++) {
if (isInteger(tokens[i])) {
ints.add(Integer.parseInt(tokens[i]));
} else if (isChar(tokens[i])) {
chars.add((char) tokens[i].indexOf(0));
}
}
}
console.close();
}
private static boolean isInteger(String s) {
try {
Integer.parseInt(s);
} catch (NumberFormatException e) {
return false;
}
// only got here if we didn't return false
return true;
}
private static boolean isChar(String s) {
if (s.length() != 1) {
return false;
}
return true;
}
}
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.