gpt4 book ai didi

Java - 如何检查 JOptionPane.showInputDialog 中确切输入的内容

转载 作者:行者123 更新时间:2023-12-02 07:03:24 25 4
gpt4 key购买 nike

这是我的代码

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);

}

}

最佳答案

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);
}

关于Java - 如何检查 JOptionPane.showInputDialog 中确切输入的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16374997/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com