我是新来的Java和一般编程...我有一个问题实现运行长度编码程序,其中从用户输入的字符串。 (例如:KKKKKKKKKKKKKBCCDDDDDDDDDDDDDDDKKKKKMNUUUGGGGG)
将基于标记字符进行编码它们的输入使特定字符串应该是这样的:?$K13BCC$D15$K5MNUUU$G5
游程长度编码程序问题
有人能帮助我弄清楚什么是错的我不断收到这是我的输出:$K13BCC$D14$K4MNUUU
看来我的程序跳过最后一个字母,并在其中一些少了一个。任何帮助,将不胜感激!
我为乱码表示歉意。我知道这是不是很大,只是想弄清楚什么是错的这里...
import java.util.Scanner;
public class RunLengthEncoding {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter input string: ");
String inputString = input.next();
System.out.print("Enter flag character: ");
String flagCharacter = input.next();
Boolean validInput = false;
for (int i = 0; i < inputString.length(); i++) {
if (Character.isUpperCase(inputString.charAt(i))) {
validInput = true;
} else {
System.out.print("Bad input.");
}
}
char repeatedLetter = inputString.charAt(0);
if (validInput) { // if the input is valid, continue
int counter = 0; // set counter equal to 0
for (int i = 0; i < inputString.length(); i++) { // iterate through the input string
if (repeatedLetter == (inputString.charAt(i))) { // if the current letter is equal to the next
counter++; // increment the counter
repeatedLetter = inputString.charAt(i); // set the repeated letter to the next letter
} else { // if the current letter is not equal to the next letter
if (counter > 3) { // and if the counter is greater than 3
System.out.print(flagCharacter + repeatedLetter + counter); // print the encoded string
} else { // if the counter is not greater than 3
for (int j = counter; j >= 0; j--) { // for every number in counter
System.out.print(repeatedLetter); // print the current repeated letter for as many times as it appears
}
}
repeatedLetter = inputString.charAt(i); // set the new repeated letter
counter = 0; // reset counter to 0
}
}
}
}
}
请不要滥用你的帖子...这不利于学习任何东西。 – px06