2016-02-12 97 views
1

我正在试着制作一个计算器来帮助我完成物理作业。为此,我试图将输入分成两部分,所以输入“波长18”将把它分成“波长”和“18”作为数字值。在输入中输入第二个字

我明白让我可以使用

String variable = input.next(); 

但是,有没有办法阅读空间后,随之而来的第一个字?

谢谢。

+0

您可以使用输入.nextLine()并使用空格作为分隔符来分割字符串 –

回答

0
String entireLine = input.nextLine(); 
String [] splitEntireLine = entireLine.split(" "); 
String secondString = splitEntireLine[1]; 
1
String[] parts = variable.split(" "); 
string first = parts[0]; 
string second = parts[1]; 
0

假设你可能也有三个词或只有一个,最好是不要依靠阵列。所以,我建议在这里使用List:

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()); 

然后你就可以做各种检查,以确保您在列表中值的正确数量,让您的数据:

//for example, only two args 
if(currentLine.size() > 1){ 
    //do get(index) on your currentLine list 
} 
相关问题