2017-03-08 134 views
-6

我正在写一个游戏,让用户猜测随机生成的数字。最后它会显示正确的总数和这些正确数字的总和。但是,我无法显示用户拥有的正确数字的正确总和。有人可以帮我弄这个吗?谢谢!猜测游戏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****"); 
} 
+10

对不起,这不是StackOverflow的是如何工作的。问题形式_“这是我的一堆代码,请为我调试”_被认为是无关紧要的。请访问[帮助]并阅读[问]获取更多信息,尤其是阅读[为什么是“有人可以帮助我?”不是一个实际问题?](http://meta.stackoverflow.com/q/284236/18157 ) –

+1

你的数字变量是char类型。所以当我们得到一个'0'时,它实际上是整数值48(ASCII表),你需要将char转换为一个int。 – JackVanier

回答

-1

你有你的字符转换成数值:

sum += Character.getNumericValue(digit); 
+0

非常感谢你! –