【发布时间】:2015-06-18 10:03:28
【问题描述】:
朋友们,
我是一名土木工程师。现在我正在从事 Android 开发工作。我知道 Java 和 C#,但我认为我的编程知识只是像阅读和理解这样的编辑。如何提高我的技能,比如编写专门为 C# 和 Java 编写的程序。
谢谢。
那么这是我的问题..
例如,我有 3 个按钮和 3 个 int 值。
如何使按钮文本在按钮单击时从 3 个 int 值字符串中随机选择。
这是一款适用于 Android 平台的简单数学游戏。
TextView textA = (TextView) findViewById(R.id.textView);
TextView textB = (TextView) findViewById(R.id.textView3);
final Button button1 = (Button) findViewById(R.id.button1);
final Button button2 = (Button) findViewById(R.id.button2);
final Button button3 = (Button) findViewById(R.id.button3);
Random rand = new Random();
final int x = rand.nextInt(1000);
Random randB = new Random();
int y = randB.nextInt(1000);
Random randw = new Random();
int w = randw.nextInt(1000);
Random randz = new Random();
int z = randz.nextInt(1000);
int A = x;
int B = y;
int Wrong1 = (A + w);
int Wrong2 = (A + z);
final int CorrectAnswer = (A + B);
String text = "text";
Button[] arr = {button1, button2, button3};
Random r = new Random();
Button b = arr[r.nextInt(arr.length)];
b.setText(text);
int Ans1 = CorrectAnswer;
int Ans2 = Wrong1;
int Ans3 = Wrong2;
textA.setText("" + A);
textB.setText("" + B);
button1.setText("" + Wrong1);
button2.setText("" + Wrong2);
button3.setText("" + CorrectAnswer);
final int ACAns;
ACAns = Integer.parseInt(button3.getText().toString());
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
int AAns = Integer.parseInt(button1.getText().toString());
if ((AAns == ACAns)) {
Toast.makeText(getBaseContext(), "Your answer is correct!", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getBaseContext(), "Your answer is Wrong!", Toast.LENGTH_SHORT).show();
}
}
});
button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
int BAns = Integer.parseInt(button2.getText().toString());
int ACAns = Integer.parseInt(button1.getText().toString());
if ((BAns == ACAns)) {
Toast.makeText(getBaseContext(), "Your answer is correct!", Toast.LENGTH_SHORT).show();
} else {
}
}
});
button3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
int CAns = Integer.parseInt(button3.getText().toString());
int ACAns = Integer.parseInt(button3.getText().toString());
if ((CAns == ACAns)) {
Toast.makeText(getBaseContext(), "Your answer is correct!", Toast.LENGTH_SHORT).show();
return;
} else {
Toast.makeText(getBaseContext(), "Your answer is Wrong!", Toast.LENGTH_SHORT).show();
}
【问题讨论】:
-
将值存储在
array中并在点击时选择一个 -
我需要随机设置Button文本...如何??
-
抱歉,无法理解您真正想要什么。是从数组中随机设置按钮文本还是随机生成文本字符串并将其设置为按钮文本?
-
我需要将 Wrong1、Wrong2、CorrectAnswer 字符串设置为按钮文本。如果 Button1 选择 Wrong1 然后 Button2 从 Wrong2 和 CorrectAnswer 中随机选择,则按钮会像 Button1.getText(wrong1 or Wrong2 or CorrectAnswer) 一样随机获取此值。
-
我想我知道你想做什么。如果这不是您想要做的,请检查我的回答和评论。但最好的办法可能是改写一点你的问题,因为它很不清楚你首先想做什么。希望我的回答能有所帮助
标签: java android button random