2015-05-04 59 views
-1

我试图拆分通过扫描器获得的输入,并将方括号内的整数拆分,并将其全部放入单独的树集合中,并根据行中的运算符执行操作。我在尝试解析输入并将其添加到不同的树集中时遇到问题,即使在将其转换为整数后,我仍然会收到InputMismatchException。想知道我出错的地方。将输入拆分为整数

import java.util.*; 

class Main { 
    public static void main(String[] args) { 
     Scanner in = new Scanner(System.in); 
     int times = in.nextInt(); 
     //iterate through number of times 
     for (int i = 0; i < times; i++) { 
      int num = in.nextInt(); 
      System.out.println(num) 
     } 
    } 
} 

我采取所述的输入是

6 
[1,2,3] + [1,4,5] 
[5,4,7,11] - [5,7] 
[1,2,3] * [1,4,5] 
[5,17,51,2,51] + [1,3,12,5,44,66,82] 
[7,13,23,11,10] - [11,13,14,7,8,9,10] 
[7,13,23,11,10] * [11,13,14,7,8,9,10] 

Where my question is from

+3

是'我<= times'应该是'I'倍'因为你从0开始编制索引。在循环中,你可能应该读完整行,然后尝试解析它。 – Pshemo

+3

我不明白你想要什么。 –

+0

我无法将注意到操作员的输入分为整数,因为我需要根据操作员执行一些操作。但我只是难以理解我将如何分解我输入整数的输入。 –

回答

0

nextInt不能正确地解析字符,如[],或,+(如果它是从数等+ 4分离代替的+4,其将简单地表示4)。

这就是为什么当你试图解析字符串像[1,2,3] + [3,4]nextInt你得到InputMismatchException,因为[

大概的分析文件最简单的方法是在像

int times = in.nextInt(); 
in.nextLine();//nextInt will not consume line separator, we need to do it explicitly 
for (int i = 0; i < times; i++) { 
    String line = in.nextLine(); 
    parse(line); 
} 

的方式,其中parse方法可以从

private static final Pattern p = Pattern 
     .compile("\\[(?<set1>\\d+(?:,\\d+)*)\\]" // match first [1,2,3] and place it in group named set1 
       + "\\s(?<operator>[-+*])\\s"  // match operator, one of - + or * 
       + "\\[(?<set2>\\d+(?:,\\d+)*)\\]"); // match second [2,3,4] and place in group named set2 

private static void parse(String text) { 
    Matcher m = p.matcher(text); 
    if (m.matches()) { 

     String[] set1 = m.group("set1").split(","); 
     String[] set2 = m.group("set2").split(","); 
     String operator = m.group("operator"); 

     if (operator.equals("+")){ 
      //handle sum of sets 
     } 
     //handle rest of operators 
     else if (operator.equals("-")){ 
      //... 
     } 
     //... 

    } else { 
     System.out.println("wrong text format:"); 
     System.out.println(text); 
    } 
}