2014-10-31 37 views
1

大家好,所以情況就是這樣。我的樂透應用程序有效,但我只需要最後一件事情來實現,我有一個huuuuge問題。所以我有6個數字保存在「lotto.dat」文件中。 1,2,3,4,5,6。如果我不選擇獲取新數字,應用程序會生成6個新的隨機數並進行比較。這工作。如何比較文件中的數字與隨機數字?

但是,如果我不想要6個新的數字,將它們保存在一個ArrayList中,並將它們打印到「lotto.dat」中,那麼該文件現在包含6個數字,並帶有數組listList事物的括號cus。我有一種感覺,這可能是這個問題,因爲當新號碼被保存時,它說甚至沒有匹配。

這是我的號碼的方法:

Scanner scann = new Scanner(System.in); 

    File f = new File("lotto.dat"); 

    PrintStream output = new PrintStream(f); 

    output.print(num1 + " " + num2 + " " + num3 + " " + num4 + " " + num5 + " " + num6); 

    System.out.println("Your lotto numbers: " + num1 + " " + num2 + " " + num3 + " " + num4 + " " + num5 + " " + num6); 

    System.out.println("Would you like to keep these numbers? y/n"); 

    String yn = scann.nextLine(); 

    if(!yn.equals("y")){ 

    newNumbers(); 

    }//While yn !y 

在我newNumbers方法我填與被寫在控制檯中的6個newNumbs一個ArrayList。然後,我將ArrayList的StreamStream打印到「lotto.dat」文件中,該文件被覆蓋。

現在,這是我的代碼,我比較隨機數(從ArrayList的號碼):

for(int n : numbers) {  // go through all the numbers in the list 

    String match = doCompare(n); // doCompare metode 

    if(match.equals("true")){ 

     List<Integer> numbersMatch = new ArrayList<>(); 

      numbersMatch.add(n); 

     Thread.sleep(1000); 
     System.out.println(); 
     System.out.println("Match on the number: " + n); 

     count++; 
    } 
    } 

這裏是我的doCompare方法:

Scanner sc = new Scanner(new File("lotto.dat")); 

    List<Integer> mn = new ArrayList<>(); 

    while(sc.hasNextInt()){ 
    mn.add(sc.nextInt());  
    } 

    if(mn.contains(n)){ 

    String tf = "true"; 
    return tf; 

    } 
    else{ 

    String tf = "false"; 
    return tf; 

    } 

我已經花了很多字面上幾個小時試圖解決問題,但我不能。爲什麼它沒有比較數字?唯一真正改變的是,保存在lotto.dat中的新號碼在外部文件中有「[]」。

+1

對不起,我的咖啡不能正常工作,所以我需要一點澄清。你確切的問題是:「如果數字是新生成的,比較來自文件的數字不起作用」_我是對嗎? – Keale 2014-10-31 03:31:00

+0

你的'doCompare()'方法應該返回一個'boolean',而不是'String',它必須與'true'或'false'進行比較。你的問題仍然模糊。 – EJP 2014-10-31 05:03:11

回答

0

你說

但如果我wan't 6個新的號碼,將它們保存在一個ArrayList和他們的PrintStream成「lotto.dat」,該文件現在包含6個號碼與支架CUS該ArrayList事情。

考慮您的發言上面,你必須與你的代碼有問題,因爲以下掃描儀時看到支架while循環將立即退出,不會有任何INT數組中

while(sc.hasNextInt()){ 
mn.add(sc.nextInt());} 

現在你的問題已經清楚了,你可以嘗試在文件上寫一個for循環,以防止這些括號被包含在你的文件中,或者你可以在讀取之前使用正則表達式去除文件中不是int的那些字符。