2

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?

Kishan Bheemajiyani
  • 3,057
  • 3
  • 26
  • 57

2 Answers2

2

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++) {
    //...
Mark Peters
  • 76,122
  • 14
  • 153
  • 186
  • 1
    Actually the OP is potentially calling `scanner.next()` *lots* of times - once before the loop, and then once *per iteration* of the loop. – Jon Skeet May 05 '15 at 13:59
  • okey just trying using single this one for (int i = 0; i < Integer.parseInt(scanner.next()); i++) { System.out.println("Count " + i); } still same result. – Kishan Bheemajiyani May 05 '15 at 14:02
  • @JonSkeet i think little i got it it will take number of numbers into the input isnt it if will give 15 it will take it as 1 right 0,1 isnt it ? – Kishan Bheemajiyani May 05 '15 at 14:05
  • @Krishna: I didn't follow that comment *at all* but I suggest you review how a `for` loop works - the whole condition is evaluated on each iteration, so when the condition includes `Integer.parseInt(scanner.next())` it will try to read another token on each iteration... – Jon Skeet May 05 '15 at 14:23
  • @JonSkeet okey jon so i got it it will try to find every time new input isnt it? so its giving 0 in out put. – Kishan Bheemajiyani May 05 '15 at 14:35
1

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);
        }
    }
Eran
  • 359,724
  • 45
  • 626
  • 694