0

Good morning all,

I am currently learning coding / Java. The task I need to do is; make a program that takes user input and returns the highest and lowest entry. I have to use a while loop to keep it simple. At the moment I got this:

    System.out.println("Enter numbers, Q to finish: ");
    int largest = sc.nextInt();
    int smallest = sc.nextInt();

    while (sc.hasNextInt()) {
        int number = sc.nextInt();

        if(number > largest) {
            largest = number;
        }
        else if(number < smallest){
            smallest = number;
        }
    }
    System.out.printf("Largest: %d  Smallest: %d", largest, smallest);

The problem is that it skips the first user entry. After some testing I saw that when I only enter 1 number and press Q I get a error. If I enter; 10 - 20 - 30, the return is; Largest: 30 Smallest: 20.

Anyone has a idea why it skips the first user entry?

0

1 Answer 1

2

Replace these 2 lines:

int largest = sc.nextInt();
int smallest = sc.nextInt();

with

int largest = sc.nextInt();
int smallest = largest;
Sign up to request clarification or add additional context in comments.

3 Comments

Works like a charm, thanks a lot for the very quick and easy solution!
How can I do that?
On a question posted by you in StackOverflow, if any of the answer satisfies you and solves your problem, you can accept it by clicking the tick mark on the left of the answer

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.