Java 如果我们在使用(int)(Math.random())时进行强制转换,则不会';即使我们乘以另一个值,我们的变量也不能赋值为零吗?

Java 如果我们在使用(int)(Math.random())时进行强制转换,则不会';即使我们乘以另一个值,我们的变量也不能赋值为零吗?,java,random,casting,Java,Random,Casting,我正在一本教科书中运行一些小型编程项目,我想知道,如果我们在下面的程序中强制转换为int类型,oneLength,twonelength,threeLength是否都被赋值为0?我知道,因为我们将强制转换为int,所以值将从0到1,这意味着0将是包含的,而1是独占的。例如,如果我们有0*(12),12是wordListOne的长度,那么最终的值不是0吗 节目如下: 公共类涂鸦板{ public static void main(String[] args) { String[] wor

我正在一本教科书中运行一些小型编程项目,我想知道,如果我们在下面的程序中强制转换为int类型,
oneLength
twonelength
threeLength
是否都被赋值为0?我知道,因为我们将强制转换为int,所以值将从0到1,这意味着0将是包含的,而1是独占的。例如,如果我们有0*(12),12是
wordListOne
的长度,那么最终的值不是0吗

节目如下:

公共类涂鸦板{

public static void main(String[] args) {

    String[] wordListOne = {"24/7", "multi-Tier", "30,000 foot", "B-to-B", "win-win", "front-end", "web-based", "pervasive", "smart", "six-sigma", "critical-patch", "dynamic"};

    String[] wordListTwo = {"empowered", "sticky", "value-added", "oriented", "centric", "distributed", "clustered", "branded", "outside-the-box", "positioned", "networked", "focused", "leveraged", "aligned", "targeted", "shared", "cooperative", "accelerated"};

    String[] wordListThree = {"process", "tipping-point", "solution", "architecture", "core competency", "strategy", "mindshare", "portal", "space", "vision", "paradigm", "mission"};


    // oneLength : number of items in array

    int oneLength = wordListOne.length;
    int twoLength = wordListTwo.length;
    int threeLength = wordListThree.length;

    // rand1 : casting to int value

    int rand1 = (int) (Math.random() * oneLength);
    int rand2 = (int) (Math.random() * twoLength);
    int rand3 = (int) (Math.random() * threeLength);


    // phrase : 

    String phrase = wordListOne[rand1] + " " + wordListTwo[rand2] + " " + wordListThree[rand3];

    System.out.println("What we need is a " + phrase); }}
非常感谢你给我的帮助,非常感谢

int rand1 = (int) (Math.random() * oneLength);
我们知道
oneLength==12

图像如果
Math.random()
给出
0.72
-现在将其乘以
12
-结果是
9.12
-现在将其转换为整数-结果是
9

如果
Math.random()
给你一个小于的数字,那么
00833..
会得到一个
0
的值,为什么


因为:
12*x<1=>x<1/12=0.0833..

你能解释一下表达式中括号
()
的功能是什么吗?在这种情况下,你是指(int)吗?我们正在使用强制转换过程将类型从double更改为int。我不是指那些括号;我指的是
(Math.random()*oneLength)中的括号
。好的,那么为什么您希望右侧的值(分配到
rand1
中的表达式)为零?我认为您需要阅读“运算顺序”的概念,以及
(Math.random()*oneLength)
的目的是什么。尝试一下
(int)(Math.random()*oneLength)
((int)Math.random())*oneLength
。请注意,括号会影响表达式的类型(double或int),不仅仅是数值。我看到了我所犯的错误。我在计算乘法和得到结果之前生成的随机数。在本例中,我所做的是在乘法之前计算0.72。所以,基本上,我是将0乘以12,得到0作为结果。@Sampoo括号很重要。你不应该有这个问题,th你放的括号是对的!我也试过。。。