Print largest two integers from a stream I'm writing a program for my intro to comp sci course where I'm supposed to prompt the user to enter a stream of integers, and then return the largest two. We were given the hint to use a scanner and a while loop with the condition .hasnext.

Please review my code:

package Homework;

import java.util.*;

public class Question1 {

public static void main(String[] args) {
    System.out.println("Please type your integers");
    Scanner kbd = new Scanner(System.in);
    int big = 0;
    int big2 = 0;
    while(kbd.hasNext())
    { 
       int num = kbd.nextInt();
       if(num &gt; big) { // opens If statement
          big2 = big;
          big = num;
        } else if((num &lt; big) &amp;&amp; (num &gt; big2))  {
           big2 = num;
        } 
    } 
    System.out.print(big);
    System.out.print(big2);
 } 
}
Your logic is actually correct.  Perhaps you just don't know what to type in your terminal window to terminate the input stream.  After typing in your numbers, you need to send an end-of-file ("EOF") character.  On Unix, you do that by hitting ControlD.  On Windows, it's ControlZ.

Note that System.in is the program's "standard input" stream, which doesn't have to come straight from the keyboard.  You can also do

echo 3 1 4 1 5 9 | java Homework.Question1


or

java Homework.Question1 &lt; numbers.txt


Therefore, kbd is a misnomer.  Try naming your Scanner more generically, like scanner or input.

You don't want to print your two numbers with no space in between.  It will look like one long number!

The placement of your braces is inconsistent, with the ones for the main function and the else if being closest to conventions.  The brace opening the while loop should be on the same line as the while keyword.  The brace closing the if block should be pulled further left, aligned with the if keyword, and else can come immediately after.

public class Question1 {
    public static void main(String[] args) {
        ...
        while (...) {
            ...
            if (...) {
                ...
            } else if (...) {
                ...
            }
        }
        System.out.println(...);
        System.out.println(...);
    }
}


You have interpreted the exercise such that duplicate entries in the input are ignored.  That's the easier way.  If the exercise requires you to print the same number twice when there is a tie for the maximum, then the program is trickier to implement.