我正在寫一個遊戲,讓用戶猜測隨機生成的數字。最後它會顯示正確的總數和這些正確數字的總和。但是,我無法顯示用戶擁有的正確數字的正確總和。有人可以幫我弄這個嗎?謝謝!猜測遊戲Java
public static void main(String[] args) {
Random rng = new Random();
Scanner consoleScanner = new Scanner(System.in);
String inputString;
int answer = rng.nextInt(90000) + 10000, sum, numberCorrect;
System.out.print("I have randomly chosen a 5-digit code for you to guess.\n"
+ "Each time you guess, I will tell you how many digits are correct and the sum of the digits that are correct.\n"
+ "For example, if the number is \"68420\" and you guess 12468, I will respond:\n"
+ "Number of Digits Correct: 1\n" + "Sum of Digits Correct : 4\n"
+ "From deduction, you will know the 4 was correct in the guess.\n\n"
+ "Now its your turn..................................................................\n" + "answer = "
+ answer);
do {
System.out.print("\nPlease enter a 5-digit code (your guess): ");
inputString = consoleScanner.nextLine();
numberCorrect = 0;
sum = 0;
if (inputString.length() != 5) {
System.out.println("Please enter 5-digit code only.");
System.exit(0);
}
for (int i = 0; i < 5; i++) {
String answerString = String.valueOf(answer);
if (inputString.charAt(i) == answerString.charAt(i)) {
numberCorrect++;
char digit = answerString.charAt(i);
sum += digit;
}
}
System.out.println("Number of Digits Correct: " + numberCorrect + "\nSum of Digits Correct: " + sum);
}
while (numberCorrect < 5);
System.out.println("****HOORAY! You solved it. You are so smart****");
}
對不起,這不是StackOverflow的是如何工作的。問題形式_「這是我的一堆代碼,請爲我調試」_被認爲是無關緊要的。請訪問[幫助]並閱讀[問]獲取更多信息,尤其是閱讀[爲什麼是「有人可以幫助我?」不是一個實際問題?](http://meta.stackoverflow.com/q/284236/18157 ) –
你的數字變量是char類型。所以當我們得到一個'0'時,它實際上是整數值48(ASCII表),你需要將char轉換爲一個int。 – JackVanier