2017-06-15 100 views
-2

我試圖用EXACT相同的格式循環練習,它不會導致像這樣的錯誤消息。和內環路(含int i)以完美工作之前,我公司推出的外環(與詮釋j)的:在Java中,我嵌套循環,但它給了我一個錯誤消息

private static void mBTI(){ 
    Scanner console = new Scanner(System.in); 
    Random rand = new Random(); 

    //Practice loop 
    int wtf = console.nextInt(); 
    for (int k = 1; k <= wtf; k++){ 
     for (int m = 1; m <= 2; m++){ 
      System.out.println("derp"); 
     } 
    }   

    //Error loop 
    System.out.println("How many results do you want? (Type a numerical value.)"); 
    int amount = console.nextInt(); 
    String[] types = {"E","I","N","S","F","T","J","P"}; 
    int loop = 0; 
    for(int j = 1; j <= amount; j++){ 
     for(int i = 1; i <= 4; i++){ 
      int randType = rand.nextInt(2); 
      randType = loop+randType; 
      System.out.print(types[randType]); 
      loop = loop+2; 
     } 
     System.out.println(""); 
    } 
} 
+5

那麼......錯誤信息是什麼?它引用了哪條線?我們目前無法閱讀您的想法。 –

+2

我認爲'System.out.print(types [randType])失敗'''數組索引越界異常'' – degr

+0

它給我的基本錯誤信息是:java.lang.ArrayIndexOutOfBoundsException:9 – Ray25Lee

回答

-1

你可能剛開的索引越界異常。請確保使用randType = randType%types.length(或其他方法將randType保留在邊界內)。

相關問題