Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/304.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java-从double到int的可能有损转换_Java_Arrays_Random - Fatal编程技术网

Java-从double到int的可能有损转换

Java-从double到int的可能有损转换,java,arrays,random,Java,Arrays,Random,我正试图编写一个程序,选择一个用户输入的随机值,我得到了从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.o

我正试图编写一个程序,选择一个用户输入的随机值,我得到了从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]);
}
}
公共类驱动程序
{
公共静态void main(字符串[]args)引发IOException{
int随机;
int选项;
扫描仪输入=新扫描仪(System.in);
内兰迪;
System.out.print(“请输入要使用的选项数:”);
String[]choices=新字符串[input.nextInt()];
int min=1;
int max=choices.length;
随机=(Math.random()*((max-min)+1))+min;
for(int i=0;i
因为Math.random()将doube、cast random或Math.random()返回给int:


出现该错误的原因是
Math.random()
返回双精度。所以这条线

(Math.random() * ((max - min) + 1)) + min;
将尝试为
random
分配一个双精度,该双精度是
int
。编译器不喜欢看到这一点,因此您无法通过它。有一个解决办法。您可以将其强制转换为
int
,从而

(int)((Math.random() * ((max - min) + 1)) + min);

这将使值向下舍入。请注意,这样做永远不会得到
max
的值,因此您不必担心
索引自动边界异常

作为旁注:当您尝试将较大值的数据类型分配给较小的数据类型时,该值可能会被截断。这是一个类型安全问题。

返回一个双精度。如果您使用
java.util.Randon
它有
nextInt
我必须问:在这里发布之前,您是否在您选择的搜索引擎中键入了错误消息?
(int)((Math.random() * ((max - min) + 1)) + min);