r/learnjava • • Oct 11 '16

PracticeIt CS courses from Washington Uni - Timing out when using Scanner functionality

Has anyone taken the java courses through PracticeIt? It's been a lot of fun and can be challenging.. However, I've noticed when I'm solving a lesson that requires using a Scanner object, the answers always fail because of a "*** TIMEOUT (infinite loop?)" error. Consider the following problem:

Write code to read an integer from the user, then print that number multiplied by 2. You may assume that the user types a valid integer. A sample run of the code would produce the following:

Type an integer: 4 4 times 2 = 8

        Scanner scanner = new Scanner(System.in);
        int val = 0;

        System.out.print("Type an integer:");
        while (scanner.hasNext()){

            val = scanner.nextInt();
        }

        System.out.println(String.format("%s times 2 = %s", val, (val*2)));

I know that the code works as is but the site times out when it tries to compile/run. Am I not terminating it correctly perhaps? I can't exactly contact the admin since I'm not a student. Any help is appreciated, as I can't finish several exercises because of this.

0 Upvotes

2 comments sorted by

2

u/darksounds Oct 11 '16

Typically, when practice it gives an error, it's fairly accurate. In this case, your while loop is clearly causing a problem. Do you know why?

And it's the University of Washington.

1

u/wheezymustafa Oct 11 '16

I should've known better. The while was in an infinite loop and I never had a control to break out of it, so the scanner was infinitely waiting for me to respond. Thank you for pushing me toward an answer without giving it away!