Kishan Bheemajiyani
Kishan Bheemajiyani

Reputation: 3439

For Loop Logic Iteration Why not behaving Same ?

I have tried to Increasing Number By one Like this

for (int i = 0; i < 10; i++) {
            System.out.println("Count " + i);

        }

this logic Works fine.

but when i try to make it As user input for the series its not giving same out put from 0

See this

Scanner scanner = new Scanner(System.in);
        // System.out.println(scanner.hasNextInt());
        if (scanner.hasNextInt()) {
            // System.out.println(scanner.nextInt());
            System.out.println(Integer.parseInt(scanner.next()));
            for (int i = 0; i < Integer.parseInt(scanner.next()); i++) {
                System.out.println("Count " + i);
            }
        }

its not giving out put by increasing element its giving if i input for example 12 Out Put:-

15
Count 0

Can any body can say why?

Upvotes: 2

Views: 70

Answers (2)

Eran
Eran

Reputation: 393841

Each call to scanner.next() reads a new token, which you parse to int.

You have to store the first input and reuse it :

    Scanner scanner = new Scanner(System.in);
    // System.out.println(scanner.hasNextInt());
    if (scanner.hasNextInt()) {
        int len = Integer.parseInt(scanner.next());
        System.out.println(len);
        for (int i = 0; i < len; i++) {
            System.out.println("Count " + i);
        }
    }

Upvotes: 1

Mark Peters
Mark Peters

Reputation: 81074

You're calling scanner.next() twice. The first time all you do is print it out, and then discard it.

Try putting it in a variable instead:

//this could use scanner.nextInt() instead
int limit = Integer.parseInt(scanner.next()); 
System.out.println(limit);
for (int i = 0; i < limit; i++) {
    //...

Upvotes: 2

Related Questions