2013-01-23 164 views
1

我正在做一些使用Java的任务,这是我应该做的。 给定一个整数X,您应该读取X行,每行包含一个字符串和2个整数值xy存储结果

**Input** 
2 <-- Read 2 lines 
PLUS 10 30 <-- PLUS refers to adding 30 to 10 
MINUS -6 20 <-- MINUS refers to minus 20 from -6 
**Output** 
40 
-26 

如何存储值40和-26? 我目前正在使用一个数组。下面的代码。

for(int i = 0; i < limit; i++) 
{ 
    String limitInput = sc.next(); 
    x = sc.nextInt(); 
    y = sc.nextInt(); 
    if(limitInput.equals("PLUS")) 
    { 
     System.out.println(x+y); 
     limitArray[i] = x + y; 
    } 
    else if(limitInput.equals("MINUS")) 
    { 
     limitArray[i] = x - y; 
    } 
    else 
    { 
     limitArray[i] = x * y; 
    } 
} 

有没有更简单的方法,像没有使用数组?

+2

你可以使用开关,但我会写最简单和最清晰的给你。你可以评论为什么只打印x + y,为什么默认运算符是乘法运算。 –

+1

请注意,在字符串上使用开关仅在'SE 7' – Maroun

+0

如何存储数据? 是否可以在不使用数组的情况下存储数据? 我正在考虑将数据存储到一个整数中,但该整数值将在循环中被覆盖。 =/ –

回答

1

不要认为你的情况下数据结构比数组简单。如果要将结果与操作/行号一起存储;会建议你使用HashMap。 但是,地图绝对不比数组简单。

Map<Integer,Integer> map = new HashMap<Integer,Integer>(); 
int line = 1; //read line number 
int result= 40; //read final result 
map.put(line, result); 

这样你就可以通过迭代map得到每一行的结果。

但是,如果您还想存储您执行的操作;那么会建议使用这样的multimap

Map<Integer, ArrayList<String>> map = new HashMap<Integer, ArrayList<String>>(); 
ArrayList<String> a = new ArrayList<String>(); 
a.add("PLUS"); //add operation 
a.add(result); //add result 

map.put(line, a); 

当从列表中读取值;只需确保将值(位置1)解析为int,并将其存储为String。