2014-02-25 92 views
0

我有下面的代碼。當從文本文件中輸入時,不會比較大小

import java.io.File; 
import java.math.BigInteger; 
import java.util.ArrayList; 
import java.util.Arrays; 
import java.util.Collection; 
import java.util.Collections; 
import java.util.Scanner; 

public class Scalar { 
    public static void main(String args[]) throws Exception { 

     Scanner sc=new Scanner(new File("D:/GC/Scalar/A-small.in")); 
     int testcases=Integer.parseInt(sc.next()); 
     System.out.println(testcases); 
     ArrayList<BigInteger> a=new ArrayList<BigInteger>(); 
     ArrayList<BigInteger> b=new ArrayList<BigInteger>(); 

     for(int j=0;j<2;j++){ 

     int size=Integer.parseInt(sc.next()); 
     System.out.println(size); 

     for(int i=0;i<size;i++) 
     { 
      a.add(sc.nextBigInteger()); 

     } 


     for(int i=0;i<size;i++) 
     { 
      b.add(sc.nextBigInteger()); 

     } 
     Collections.sort(a);   
     System.out.println(a.size()); 
     System.out.println(a); 
     Collections.sort(b,Collections.reverseOrder()); 
     System.out.println(b); 
     BigInteger sum; 
     for(int i=0;i<a.size();i++){ 
      sum=a.get(i).multiply(b.get(i)); 
      sum=sum.add(sum); 

     } 

    } 

    } 


} 

和下面的內容在一個文本文件中。

1000 
3 
1 -5 3 
-2 1 4 
5 
5 4 3 1 2 
1 1 0 1 0 
7 
677 463 -569 516 401 -998 882 
890 588 959 909 948 -617 -655 
8 
-912 937 167 366 -222 -397 190 -216 
354 

這裏我試圖所述第一陣列和以相反的順序在第二排序,然後做和與積,在這裏,我只用了2例,在1000中輸入以上是測試用例總數,和單個數字行表示數組的大小,並且在我的程序中要確保數組的大小與給定的大小相匹配,我打印大小,在第一種情況下,輸入大小爲3,我得到它正確,但在第二種情況下,輸入的大小是5,但是我將它作爲數組的大小,下面是我得到的輸出。

1000 
3 
3 
[-5, 1, 3] 
[4, 1, -2] 
5 
8 
[-5, 1, 1, 2, 3, 3, 4, 5] 
[4, 1, 1, 1, 1, 0, 0, -2] 

請讓我知道我在哪裏錯了。

感謝

回答

3

這就是問題所在:

ArrayList<BigInteger> a=new ArrayList<BigInteger>(); 
ArrayList<BigInteger> b=new ArrayList<BigInteger>(); 

for(int j=0;j<2;j++){ 
    // Stuff 
} 

你重複使用相同列出了每個測試 - 所以你從第二次測試增加值到已包含列表第一次測試的數據。

選項:

  • (首選),爲每個測試
  • 清除出在每個測試

開始列表創建新列表既然你不邏輯想爲了保持列表從一個測試到另一個,我只是將代碼更改爲:

for(int j = 0; j < 2; j++){ 
    List<BigInteger> a = new ArrayList<BigInteger>(); 
    List<BigInteger> b = new ArrayList<BigInteger>(); 
    // Populate the lists, etc. 
} 

請注意,這個可以更容易地提取「讀取大小,讀取數據,整理」整個操作到一個單獨的方法。

另外,我嫌疑你想你的循環更改爲:

for(int j = 0; j < testcases; j++) { 

......否則你會經過兩次測試停止。

如果您使用的是Java 7,您可以使用類型推斷,使ArrayList創造更簡單,太:

List<BigInteger> a = new ArrayList<>(); 

...你甚至可以考慮提取「讀n號碼到一個列表「到一個單獨的方法,讓你的代碼看起來是這樣的:

int size = Integer.parseInt(sc.next()); 
System.out.println(size); 
List<BigInteger> a = readBigIntegers(sc, size); 
List<BigInteger> b = readBigIntegers(sc, size); 
// Now sort etc. 

還要考慮使用Scanner.nextInt(),而不是您的明確Integer.parseInt電話。