【问题标题】:Reading the value of a Math.random generated button label读取 Math.random 生成的按钮标签的值
【发布时间】:2019-10-03 00:52:15
【问题描述】:

我正在做一个要求我做以下事情的练习;

  1. 创建一个 GridPane
  2. 将窗格的水平和垂直间隙设置为零
  3. 将窗格的网格线可见性设置为 true
  4. 使用嵌套的 FOR 循环创建按钮并将其添加到窗格(循环 从0到10)
  5. 每个按钮都必须标有 0 到 99 之间的任意数字
  6. 根据以下规则为按钮着色: 一个。如果颜色的标签可以被 2 整除,则将颜色更改为蓝色 湾。如果颜色的标签可以被 3 整除,则将颜色更改为 黄色 C。如果颜色的标签可以被 6 整除,则将颜色更改为绿色

  7. 将窗格添加到场景中

  8. 将场景添加到舞台,然后显示舞台

我已经设置好了所有东西,只是不确定如何读取 Math.random 生成的值并为该按钮分配特定颜色。

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.scene.layout.GridPane;
import javafx.scene.control.Button;
import javafx.scene.paint.Color;



public class Exercise8GridPane extends Application {

    @Override
    public void start(Stage primary) {
        primary.setTitle("Exercise 8");
        GridPane gp = new GridPane();
        gp.setHgap(0);
        gp.setVgap(0);
        gp.setGridLinesVisible(true);
        for (int k = 0; k < 10; k++) {
            for (int l = 0; l < 10; l++) {                
                Button btn = new Button(String.valueOf((int)(Math.random() * 100)));
                // if / 3 == 0){
                btn.setStyle("-fx-base:red;-fx-text-fill:yellow"); 

                  gp.add(btn, l, k);  
            }

        }
        Scene s = new Scene(gp);
        primary.setScene(s);
        primary.show();
        }
    public static void main(String[] args) {
        launch(args);
    }
}

【问题讨论】:

  • 您的问题是什么?你在做什么有什么问题?
  • 听起来您实际上是在问如何实施第 6 步。对吗?
  • 是的,我一直在尝试执行第 6 步。
  • 请注意,要生成ints,创建Random 的实例并使用其nextInt 方法更方便。至于问题:不确定这里到底是什么问题:确定int 是否可以被某个数字整除?给定颜色名称设置颜色? ...?
  • 首先将随机值放入变量中:int value = (int)(Math.random() * 100); Button btn = new Button(String.valueOf(value)); 步骤 6 中描述的测试可以使用模运算符 (%) 完成。

标签: java javafx


【解决方案1】:

java.lang.Math.random() 返回一个带正号的双精度值,大于等于 0.0 小于 1.0。这个新的伪随机数生成器随后用于对该方法的所有调用,并且不会在其他任何地方使用。

有无数种阅读方式。

我建议做类似的事情

int RED = (int) (Math.random() * 256); 
// Note that Math.random() returns a value less than 1.0 
int BLUE = ...

很难从一个数字中得到三个值,所以我认为这会很好。

【讨论】:

  • 看来问题是关于解释随机值,而不仅仅是阅读它。标题具有误导性。
  • 感谢您澄清这一点。我已经编辑了我的问题以包含一种方式。
【解决方案2】:
Math.random() -> 0.0 - 0.9999999...
(int)(Math.random() * 5) -> 0 - 4
(int)(Math.random() * 5 + 1) -> 1 - 5

所以你可以这样写:

int colorNum = (int)(Math.random() * 4);
if(colorNum ==0)
    //set button to red
//etc.

【讨论】:

  • 如果 Langrisser 想要拥有许多不同深浅的红色怎么办?
猜你喜欢
  • 2020-08-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-26
  • 1970-01-01
  • 2018-05-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多