【问题标题】:Random number generation with random operators使用随机运算符生成随机数
【发布时间】:2017-04-02 02:01:10
【问题描述】:

我是 android 开发的新手,目前正在开发一个简单的应用程序,除其他外,它每次都需要使用随机运算符(+、-、*、/)生成随机数。我有一个“生成”按钮,每次按下它都会给出不同的问题。我知道如何生成随机数,但我不知道如何生成随机运算符,因此每次问题都不一样。我尝试使用 switch 语句,但到目前为止没有成功(或者我缺少其中的代码)。任何人都可以帮忙吗?提前致谢。

这是我到目前为止的代码:

private void goGenerate() {

    num1 = (int)(Math.random()*10) + 1;
    num2 = (int)(Math.random()*10) + 1;
    generate();
}

private void generate() {
    StringBuilder equation = new StringBuilder();
    goGenerate();

    operator = (int)(Math.random() *4 ) + 1;

    equation.append(num1);
    if(operator == 1) {
        equation.append("+");
        result = num1 + num2;
    }
    else if(operator == 2) {
        equation.append("-");
        result = num1-num2;
    }
    else if(operator == 3) {
        equation.append("*");
        result = num1 * num2;
    }
    else if(operator == 4) {
        equation.append("/");
        while((num1 % num2 != 0) && (num1 < num2)) {
            generate();
        }
        result = num1 / num2;
    }

    textViewOperation.setText(operator);

【问题讨论】:

  • 请发布您已经尝试过的代码,以便我们帮助您解决问题

标签: android random


【解决方案1】:

创建两个随机例程,一个用于您的数字,一个限制为 0-3,您可以将每个可能的数字(0 到 3)与一个运算符相关联。然后就完成了。祝你好运。

编辑(可行):

int operator, num1, num2, result;
StringBuilder equation;

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    final TextView tv1 = (TextView) findViewById(R.id.tv1);
    tv1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            generate();
            tv1.setText(String.valueOf(result));
        }
    });

}



private Integer generate() {

    equation = new StringBuilder();
    num1 = (int)(Math.random()*10) + 1;
    num2 = (int)(Math.random()*10) + 1;

    operator = new Random().nextInt(4);

    equation.append(num1);
    if (operator == 1) {
        equation.append("+");
        result = num1 + num2;
    } else if (operator == 2) {
        equation.append("-");
        result = num1 - num2;
    } else if (operator == 3) {
        equation.append("*");
        result = num1 * num2;
    } else if (operator == 4) {
        equation.append("/");
        while ((num1 % num2 != 0) && (num1 < num2)) {
            generate();
        }
        result = num1 / num2;
    }
    return result;
}}

【讨论】:

  • 感谢您的回答。我明白你在说什么。不过,我不确定如何将号码与运营商相关联。
  • if (random_num == 1) my_operator = "/"; (等等)
  • @LukasA。如果您更喜欢编辑您的答案,请发布您的代码,我会帮助您实现这一点。
  • 我把代码放在我最初的问题中。当我用完字符时不确定如何将其添加到 cmets 中?:S
  • 很好:首先我会使用int operator = new Random().nextInt(4);(我不知道你的方法是否有相同的结果)。好吧,我认为这就是全部。你得到你想要的了吗?
猜你喜欢
  • 2021-09-12
  • 2022-10-07
  • 1970-01-01
  • 1970-01-01
  • 2019-07-03
  • 1970-01-01
  • 2022-11-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多