我需要一点帮助,我的机器人猜测游戏应用程序的一些java编码。
目前,我的if else语句涵盖猜测是否太高,太低或正确。我想要它做的是告诉用户他们给出的答案是接近答案还是远离答案。比如说,在50%或50%以内。我可以做其他地方使用数字,但是当我试图找出如何根据程序生成的随机数计算出百分比时,我会感到难过。如果它是一个静态数字我会没事的但是我不能这样做。
非常感谢任何帮助。
package lab.mad.cct.c3375331task1;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.util.Random;
public class Task1Activity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.task1_layout);
final TextView textResponse = (TextView) findViewById(R.id.txtResponse);
final TextView guessText = (TextView) findViewById(R.id.txtAnswer);
final EditText userGuess = (EditText) findViewById(R.id.etNumber);
Button pressMe = (Button) findViewById(R.id.btnGuess);
// When the button is clicked, it shows the text assigned to the txtResponse TextView box
pressMe.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String randText = "";
Random randGen = new Random();
int ranNum = randGen.nextInt(5);
int userNumber = Integer.parseInt(userGuess.getText().toString());
int attempts = 0;
if (userNumber >19 ) {
guessText.setText("Please guess between 0 and 20");
} else if (userNumber == ranNum) {
guessText.setText("You got it!");
} else if (userNumber < ranNum) {
guessText.setText("Your answer is too low. Guess again!");
guessText.setBackgroundColor(Color.RED);
} else if (userNumber > ranNum) {
guessText.setText("Your answer is too high. Guess again!");
}
randText = Integer.toString(ranNum);
textResponse.setText("");
userGuess.setText("");
}
});
}
}
答案 0 :(得分:0)
您可以像这样计算两个数字(随机数和猜测数字)之间的百分比差异:
public static String flattenToAscii(String string) {
char[] out = new char[string.length()];
String normalized = Normalizer.normalize(string, Normalizer.Form.NFD);
int j = 0;
for (int i = 0, n = normalized.length(); i < n; ++i) {
char c = normalized.charAt(i);
if (c <= '\u007F') out[j++] = c;
}
return new String(out);
}
值public float percentDiff(int randomNumber, int guessedNumber) {
int diff = Math.abs(randomNumber - guessedNumber);
float diffPercentage = (float) diff / (float) randomNumber;
System.out.println("" + diffPercentage);
return diffPercentage;
}
将超过50%,反之亦然。
答案 1 :(得分:0)
如果你想计算(在飞行中)用户提供的数字是随机生成的数字的百分比,那么你可以使用一个简单的公式,如:
int percentOf = ((userNumber * 100) / ranNum);