2017-02-13 81 views
-2

我想写一个程序,要求用户输入一个字母(R,G,B),然后在五个输出结果后。连续不能有2个字母。当我输入第三个字母并且双字母检查不起作用时,我得到indexoutofbounds卡住了。索引超出界限。不知道为什么

package absolutejava; 

import java.util.Scanner; 
import java.util.*; 

public class RGB { 

    public static void main(String[] args) { 
     Scanner kb = new Scanner(System.in); 
     int count = 0; 
     boolean isColor = false; 
     String finalString = ""; 
     int i = 0; 
     int j = 1; 

     String temp = ""; 
     for (count = 0; count < 5;) { 
      System.out.println("Enter a color. Use R for red, G for green, and B for blue."); 
      temp = kb.nextLine(); 

      if ((temp.equals("R") || temp.equals("G") || temp.equals("B"))) { 
       isColor = true; 
       temp += temp; 

      } else { 
       isColor = false; 
       System.out.println("Invald Color, please choose again"); 
      } 

      if (isColor == true && j < 6 && i < 5) { 
       count++; 
       if (temp.length() > 2 && temp.length() <= 5 && finalString.substring(i, j).equals(temp.substring(i - 1, j - 1))) { 
        System.out.println("Two colors cannot be next to each other "); 
        isColor = false; 
        count--; 

       } else if (temp.length() == 5) { 
        finalString = finalString + temp.substring(i); 
        //debugging line 
        System.out.println("i " + i + "j " + j + "count " + count + " " + finalString + " length " + temp.length()); 
        i++; 
        j++; 
       } else { 
        finalString = finalString + temp.substring(i, j); 
        //debugging line 
        System.out.println("i " + i + "j " + j + "count " + count + " " + finalString + " length " + temp.length()); 
        i++; 
        j++; 
       } 
      } 
     } 

     System.out.println(finalString); 
    } 
} 
+0

为什么不使用变量来跟踪以前的颜色?如果输入的当前颜色等于先前的颜色,请让用户再次输入颜色。否则,继续进行。 –

回答

0

下面这行肯定是不对的:

temp += temp; 

你与当前输入每次迭代更换temp,所以这不会有任何效果。即使该不是的情况下,你只是将相同的字符串添加到自己 - 例如, “A”会变成“AA”。

我假设你的意思

finalString += temp; 

或诸如此类的话。

一般来说,好像你在几个地方混合了tempfinal

还有一件事:不明确地比较truefalse,这是没有必要的,通常被认为是不好的风格。