Question

I'm trying to write a program where it asks the user to enter integers and to keep entering them until the user enters a Q. After every input, the program should prompt with the string: "Enter an integer, or Q to quit: ".

On my terminal, every second out.print only prompts the user for input and not the string to ask for the input. For example, output would look like this:

Enter an integer, or Q to quit: 90
80
Enter an integer, or Q to quit: 100
Enter an integer, or Q to quit: 25
Enter an integer, or Q to quit: 7
Enter an integer, or Q to quit: Q

My code is as follows...

    Scanner in = new Scanner(System.in);

    System.out.print("Enter an integer, or Q to quit: ");

    int largest = in.nextInt();

    if (in.hasNextInt())
    {

        while (in.hasNextInt())
            {


                int input = in.nextInt();
                if(input > largest)
                {
                    largest = input;
                }

                System.out.print("Enter an integer, or Q to quit: ");

            }
    }


    System.out.println(largest);

My first guesses were the ordering of certain statements, but I haven't had any luck. Any suggestions?

Was it helpful?

Solution

The problem is that you are waiting for two numbers... change it to as follows:

        Scanner in = new Scanner(System.in);

        System.out.print("Enter an integer, or Q to quit: ");
        int largest = Integer.MIN_VALUE;

        while (in.hasNextInt())
        {           
            int input = in.nextInt();
            if (input > largest)
            {
                largest = input;
            }

            System.out.print("Enter an integer, or Q to quit: ");

        }

        System.out.println(largest);

The problem with your previous version of the code was that you were expected 2 numbers initially, one of them being the largest value.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top