get input

If you want input for your program in Java, the first thing you have to think of is the Scanner class. Summarized, it is just a command we can use to “scan” the input we get from:

For more information about the Scanner class check: What is the scanner class?

This is stage one of processing the input: java programming read input

the first thing you have to do is to import the scanner class. The reason to import is that the scanner class already exists, but to use it, we first have to import the class:

import java.util.Scanner;

The second step is to create an object, or also called a scanner object. It is important that you know where you place the scanner object. For instance, if you place it in a method you can only use it in that particular method.

 

package P;

import java.util.Scanner;

public class C {
	
	C() {
	}
	
	void start() {
		Scanner in = new Scanner("hi");
	}
	
	public static void main(String[] args) {
		new C().start();

	}

}
  • scanner in constructor
package P;

import java.util.Scanner;

public class C {
	
	Scanner in;
	
	C() {
		in = new Scanner("hi");
	}
	
	void start() {
	}
	
	public static void main(String[] args) {
		new C().start();

	}

}

In these two examples, we (the programmer) filled in the input. If you want to know how to ask input from a user or from a file, check the following links: