2012-04-07 30 views
1

我需要使用for循環和數組來獲取兩個輸入並將它們相減(輸入格式hh:mm:ss)。然後在editText中輸出差異。但我似乎無法讓我的代碼運行。使用for循環找到兩個時間字符串之間的差異(hh:mm:ss)

對不起,如果這是一個非常基本的問題。我花了好幾天的時間在網絡上試圖瞭解問題。這是我第一次嘗試Java。

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 

    end = (EditText) findViewById(R.id.etEnd); 
    start = (EditText) findViewById(R.id.etStart); 
    diff = (EditText) findViewById(R.id.etDiff); 
    calc = (Button) findViewById(R.id.bCalc); 
    clear = (Button) findViewById(R.id.bClear); 

    calc.setOnClickListener(new View.OnClickListener() { 

     @Override 
     public void onClick(View v) { 
      // TODO Auto-generated method stub 
       int hh = tot[0]; 
       int mm = tot[1]; 
       int ss = tot[2]; 

      String sGet2 = end.getText().toString(); // end to string 
      String sGet1 = start.getText().toString(); // start to string 

      String[] erA = sGet2.split(":"); // end string to end array 
      String[] srA = sGet1.split(":"); // start string to string array 

      for (int i = 0; i < srA.length; i++) { 

       inted = Integer.parseInt(erA[i].trim()); 
       intst = Integer.parseInt(srA[i].trim()); 

       tot[i] = inted - intst; 

       if (i == 2) { 
        String mt = ":" + mm; 
        String st = ":" + ss; 
        String ht = ":" + hh; 
        String tota = mt + st; 
        String total = tota + ht; 

        out = String.format("%4.4s", total); 

        diff.setText(out); 

       } else 
        return; 

回答

1

這並不奇怪,你的代碼不工作......它從來沒有執行過很多!

for (int i = 0; i < srA.length; i++) { 
    // bla bla bla 
    if (i == 2) { 
     // This code never runs because i is always 0. 
    } else 
     return; // What is this doing here!? 
} 

如果這是你在編程第一次嘗試那麼我認爲你應該更簡單的東西一點點開始,如控制檯程序。也可以使用調試器來遍歷代碼,以便您可以看到控制流程如何工作。

您可能還想購買一本教Java的書。有許多好書可以用來開始你的基礎知識。

0

偉大的代碼爲什麼返回其他部分。它在i = 0時終止執行。這是for循環開始執行。

第一次我的值是零,你的條件i == 2失敗,那麼它執行其他部分,所以它終止for循環。那麼for循環有什麼用?

使用下面的代碼::

String time1 = "22:55:00"; 
String time2 = "23:05:00"; 
SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss"); 
Date date1 = format.parse(time1); 
Date date2 = format.parse(time2); 
long difference = date2.getTime() - date1.getTime();   

的區別是在米利斯你可以將其轉換爲任何單位或者您可以使用來自Apache的公共DurationFormatUtils到相當格式化。

System.out.println("Duration: "+DurationFormatUtils.formatDuration(difference, "HH:mm:ss")); 

阿帕奇百科全書具有非常好的實用功能,Apache的公地(郎)

+0

我應該拿出if和else語句,並把是否碼後的for循環?哦,失去了回報; – 2012-04-07 03:23:39

+0

你究竟在做什麼 – 2012-04-07 03:25:49

+0

我有三個EditText的。其中兩個用於輸入(例如hh:mm:ss)。第三個將在提交按鈕被按下時顯示差異。 – 2012-04-07 21:54:06

相關問題