2015-05-04 93 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); 
    } 
}