I’m not really sure how to word this, but basically I want to read in an rgb color in xxx, xxx, xxx format and store each xxx in an array. I am making a program to convert rgb into hexadecimal. Until I get my gui created (which may take me some time) I am executing and inputting in the terminal.
Currently this is what I am doing:
System.out.println("Enter the first set:");
rgb[0] = new Scanner(System.in).nextInt();`
System.out.println("Enter the second set:");
rgb[1] = new Scanner(System.in).nextInt();
System.out.println("Enter the third set:");
rgb[2] = new Scanner(System.in).nextInt();
- I have seen people use
.split(","), is this the best way to do what I want? - Would a regular expression work better?
- Anyone know any tutorials that I could use? Most of the ones I have found have just left me more confused than I already was.
Just so you know I am not doing this for a project (before anyone accuses me). I already have the algorithm and everything else works except for this.
Here are my suggestions:
Don’t create a new
Scannerinstance each time you want to read input. Just create one at the beginning of the program and reuse it throughout.The
splitmethod takes a regular expression as its argument, and returns aString[](splitting the string on each match of its argument). So if you’re planning on parsing a string of the form"xxx, xxx, xxx"then.split(",\\s*")is probably your best bet.\smatches any whitespace character and\s*matches\szero or more times.I’m assuming
rgbis anint[], so you could loop through yourString[]that was obtained fromsplit(as described above), callInteger.parseInton each element, and add the parsed int torgb.Relevant documentation
String#splitInteger#parseInt