[英]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.我正在尝试编写一个程序,要求用户输入一个字母(R、G、B),然后在五个输出结果之后。 There cannot be 2 letters in a row.
一行不能有 2 个字母。 I get
indexoutofbounds
when I enter the third letter and the double letter check does not work.当我输入第三个字母时,我得到
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);
}
}
The following line is definitely wrong:下面这行肯定是错误的:
temp += temp;
You're replacing temp
with the current input every iteration, so this will have no effect.您每次迭代都用当前输入替换
temp
,因此这将不起作用。 Even if that wasn't the case, you'd just be adding the same string to itself - eg "A" would become "AA."即使情况并非如此,您也只需将相同的字符串添加到其自身即可——例如,“A”将变为“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.一般来说,您似乎在一些地方混淆了
temp
和final
。
One more thing: don't explicitly compare to true
and false
, it's unnecessary and is generally considered poor style.还有一件事:不要明确地与
true
和false
进行比较,这是不必要的,通常被认为是糟糕的风格。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.