0

So I am just making a simple averaging program for fun, and I came across an error that I am interested in why it's happening. Here's the code:

import java.util.Scanner;

class Main
{
public static Scanner scan = new Scanner(System.in);
public static void main (String[] args)
{
    System.out.println("how many #s to average");
    int bob = 0;

    int loop = scan.nextInt();
    int counter = 0;
        while(counter<loop){
        counter++;
        int one = scan.nextInt();
        int two = scan.nextInt();
        bob = bob+one+two;
        if(loop==counter){
        System.out.println("The average is "+bob);
    }
    }

}
}

And I'm getting Java.util.NoSuchElementException at all the places with scan.nextInt(). What's happening?

ByteDuck
  • 1,631
  • 2
  • 12
  • 27
  • Are you entering ints when Scanner asks you for input? – Martin Dinov Jan 16 '14 at 19:52
  • 2
    possible duplicate of [NoSuchElementException with Java.Util.Scanner](http://stackoverflow.com/questions/13729294/nosuchelementexception-with-java-util-scanner) – Orel Eraki Jan 16 '14 at 19:54
  • @MartinDinov yes, I am. – ByteDuck Jan 16 '14 at 19:56
  • Sorry, withour how you enter inputs, I seem to not able to reproduce the error. I run your code and it worked fine. Btw, where is the line `scan.nextInt()` (first, second or third one)? – vutran Jan 16 '14 at 20:08
  • Your code works fine for me. What inputs do you enter to cause the program to fail? Also, why do you call `nextInt()` twice? Don't you only need to get one number for each loop? BTW, the way your code is written you will prompt the user for twice as many numbers as they need (i.e. enter "2" for how many numbers to average then prompts the user for 4 more inputs), and you're printing the sum not the average. – mdl Jan 16 '14 at 20:40

0 Answers0