所以我的代码有点问题。假设输出是:
aaaaabcc1111111111
xyz
abbbc
我的代码将仅读取第一行“ aaaaabcc1111111111”,而不读取其余行。我一直在尝试弄乱for循环,但是我似乎无法将精力放在做什么上。任何帮助将不胜感激!
public class Compress {
public static void main(String[] args) {
java.util.Scanner in = new java.util.Scanner(System.in);
String s = in.next();
in.nextLine();
String compressString = compress(s);
System.out.println(compressString);
}
public static String compress (String text){
String string = "";
int count = 0;
char currentChar = text.charAt(0);
for(int i=0; i<text.length(); i++){
if (currentChar == text.charAt(i)) {
currentChar = text.charAt(i);
count++;
} else {
if (count >= 3) {
if (Character.isDigit(currentChar)) {
//if character is a digit, print #c#n
string += "#" + count + "#" + currentChar;
} else {
//else it is then a letter, so print #cn
string += "#" + count + currentChar;
}
} else if (count == 2) {
string += currentChar;
string += currentChar;
} else if (count == 1) {
string += currentChar;
}
currentChar = text.charAt(i);
count = 1;
}
}
//if count is greater than 3
if (count >= 3) {
//if character is a digit, print #c#n
if (Character.isDigit(currentChar)) {
string += "#" + count + "#" + currentChar;
} else {
//else it IS then a letter, so print #cn
string += "#" + count + currentChar;
}
} else if (count == 2) {
string = string + currentChar;
string = string + currentChar;
} else if (count == 1) {
string += currentChar;
}
return string;
}
}
答案 0 :(得分:0)
这是您的main
方法正在做的事情,逐行:
String s = in.next();
读取第一行并将其存储在s
in.nextLine();
读取第二行,不要将其存储在任何地方
String compressString = compress(s);
压缩第一行
System.out.println(compressString);
打印出压缩的第一行
}
无需阅读第三行即可结束。
希望这足以将您指向正确的方向。