2015-10-14 77 views
1

package minFinder; /* *取自用戶的兩個值並找到較小的值 */第二個JOptionPane.showInputDialog不打開

import java.util.Scanner;

import javax.swing.JOptionPane;

公共類minFinder {

public static void main(String[] args) { 
    Scanner keyboard = new Scanner(System.in); 
    double num1, num2; 

    JOptionPane.showInputDialog("Please input the first number"); 
    num1 = keyboard.nextDouble(); 

    JOptionPane.showInputDialog("Please input the second number"); 
    num2 = keyboard.nextDouble(); 

    JOptionPane.showInputDialog(Math.min(num1, num2)); 
} 

}

這是困擾着我,無論什麼原因,代碼,第二和第三對話框無法打開,我能得到一些幫助,這?我覺得解決方案可能很明顯。

感謝

+1

?這沒有意義 – MadProgrammer

回答

2

無論出於何種原因,第二和第三對話框無法打開,

掃描儀正在等待你從鍵盤輸入的數據。

擺脫Scanner類。如果你打算使用GUI,那麼你不需要從鍵盤輸入。

有關使用JOptionPane的示例,請查看Getting Input From the User上的Swing教程部分。

+0

我假設你會更新以顯示OP應該如何使用'inputDialog',所以我現在只需+1 – MadProgrammer

1

掃描儀僅從控制檯獲取輸入。輸入對話框已經有一個接受輸入的GUI,所以你可以擺脫掃描儀。

第二個和第三個對話框沒有顯示的原因是因爲第一個掃描儀仍在等待輸入,即使已經在輸入對話框中輸入了一些文本。第一個工作是因爲Scanner不在等待任何輸入。

下面是正確的代碼:

package minFinder; /* * Takes two values from the User and and finds the smaller value */ 

import java.util.Scanner; 

import javax.swing.JOptionPane; 

public class minFinder { 
    public static void main(String[] args) { 
     double num1, num2; 

     num1 = Double.parseDouble(JOptionPane.showInputDialog("Please input the first number")); 
     num2 = Double.parseDouble(JOptionPane.showInputDialog("Please input the first number")); 

     JOptionPane.showMessageDialog(null, Math.min(num1, num2)); //Note how I changed it to a message dialog 
    } 
} 

你應該考慮一些其他的事情是類名應以大寫字母開始,包名應該是完全小寫。

上面的代碼實際上並沒有檢查輸入的字符串是否爲double,所以如果它是無效的數字,則會拋出NumberFormatException。解決此問題的方法是做到以下幾點:

package minFinder; /* * Takes two values from the User and and finds the smaller value */ 

import javax.swing.JOptionPane; 

public class minFinder { 
    public static void main(String[] args) { 
     double num1 = 0; 
     double num2 = 0; 
     boolean invalidNumber; 

     try { 
      num1 = Double.parseDouble(JOptionPane.showInputDialog("Please input the first number")); 
     } catch(NumberFormatException e) { 
      invalidNumber = true; 
      while(invalidNumber) { 
       try { 
        num1 = Double.parseDouble(JOptionPane.showInputDialog("Invalid number. Please try again")); 
        invalidNumber = false; 
       } catch(NumberFormatException e2) {} 
      } 
     } 

     try { 
      num2 = Double.parseDouble(JOptionPane.showInputDialog("Please input the second number")); 
     } catch(NumberFormatException e) { 
      invalidNumber = true; 
      while(invalidNumber) { 
       try { 
        num2 = Double.parseDouble(JOptionPane.showInputDialog("Invalid number. Please try again")); 
        invalidNumber = false; 
       } catch(NumberFormatException e2) {} 
      } 
     } 

     JOptionPane.showMessageDialog(null, Math.min(num1, num2)); 
    } 
} 

下面是關於對話的一些詳細信息:你爲什麼要使用`inputDialog`,並要求用戶輸入通過命令行的值http://docs.oracle.com/javase/tutorial/uiswing/components/dialog.html