Java string.nextLine()
所以我的代码有点问题。假设输出为: AAAA BCC1111111 xyz abbbc 我的代码将只读取第一行“AAAAA BCC1111111”,而不读取其余的。我一直试图搞乱for循环,但我似乎不知道该怎么办。任何帮助都将不胜感激Java string.nextLine(),java,Java,所以我的代码有点问题。假设输出为: AAAA BCC1111111 xyz abbbc 我的代码将只读取第一行“AAAAA BCC1111111”,而不读取其余的。我一直试图搞乱for循环,但我似乎不知道该怎么办。任何帮助都将不胜感激 public class Compress { public static void main(String[] args) { java.util.Scanner in = new java.util.Scanner(System.i
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;
}
}
公共类压缩{
公共静态void main(字符串[]args){
java.util.Scanner in=new java.util.Scanner(System.in);
字符串s=in.next();
in.nextLine();
字符串压缩字符串=压缩;
System.out.println(压缩字符串);
}
公共静态字符串压缩(字符串文本){
字符串=”;
整数计数=0;
char currentChar=text.charAt(0);
对于(int i=0;i=3){
if(字符.isDigit(currentChar)){
//如果字符是数字,则打印#c#n
字符串+=“#”+计数+“#”+当前字符;
}否则{
//否则它就是一封信,所以打印出来
字符串+=“#”+计数+当前字符;
}
}否则如果(计数=2){
字符串+=当前字符;
字符串+=当前字符;
}否则如果(计数=1){
字符串+=当前字符;
}
currentChar=text.charAt(i);
计数=1;
}
}
//如果计数大于3
如果(计数>=3){
//如果字符是数字,则打印#c#n
if(字符.isDigit(currentChar)){
字符串+=“#”+计数+“#”+当前字符;
}否则{
//否则它就是一封信,所以打印出来
字符串+=“#”+计数+当前字符;
}
}否则如果(计数=2){
字符串=字符串+当前字符;
字符串=字符串+当前字符;
}否则如果(计数=1){
字符串+=当前字符;
}
返回字符串;
}
}
以下是您的main
方法逐行执行的操作:
String s = in.next();
在中读取第一行并将其存储在s
in.nextLine();
读入第二行,不要将其存储在任何地方
String compressString = compress(s);
压缩第一行
System.out.println(compressString);
}
打印出压缩后的第一行
System.out.println(compressString);
}
没有读过第三行就结束了
希望这足以为你指明正确的方向。你读了两行,忽略了第二行。我不知道你期望什么。有什么建议吗?我将代码存储在第二行,但现在在线程“main”java.lang.StringIndexOutOfBoundsException中出现异常:字符串索引超出范围:0–errorhello,所以我存储了第二行和第三行并打印了它们……但现在出现了一个错误。线程“main”java.lang.StringIndexOutOfBoundsException中出现异常:字符串索引超出范围:0请使用所做的任何更改更新帖子中的代码。