2015-10-14 72 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