java scanner和for_java - For循环会导致Scanner读取另一行 - 堆栈内存溢出

我正在尝试做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();

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值