Q:

Java if statement terminated error

I tried to create basic number find game (1-100).
But always the program terminated after second try.
Code:
Random rnd = new Random();
int rndm  = rnd.nextInt(100);

int tryn;
Scanner sc = new Scanner(System.in);
System.out.print("Guess: ");
tryn = sc.nextInt();

if (tryn == rndm) {
        System.out.println("You win.");
        sc.close();
    }
    else if (tryn > rndm) {
        System.out.println("Too high.");
        System.out.print("Guess again: ");
        tryn = sc.nextInt();
    }
    else {
        System.out.println("Too low.");
        System.out.print("Guess again: ");
        tryn = sc.nextInt();    
    }

When I run output like:
<terminated> test2 [Java Application]...
Guess: 30
Too low.
Guess again: 50

Why my program doesn't loop? Thanks for any help.

A:

Please see the following code (I have tested it):
import java.util.Random;
import java.util.Scanner;

public class Guess {

    public static void main(String[] args) {
        Random rnd = new Random();
        int rndm = rnd.nextInt(100);

        int tryn;
        Scanner sc = new Scanner(System.in);
        System.out.print("Guess: ");

        while (sc.hasNextInt()) {
            tryn = sc.nextInt();

            if (tryn == rndm) {
                System.out.println("You win.");
                break;
            } else if (tryn > rndm) {
                System.out.println("Too high.");
                System.out.print("Guess again: ");
            } else {
                System.out.println("Too low.");
                System.out.print("Guess again: ");
            }
        }

        sc.close();
    }
}

