我正在尝试做CCC 2019的J3问题,并且我的代码大部分都可以工作,除了我的for循环导致Scanner在读取最后一行之前读取额外的一行这一事实之外。
预期输入:
4
+++===!!!!
777777......TTTTTTTTTTTT
(AABBC)
3.1415555
预期产量:
3 + 3 = 4 !
6 7 6 . 12 T
1 ( 2 A 2 B 1 C 1 )
1 3 1 . 1 1 1 4 1 1 4 5
我的输出:
3 + 3 = 4 !
6 7 6 . 12 T
1 ( 2 A 2 B 1 C 1 )
"Scanner waits for another line here"
"If I press enter, it then spits out the last line."
1 3 1 . 1 1 1 4 1 1 4 5
我似乎找不到问题,并且尝试将for循环放入方法中,然后为每个输入接受Scanner的四个不同输入(str0,str1等),它仍然读取另一行。 我在sc.nextInt()之后添加了sc.nextLine()以确保Scanner读取输入的下一行以及int旁边的空格。 我尝试省略输入的最后一行,但随后它仅读取最后一行之前的另一行。 因此,似乎此问题仅限于最后一行而不是特定输入。
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int counter = 1;
int n = sc.nextInt();
sc.nextLine();
for (int i = 0; i < n; i++){
String str = sc.nextLine();
for (int j = 0; j < str.length(); j++){
if (j != str.length() - 1 && str.charAt(j) == str.charAt(j+1)){
counter++;
}else{
System.out.print(counter + " " + str.charAt(j) + " ");
counter = 1;
}
}
System.out.println();
}
}