【发布时间】:2018-04-18 02:24:13
【问题描述】:
我正在尝试编写一个程序来选择用户输入的随机值,但我得到了错误 - 从 double 到 int 的可能有损转换。这是我的代码。任何帮助表示赞赏。
public class Driver
{
public static void main(String [] args)throws IOException{
int random;
int options;
Scanner input = new Scanner(System.in);
int randy;
System.out.print("Please enter the number of options you would like to use: ");
String [] choices = new String [input.nextInt()];
int min = 1;
int max = choices.length;
random = (Math.random() * ((max - min) + 1)) + min;
for(int i = 0; i < choices.length; i++){
System.out.print("Enter option " + (i+1) + ": ");
choices[i] = input.next();
}
System.out.print("The random option chosen is: " + choices[random]);
}
}
【问题讨论】:
-
Math.random()返回一个双精度值。 -
如果你使用
java.util.Randon它有nextIntdocs.oracle.com/javase/7/docs/api/java/util/… -
我不得不问:在发帖之前,您是否在您选择的搜索引擎中输入了错误消息?