简体   繁体   中英

Stuck. Index out of bounds. Can't figure out why

I am trying to write a program that asks the user for a letter (R,G,B) and then after five output the result. There cannot be 2 letters in a row. I get indexoutofbounds when I enter the third letter and the double letter check does not work.

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);
    }
}

The following line is definitely wrong:

temp += temp;

You're replacing temp with the current input every iteration, so this will have no effect. Even if that wasn't the case, you'd just be adding the same string to itself - eg "A" would become "AA."

I assume you meant

finalString += temp;

or something to that effect.

In general, it seems like you're mixing up temp and final in a few places.

One more thing: don't explicitly compare to true and false , it's unnecessary and is generally considered poor style.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM