I don't exactly understand this basic java program [closed]
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...
Scanner in = new Scanner(System.in);
Read in the entire next line which is all chars up to the next newline...
String name = in.nextLine();
Read the next set of chars as an integer...
Integer birthyear = in.nextInt();
System.in calls input from the console. The Scanner then reads that input data and puts it into whatever format. The in.nextVar is the function that takes the data and reads one 'chunk' of data, and puts it into the specified format.
You can may be find your answer in this tutorial on the scanner object.
精彩评论