2013-03-01 26 views
3

我无法弄清楚如何阅读输入行的其余部分。我需要令牌的第一个字,然后可能创建输入行的剩余部分作为一个整体令牌Java阅读方法如何阅读第一个单词然后输入其余部分

public Command getCommand() 
{ 
    String inputLine; // will hold the full input line 
    String word1 = null; 
    String word2 = null; 

    System.out.print("> ");  // print prompt 

    inputLine = reader.nextLine(); 

    // Find up to two words on the line. 
    Scanner tokenizer = new Scanner(inputLine); 
    if(tokenizer.hasNext()) { 
     word1 = tokenizer.next();  // get first word 
     if(tokenizer.hasNext()) { 
      word2 = tokenizer.next();  // get second word 
      // note: just ignores the rest of the input line. 
     } 
    } 

    // Now check whether this word is known. If so, create a command 
    // with it. If not, create a "null" command (for unknown command). 
    if(commands.isCommand(word1)) { 
     return new Command(word1, word2); 
    } 
    else { 
     return new Command(null, word2); 
    } 
} 

输入:

take spinning wheel 

输出:

spinning 

所需的输出:

spinning wheel 

回答

3

使用split()
String[] line = scan.nextLine().split(" ");
String firstWord = line[0];
String secondWord = line[1];

这意味着你需要拆分空间的行,并将其转换为数组。现在,使用YHE指数,你可以得到任何字你想

0

OR -

String inputLine =//Your Read line 
String desiredOutput=inputLine.substring(inputLine.indexOf(" ")+1) 
1

你可以尝试这样也...

String s = "This is Testing Result"; 
System.out.println(s.split(" ")[0]); 
System.out.println(s.substring(s.split(" ")[0].length()+1, s.length()-1));