开发者

I don't exactly understand this basic java program [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably a开发者_开发技巧nswered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 11 years ago.

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜