线程" main"中的例外情况java.lang.NumberFormatException:对于输入字符串:" G"

时间:2016-03-30 22:50:45

标签: java

import java.util.Scanner;
import java.util.Random;

public class ResponseTimeProject
{
    public static void main(String[] args)
    {
         Scanner in = new Scanner(System.in);
         Random rand = new Random();

         System.out.print("Please enter your full name: ");
         String name = in.nextLine();

         System.out.println ("Hello " + name 
         + ". Please answer as fast as you can."
         + "\n\nHit <ENTER> when ready for the question.");
         in.nextLine();

         String alphabet="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
         int character=(int)(Math.random()*26);
         String s=alphabet.substring(character, character+1);

         Random r = new Random();

         for (int i = 0; i < 1; i++) 
         {
             System.out.println (alphabet.charAt(r.nextInt(alphabet.length())));
         } 

         long startTime = System.currentTimeMillis();

         System.out.print("What is the next letter in the alphabet?" + " ");
         String response = in.nextLine();
         int letter = Integer.parseInt(response);

         long endTime = System.currentTimeMillis();

         String outcome;
         if  (letter == character+1)
             outcome = "Correct!";
         else
             outcome = "Incorrect.";

         long reactionTime = endTime - startTime;

         System.out.println("That took " + reactionTime + " milliseconds");
         System.out.println("Thank you "  + name + ", goodbye.");
    }
}

这是我的代码。我试图询问用户字母表中的下一个字母是什么。我无法弄清楚正确的字符串结果。我希望程序判断答案是否正确。

2 个答案:

答案 0 :(得分:0)

很明显,如果你转换String&#34; G&#34;你会得到NumberFormatException。到整数。 你应该检查 letter.equals(alphabet.substring(character+1, character+2))而不是letter == character+1

这是经过纠正的

System.out.print("What is the next letter in the alphabet?" + " ");
String response = in.nextLine();

long endTime = System.currentTimeMillis();

String outcome;
if (alphabet.substring(character+1, character + 2).equals(response)) {
    outcome = "Correct!";
} else {
    outcome = "Incorrect.";
}

答案 1 :(得分:0)

您正在获取NumberFormatException,因为您尝试通过执行以下操作将带字母的字符串解析为整数:

int letter = Integer.parseInt(response);

如果你想将它转换为整数,那么你应该做这样的事情:

int letter = Character.getNumericValue(response.charAt(0));