2011-07-21 30 views
4

我试图创建一个计算器,需要一个字符串,可以在4种不同格式:如何解析这个输入?

input: add 1 2 13 5 together 
     => 1 + 2 + 13 + 5 = 21 
input: add 9 to 10 
     => 9 + 10 = 19 
input: subtract 5 from 13 
     => 13 - 5 = 8 
input: bye 
     => end program 

我已经设置了我这样的代码:

import java.util.*; 

    class Calculator { 
     public static void main(String[] args) { 
     System.out.println("yes>") 
     Scanner zip = new Scanner(System.in); 
     String input = zip.nextLine(); 

     if (input.equals("bye")) 
      System.exit(0); 
     else if (input.substring(0, 1) == "a") //assume first cmd is add 
      (integer.ParseInt(input.subtring(3, BLANK) //extract first number 

我的问题是,我不知道字符串中数字的索引。我想这样做:

if(input.substring(0,3)==“add”)=>下一个数字将是一个数字。解析integer.substring(3,BLANK)。 BLANK应该是空格字符的索引。那么这个数字需要放入一个变量中,程序需要检查所有其他整数。

我对如何解决这个问题有点困惑。如果有500个需要添加(或减去)的数字会怎样?有没有办法以递归方式做到这一点?这个程序应该使用我读过的正则表达式,但我不知道如何实现。

任何帮助将非常感激。在此先感谢

+1

我会使用正则表达式 - 您可以用非常确定的模式捕捉关键字和数字。我会写代码,但我不知道Java的方式.. –

+0

这就是我想弄清楚如何做。我的语法只是离开 – mdegges

回答

3

使用Scanner创建和使用以下方法:hasNextnext(读 “TO”, “减”,等等),hasNextIntnextInt(阅读NUM )。一旦给予扫描仪,input就不应该做任何事情。确保hasNext之前尝试hasNextInt,因为如果下一个单词相匹配的整数:)

这里有一些注意事项,以帮助建立解析器hasNext将返回true:

  1. “ADD” NUM1 NUMN +“一起”;如果第一个NUM1后面跟另一个NUMN那么这个格式。继续阅读NUMN直到没有更多 - 可以放入一个ArrayList供以后使用或计算并立即发出输出。那么最后应该有一个“TOGETHER”。

  2. “ADD”NUM1“TO”NUM2;只有当NUM1跟着“TO”时。

  3. “减” NUM1 “FROM” NUM2

  4. “再见”

可能开始是这样的:

String action = scanner.next(); 
if (action.equals("bye")) { 
    ... 
} else if (action.equals("add")) { 
    if (scanner.hasNextInt()) { 
    int num1 = scanner.nextInt(); 
    if (scanner.hasNextInt()) { 
     /* ADD NUM1 NUMN+ TOGETHER */ 
     int total = num1; 
     System.out.print("" + num1); 
     while (/* has more int */) { 
      int numN = /* read int */ 
      System.out.print(" + " + numN); 
      /* increase total */ 
     } 
     /* display results */ 
     /* now expecting "together" */ 
    } else { 
     /* ADD NUM TO NUM */ 
     if (!scanner.hasNext() 
      || !scanner.next().equals("to")) { 
     /* expecting "to" */ 
     } else { 
     /* get next number, add, show results */ 
     } 
    } 
    } else { 
     /* expecting NUM */ 
    } 
} else ... 

快乐在家办公。

1

您可以使用split()将行分割为单独的标记,然后检查第一个是否是一个命令,并验证其他是数字。

短的例子:

String[] tokens = input.split(" "); 
if (tokens.length > 0) { // there are tokens 
    if (tokens[0].equals("add")) { // valid command - add 
     // parse tokens and make sure they are numbers