简体   繁体   中英

Java - losing first user input using a while loop

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 QI 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?

Replace these 2 lines:

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

with

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM