PilotoLoco
PilotoLoco

Reputation: 13

show only the final iteration from a loop

I have been checking StackOverflow for a while and now it was finally time for me to register. I couldn't find my question on the site, so I thought I will ask it myself. I have copied my code down below. I am doing this for a school assignment. It does everything it is supposed to ( find the second smallest number) but, the output is not what i want it to be. I have tried placing the out.printf statement somewhere else but it just doesn't work. What happens first is that the first 2 numbers are automatically assigned to smallestNumber and secondSmallestNumber, the assignment says that the first number entered should always be smaller than the second. After that it goes to the loop and compares all numbers. And finally it should print out the final secondSmallestNumber. But it just prints all. I have tried several things and i can't get this right. Help me out please?

EDIT : teaching assistant told me I can't submit my assignments online in the event of fraud. So I'm sorry have to delete this code.

Upvotes: 0

Views: 283

Answers (3)

PKey
PKey

Reputation: 3841

As mentioned by others - you should move the printing outside the loop. Also at the end you shout flush your printstream. So try this:

    package module2;

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

    public class SecondSmallest {

        PrintStream out;

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

        void start() {
            Scanner in = new Scanner(System.in);
            out.printf("%s", "Enter multiple numbers divided by a space and close with Enter: ");
            int newNumber;
            int smallestNumber = in.nextInt();
            int secondSmallestNumber = in.nextInt();

            while (in.hasNext()) {
                newNumber = in.nextInt();

                if (newNumber < smallestNumber) {
                    secondSmallestNumber = smallestNumber; 
                    smallestNumber = newNumber;

                } 
            }
        //moved here to print only once 
           out.printf("%s%d\n", "The second smallest number is : ", secondSmallestNumber);
        //flush output stream 
           out.flush();
        }   


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

Upvotes: 1

Sakalya
Sakalya

Reputation: 578

Move out.printf("%s%d\n", "The second smallest number is : ", secondSmallestNumber); outside of the while loop.

Upvotes: 1

Scott Hunter
Scott Hunter

Reputation: 49803

To do something repeatedly, you put it inside of a loop. Thus, to not do it repeatedly, put it outside of the loop.

Upvotes: 2

Related Questions