2013-05-04 20 views
0

这是我的代码爪哇 - 我怎么能检查究竟是什么进入了JOptionPane.showInputDialog

import java.util.Random; 

import javax.swing.JOptionPane; 
public class randomnumbersv2 { 

    public static void main(String[] args){ 
     Double randomnumber = Double.parseDouble(JOptionPane.showInputDialog("Please enter the maximum number that you would like this program to generate")); 

     Random rnd = new Random(); 
     System.out.println(rnd.nextInt(How would I make sure that what is eneted in the Joption can be put into here)); // change int to whatever number you want, this number will be the max random number generated 

     JOptionPane.showMessageDialog(null, "Your random number is" + randomnumber); 

    } 

} 

回答

2

Random#nextInt接受整数值作为其上限。因此输入的值应该是这样的。此外,根据文档,数字应为正数:

try { 
    int maxNumber = 
      Integer.parseInt(JOptionPane.showInputDialog("Please enter input")); 

    if (maxNumber > 0) { 
    Random rnd = new Random(); 
    System.out.println(rnd.nextInt(maxNumber)); 
    } else { 
    throw new IllegalArgumentException("Non positive number not allowed"); 
    } 
} catch (NumberFormatException e) { 
    throw new IllegalArgumentException("Invalid integer", e); 
}