2014-08-31 31 views
0

當我就行了這個Java程序的StringIndexOutOfBounds錯誤:的Java StringIndexOutOfBounds使用子串

String num3 = lottoString.substring(2,2); 

告訴我,2超出範圍的,但是這個代碼應隨機挑選範圍三位數彩票號碼從000到999.我的錯誤是什麼?

import java.util.Scanner; 
public class Lottery 
{ 
    public static void main(String[] args) 
    { 
     //Declare and initialize variables and objects 
     Scanner input = new Scanner(System.in); 
     String lottoString = ""; 

     //Generate a 3-digit "lottery" number composed of random numbers 
     //Simulate a lottery by drawing one number at a time and 
     //concatenating it to the string 
     //Identify the repeated steps and use a for loop structure 
     for(int randomGen=0; randomGen < 3; randomGen++){ 
      int lotNums = (int)(Math.random()*10); 
      lottoString = Integer.toString(lotNums); 
     } 

     String num1 = lottoString.substring(0,0); 
     String num2 = lottoString.substring(1,1); 
     String num3 = lottoString.substring(2,2); 

     String num12 = num1 + num2; 
     String num23 = num2 + num3; 
     String num123 = num1 + num2 + num3; 

     //Input: Ask user to guess 3 digit number 
     System.out.println("Please enter your three numbers (e.g. 123): "); 
     String userGuess = input.next(); 

     //Compare the user's guess to the lottery number and report results 
     if(userGuess.equals(num123)){ 
      System.out.println("Winner: " + num123); 
      System.out.println("Congratulations, both pairs matched!"); 
     }else if(userGuess.substring(0,2).equals(num12)){ 
      System.out.println("Winner: " + num123); 
      System.out.println("Congratulations, the front pair matched!"); 
     }else if(userGuess.substring(1,3).equals(num23)){ 
      System.out.println("Winner: " + num123); 
      System.out.println("Congratulations, the end pair matched!"); 
     }else{ 
      System.out.println("Winner: " + num123); 
      System.out.println("Sorry, no matches! You only had one chance out of 100 to win anyway."); 
     } 
    } 
} 
+0

添加一行來打印出字符串的長度,就在你做子串操作之前。 – 2014-08-31 18:49:28

回答

0

正如在其他答覆中提到,每次迭代你的循環時間,可以重置的lottoString價值只是一個數字。您需要追加它,就像這樣:

lottoString += Integer.toString(lotNums); 

你的另一個問題是你的substring方法的使用。如果兩個索引位置都相同,例如0,0,它將返回一個空字符串。你想要的是這樣的:

String num1 = lottoString.substring(0,1); 
String num2 = lottoString.substring(1,2); 
String num3 = lottoString.substring(2,3); 
+0

哦,謝謝!我認爲3是行不通的,因爲只有3位數,而且它們的計數很奇怪 – user2337438 2014-08-31 18:55:55

+0

@ user2337438是的,在官方文檔中它說:'子字符串從指定的beginIndex開始並延伸到索引endIndex - 1處的字符。 – 2014-08-31 18:56:56

0
for(int randomGen=0; randomGen < 3; randomGen++){ 
    int lotNums = (int)(Math.random()*10); 
    lottoString = Integer.toString(lotNums); 
} 

你assignining Integer.toString()來lottoString的結果。 lotNums是一個數字從0到9

我猜你想

lottoString += Integer.toString(lotNums);