gpt4 book ai didi

java - 如何在android开发中随机化if语句

转载 作者:行者123 更新时间:2023-12-01 18:28:11 25 4
gpt4 key购买 nike

我正在 android 中构建一个调查问卷类型的应用程序,我想知道如果 if 语句具有相同的值,是否有办法随机化最终输出?换句话说,我不希望每次都出现一个结果,我希望结果在“干得好”和“干得好”之间随机出现,有人知道这是否可能吗?

这是我的代码:

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_system);
RadioGroup gender = (RadioGroup) findViewById(R.id.answer1);
gender.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(RadioGroup group, int checkedId) {
// TODO Auto-generated method stub
switch (checkedId) {
case R.id.answer1A:
ans1 = 1;
break;
case R.id.answer1B:
ans1 = 2;
break;
}
}
});
RadioGroup nutrition = (RadioGroup) findViewById(R.id.answer2);
nutrition.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(RadioGroup group, int checkedId) {
// TODO Auto-generated method stub
switch (checkedId) {
case R.id.answer2A:
ans2 = 1;
break;
case R.id.answer2B:
ans2 = 2;
break;
}
}
});


btnSubmitQuiz = (Button) findViewById(R.id.submit);
btnSubmitQuiz.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// 1
if (ans1 == 1 && ans2 == 1) {

displayResult("good job");

}

if (ans1 == 1 && ans2 == 1 ) {

displayResult("well done");

}


else {

displayResult("FAIL");

}
}

private void displayResult(String result) {
Intent i = new Intent("com.example.system.SHOWRESULT");
i.putExtra("unique_constant", result);
startActivity(i);

}
});

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.system, menu);
return true;
}

}

最佳答案

您可以使用一个函数从正确结果响应的字符串数组中生成随机索引。

String[] correctResults;
Random randomGenerator;

public void onCreate (Bundle savedInstanceState) {
//All your init stuff...
generator = new Random();
correctResults = new String[] {"good job", "well done"};
}

public String getRandomCorrectResult() {
return correctResults[generator.nextInt(correctResults.length)];
}

只需在 if 语句中调用 getRandomCorrectResult() 即可!

关于java - 如何在android开发中随机化if语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25270677/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com