2012-07-07 72 views
1
import java.io.File; 
import java.io.IOException; 
import java.util.ArrayList; 
import java.util.Scanner; 
import javax.swing.JOptionPane; 

public class Test { 
    private static ArrayList<Countries> arr = new ArrayList<Countries>(); 
    private static ArrayList<Countries> d = new ArrayList<Countries>(); 
    static String country; 
    static String capital; 
    static String cities; 
    static String cevap; 
    static int score =0; 


    public static void main(String args[]) throws IOException{ 
     Scanner keybord = new Scanner(System.in); 
     arr = new ArrayList<Countries>(); 
     d = read("data.txt"); 

     for(int i = 0; i < d.size(); i++){ 
      System.out.print(d.get(i).toString()); 
      cevap = keybord.nextLine(); 
      if(cevap.equalsIgnoreCase(d.get(i).getCapital())){ 
       System.out.println ("The answer is true!\nYou win 10 points"); 
      score += 10; 
      } 
      else{ 
       System.out.println("The answer is not true" + " The answer is " + d.get(i).getCapital() + "\nYou loose 10 points"); 
       score -= 10; 
      } 
      System.out.println("You're score is: " + score); 
      System.out.println(); 
     } 
    } 



    public static ArrayList<Countries> read(String filename) throws IOException{ 
     Scanner scan = new Scanner(new File(filename)); 
     while(scan.hasNext()){ 
      country = scan.nextLine(); //System.out.println(country); 
      String cities1 = scan.nextLine(); //System.out.println(cities1); 
      String cities2 = scan.nextLine(); //System.out.println(cities2); 
      String cities3 = scan.nextLine(); //System.out.println(cities3); 
      String cities4 = scan.nextLine(); //System.out.println(cities4); 
      String capital = scan.nextLine(); //System.out.println(capital); 
      Countries c = new Countries(country, cities1, cities2, cities3, cities4, capital); 
      arr.add(c); 
      scan.nextLine(); 
     } 
     return arr; 
    } 



} 

爲了使這個程序的桂,我應該改變主要部分,因爲它是下面。因爲我認爲從我閱讀的數據中讀取和初始化變量會更方便。或者我應該爲Gui創建另一個班級?我應該創建一個用於創建代碼的GUI的新類嗎?

public static void main(String args[]) throws IOException{ 
     Scanner keybord = new Scanner(System.in); 
     arr = new ArrayList<Countries>(); 
     d = read("data.txt"); 

     for(int i = 0; i < d.size(); i++){ 
      lcountry = new JLabel(d.get(i).getCity1()); 
      label1 = new JLabel(d.get(i).getCity1()); 
      label2 = new JLabel(d.get(i).getCity2()); 
      label3 = new JLabel(d.get(i).getCity3()); 
      label4 = new JLabel(d.get(i).getCity4()); 
+0

如果你想製作一個GUI,你將不得不拋棄該代碼並重新開始使用非靜態的OOP代碼。 – 2012-07-07 21:33:36

回答

3

不,我會建議封裝所有的UI東西在一個單獨的類。如果你把它放在主要方法中,它的可用性會差很多。

事實上,這適用於所有的課程。一個主要的方法應該非常小,並且只需創建實際工作的類的實例。如果主體很大,你做錯了。

無論您使用文本還是圖形用戶界面,您的問題都應該可用。你可以告訴你封裝好的東西,當你可以交換文本用戶界面的圖形和一切仍然有效。它被稱爲封裝和分層。如果你不能輕鬆地交換用戶界面,那麼你做錯了。

+0

好吧我會在另一個類的GUI部分,但我不明白的是,我如何訪問我在Tester類中讀取的數據並將它們顯示在UI中? – sergerde 2012-07-07 21:44:48

+0

@ZuZuZzZz:你給測試者類訪問器和增變器(getter和setter)方法。 – 2012-07-07 21:47:17