Ben den Drijver
Ben den Drijver

Reputation: 9

Java Program does nothing with input (

For my programming-course assignment I have this program that needs to take a random number of positive integers and then select the second smallest one. I believe that everthing is coded properly, but when I execute the program and enter the integers, the program skips to the next line and does nothing. Am I maybe overlooking a rookie mistake?

This is the code:

package SecondSmallest;

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

public class SecondSmallest {

//Name:         Ben den Drijver
//Assignment:   SecondSmallest
//Date: 10      september 2014

PrintStream out;

SecondSmallest(){
    out = new PrintStream(System.out);
}

void start(){
    Scanner in = new Scanner(System.in);

    out.printf("Enter a series of integers: ");
    int smallest = in.nextInt(),
        secondSmallest = in.nextInt();

    while (in.hasNext()){               
        int n = in.nextInt();

        if (n < smallest){
            secondSmallest = smallest;
            smallest = n;
        } else 
            if (n < secondSmallest && n > smallest){
                secondSmallest = n;
            }           
    }
    out.printf("The second smallest number is: %d", secondSmallest);
}
public static void main (String[] argv) {
    new SecondSmallest().start();
}
}

If someone could give me a small hint or something, that would be great. Thanks!

Upvotes: 0

Views: 448

Answers (1)

I think you would want to use a delimiter using space or enter. And you probably also want to scan only numbers and detect a non-numeric character as a stopper.

You can try something like this:

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

public class SecondSmallest {

//Name:         Ben den Drijver
//Assignment:   SecondSmallest
//Date: 10      september 2014
    PrintStream out;

    SecondSmallest() {
        out = new PrintStream(System.out);
    }

    void start() {
        Scanner in = new Scanner(System.in);
        in.useDelimiter("[ \n]"); // --> your delimiter

        out.printf("Enter a series of integers: ");
        int smallest = in.nextInt();
        int secondSmallest = in.nextInt();

        while (in.hasNext("[0-9]*")) { //--> scan only numeric values for your "SecondSmallest" process
            int n = in.nextInt();

            if (n < smallest) {
                secondSmallest = smallest;
                smallest = n;
            } else if (n < secondSmallest && n > smallest) {
                secondSmallest = n;
            }
        }
        in.close();
        out.printf("The second smallest number is: %d", secondSmallest);
    }

    public static void main(String[] argv) {
        new SecondSmallest().start();
    }
}

And one more thing is you shall handle the exception case where user only input one integer. Apart from that, your code works fine.

Upvotes: 1

Related Questions