2013-10-26 17 views
0

我正在做一個java課程介紹的作業,並且遇到困難時,問題如下:如何通過對話框收集用戶的輸入?

「要求用戶輸入一個數字,您應該使用輸入對話框輸入此輸入。確保將字符串從對話框轉換爲實數,程序需要跟蹤用戶輸入的最小數字以及輸入的最大數字,詢問用戶是否要輸入另一個數字,如果是,重複這個過程。如果沒有,那用戶輸入輸出的最小和最大數量。

此程序輸出的最大和最小數量的AT當用戶想退出程序的結束。

另外,當用戶只輸入一個數字時,你的程序應該考慮這種情況。在這種情況下,最小和最大的數字將是相同的。「

我無法獲得輸入對話框以適合我的代碼並將該輸入轉換爲可用於計算的整數。 !不知道如何解釋超過兩個進入更多的數字用戶,但我不是要去成現在 任何幫助,將不勝感激,謝謝提前

這是我到目前爲止有:


package findingminandmax; 

import javax.swing.JOptionPane; 

public class Findingminandmax 
{ 

    public static void main(String[] args) 
    { 

      int i = 3; 
      int j = 2; 
      int k = max(i, j); 
      JOptionPane.showMessageDialog(null, "The maximum between " + i + 
        " and " + j + " is " + k); 
    } 

    public static int max(int num1, int num2) { 
     int result; 

     if (num1 > num2) 
      result = num1; 
     else 
      result = num2; 

     return result; 
    } 
} 

回答

2

對於輸入,使用方法:

String s = JOptionPane.showInputDialog(message)); 

如果你想將它轉換爲一個整數:

爲float:

float f = Float.parseFloat(s); 

或一個雙:

double d = Double.parseDouble(s); 

此外,爲了接受超過1個輸入,你可以使用一個for循環或while:

int n = 5; // Number of times the input will be requested 
for (int i = 0; i < n; i++) { 
    ... 
    // Code here to accept the input 
    String s = JOptionPane.showInputDialog(message)); 
    ... 
} 

如果你要存儲許多輸入,您可能需要將它們存儲在數組中。 ArrayList

相關問題