简体   繁体   中英

Output of basic Java not printing. Can't figure out why

I'm a freshman at uni and we have to make an assignment where we have to find the second smallest number in a line of integers. Now I THINK I got it but I can't get the result to print. Can anyone figure out why this is?

package SecondSmallest;

import java.util.Scanner;
import java.io.PrintStream;


public class SecondSmallest {

    public static void secondSmallestLoop() {

        Scanner in = new Scanner(System.in);
        PrintStream out = new PrintStream(System.out);

        out.printf("Please enter a series of at least 2 integers: ");

        int smallest = in.nextInt();
        int secondSmallest = in.nextInt();

        while (in.hasNextInt()) {

            int next = in.nextInt();

            if (next < smallest) {
                secondSmallest = smallest;
                smallest = next;
            }

            else if (next < secondSmallest) {
                secondSmallest = next;
            }

        }

        out.print("The second smallest number is: " + secondSmallest);              
    }

    public static void main(String[] args) {
        SecondSmallest.secondSmallestLoop();
    }
}

In my opinion, it is better to have a condition to stop your scanner. So I would suggest to use a do-while instead. You also should use System.out.println, because it's ready to print in your console. You don't have to instantiate a PrintStream everytime. And by the way, your code is working, but it would be interesting to consider the thoughts we gave to you.

Your problem is not defined stop point for the while loop.

in.hasNextInt() mean: If you input an integer, it will be continue. To stop it, you can input a character that isn't an integer.

Hope to helpful

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