简体   繁体   中英

Last iteration of for loop not outputting

Forgive me if this is not formatted properly, this is my first post. I looked to see if this issue has been found before and I cannot find anyone who has had the same problem I am having.

I am trying to learn Java and cannot for the life of me figure out why my for loops are not outputting the last iteration. I am going through codeabbey's exercises and completed the first two relatively easily. However on the third and fourth problems, I cant get my for loop to output during the last iteration.

I began looking on google and thought I would compare my answer to someone else's. I couldn't see why mine wouldn't work when my code was almost identical to the person I found. So I copied their code and to my surprise I had the same problem when this code also would not output on the last iteration.

So, here is the context.

The website gives you a single number first which is the number of sets of the following numbers. For the third problem, you are to add the sets of two, output the sum followed by a space and loop through the entire batch. For the fourth problem, it is similar where the first number is the number of sets in the batch but you are to compare the two numbers and output the lower number. I will copy my code here for the third problem because the code is simpler.

Here is the code:

import java.util.Scanner;

public class Summation {

    public static void main(String[] args) {

        Scanner in = new Scanner(System.in);
        int n = in.nextInt();

        for(int i = 0; i < n;i++){

            int a = in.nextInt();
            int b = in.nextInt();

            System.out.println(a + b + " ");
        }

    }

}

Here is the input you are to copy and paste:

3

100 8

15 245

1945 54

and this is my output:

108 260

So, as you can see we are missing the last output here. I tried changing the for loop to (i < (n+1) ) which still didn't change anything. Any help would be GREATLY appreciated!

Ok so I tested it, and with your numbers, typing them in one by one it works. Copy pasting them, press enter one more time at the end of the copy. If you don't press enter, the scanner thinks you're still adding to the second number so it won't continue until enter is pressed.

我会尝试使用其他人建议的println(),或在程序结尾处调用flush(),以确保某些内容未保存在缓冲区中且未被写入。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM