As I’m extremely new to java, I seem to have trouble grasping some concepts. Here is a program. I understand the System.out part reasonably well but am having trouble getting my head around how the input works.
// IO Example:
import java.util.Scanner;
public class HelloAge {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("What's your name? ");
String name = in.nextLine();
System.out.print("In which year were you born? ");
Integer birthyear = in.nextInt();
Integer age = 2011 - birthyear;
System.out.println("Hello, " + name + "! Welcome to COMP1100.\n" +
"You will turn " + age + " this year.");
}
}
I can’t see why there is in.nextLine(); and then in.nextInt(); I don’t see what those two commands have in common or what they’re supposed to mean? That’s my main issue.
In general try the javadocs first; in this case the Scanner docs.
First create a new scanner for reading stdin…
Read in the entire next line which is all chars up to the next newline…
Read the next set of chars as an integer…