Getting Input in Java

Creating Scanner objects

The easiest way to get input is to create an instance of the scanner class.

Using Scanner objects

Once you have a scanner object scanner, you can ask for: or many other possibilities; see the Scanner documentation for details.

Putting it All Together

The following code prompts for a file name. It expects this text file to begin with a number N, followed by N other numbers (on separate lines or separated by whitespace).
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;

class change
{
  public static void main( String[] args )
  {
    // get keyboard input Object
    Scanner kbd = new Scanner(System.in);
    // get input from keyboard
    System.out.print( "Enter a filename: " );
    String filename = kbd.nextLine();
    // trim off any whitespace (optional)
    filename = filename.trim();
    System.out.println("Now trying to open " + filename);
    
    // get file input Object via the file:
    Scanner file = null;
    try { // in case the file's not there
      file = new Scanner(new File(filename));
    } catch (FileNotFoundException e) {
      System.out.println("File " + filename + " not found.");
      System.out.println( e );
    }
    // get integer at the start of the file:
    int num_coins = file.nextInt();
    System.out.println("Read the # of coins = " + num_coins);
    
    // create an array, coins, to hold the coins:
    int[] coins = new int[num_coins];
    
    // here, you'll need to loop in order to read each coin in...
    
    // It's useful for debugging to be able to print an array 
    System.out.println("The array, coins, is " + Arrays.toString( coins ));
    
    // It's also useful to be able to get more input from the keyboard:
    System.out.println("Input an integer and I'll add 1: ");
    int amt = kbd.nextInt(); // it will crash if it's not an int!
    System.out.println("You entered " + amt + ", one less than " + (amt+1));
  }
}