我不太明白这个基本的java程序

发布于 2024-11-15 01:21:40 字数 765 浏览 2 评论 0原文

由于我对java非常陌生,我似乎很难掌握一些概念。这是一个程序。我对 System.out 部分理解得相当好,但我很难理解输入的工作原理。

// 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.");
    }
}

我不明白为什么有 in.nextLine(); 然后是 in.nextInt(); 我不明白这两个命令有什么共同点或什么他们应该是什么意思?这是我的主要问题。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

怀念你的温柔 2024-11-22 01:21:40

一般来说,首先尝试 javadocs;在本例中为扫描仪文档

首先创建一个新的扫描仪来读取标准输入...

Scanner in = new Scanner(System.in);

读入整个下一行,其中是直到下一个换行符

String name = in.nextLine();

的所有字符...将下一组字符读取为整数...

Integer birthyear = in.nextInt();

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();
一枫情书 2024-11-22 01:21:40

System.in 调用来自控制台的输入。然后扫描仪读取输入数据并将其转换为任何格式。 in.nextVar 是一个函数,它获取数据并读取一个“块”数据,并将其放入指定的格式。

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.

温暖的光 2024-11-22 01:21:40

您可以在扫描仪对象的本教程中找到答案。

You can may be find your answer in this tutorial on the scanner object.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文