2016-03-30 50 views
0
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."); 
    } 
} 

這是我的代碼。我正在詢問用戶字母表中的下一個字母是什麼。我無法弄清楚正確的字符串結果。我想讓程序知道答案是否正確。線程「main」中的異常java.lang.NumberFormatException:用於輸入字符串:「G」

回答

0

很明顯,你會得到NumberFormatException的,如果你的祕密字符串「G」爲整數。 你應該檢查 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."; 
} 
0

你所得到的NumberFormatException因爲你試圖通過執行以下操作來解析與字母組成的字符串到整數

int letter = Integer.parseInt(response); 

如果你想將它轉換爲一個整數,那麼你應該這樣做:

int letter = Character.getNumericValue(response.charAt(0)); 
相關問題