Reputation: 43
I'm trying to make a calculator to help me with physics homework. For this, I'm trying to make it separate input into two parts, so typing "wavelength 18" would split it into "wavelength" and "18" as a numeric value.
I understand to get the first word that I can use
String variable = input.next();
But is there a way to read what comes after the space?
Thanks.
Upvotes: 1
Views: 597
Reputation: 412
Assuming that you also might have three words or just one, it is better not to rely on arrays. So, I suggest to use List here:
final String inputData = input.next();
//Allows to split input by white space regardless whether you have
//"first second" or "first second"
final Pattern whiteSpacePattern = Pattern.compile("\\s+");
final List<String> currentLine = whiteSpacePattern.splitAsStream(inputData)
.collect(Collectors.toList());
Then you can do a variety of checks to ensure you have correct number of values in the list and get your data:
//for example, only two args
if(currentLine.size() > 1){
//do get(index) on your currentLine list
}
Upvotes: 0
Reputation: 1101
String[] parts = variable.split(" ");
string first = parts[0];
string second = parts[1];
Upvotes: 1
Reputation: 373
String entireLine = input.nextLine();
String [] splitEntireLine = entireLine.split(" ");
String secondString = splitEntireLine[1];
Upvotes: 0