我正在尝试制作一个计算器来帮助我完成物理作业。为此,我试图将它分成两个部分,因此键入"波长18"将它分成波长"和" 18"作为数值。
我理解能得到第一个可以使用的词
String variable = input.next();
但有没有办法阅读太空后的内容?
感谢。
答案 0 :(得分:1)
String[] parts = variable.split(" ");
string first = parts[0];
string second = parts[1];
答案 1 :(得分:0)
String entireLine = input.nextLine();
String [] splitEntireLine = entireLine.split(" ");
String secondString = splitEntireLine[1];
答案 2 :(得分:0)
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
}