本文介绍了Scanner输入=新的Scanner(System.in)究竟是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Scanner input = new Scanner(System.in);

您能否详细解释上面的代码是如何逐步完成的?我真的不明白它是如何工作的以及它如何链接到我以后能够做这个声明:

Could you give me a detailed explanation on what the code above is doing step by step? I don't really understand how it works and how it links to me later being able to do this statement:

int i = input.nextInt()


推荐答案

好的,让我们详细说一下关于 class。

Alright, let's elaborate with some simplified explanation about the Scanner class.

这是一个标准的Oracle类,您可以通过调用 import java.util来使用它。扫描仪

It is a standard Oracle class which you can use by calling the import java.util.Scanner.

所以让我们做一个类的基本例子:

So let's make a basic example of the class:

class Scanner{
   InputStream source;

   Scanner(InputStream src){
       this.source = src;
   }

   int nextInt(){
       int nextInteger;
       //Scans the next token of the input as an int from the source.
       return nextInteger;
   }
}

现在拨打扫描仪input = new Scanner(System.in); 你创建了 Scanner 类的新对象(所以你创建了一个新的Scanner)和您将其存储在变量输入中。同时你正在调用(所谓的),参数 System.in 。这意味着它将从程序的标准输入流中读取。

Now when you call Scanner input = new Scanner(System.in); you make a new object of the Scanner class (so you make a new "Scanner") and you store it in the variable input. At the same time you are calling the (so called) constructor of the class, with the parameter System.in. That means it is going to read from the standard input stream of the program.

现在当你调用 input.nextInt(); 你从你刚创建的对象执行方法(也是)。但是正如我们所看到的,这个方法返回一个整数,所以如果我们想要使用那个整数,我们必须像你一样将调用分配给变量:

Now when you are calling input.nextInt(); you execute the method from the object you just created (also documented). But as we see, this method returns a integer, so if we want to use that integer, we have to assign the call to a variable like you do:

int i = input.nextInt();

这篇关于Scanner输入=新的Scanner(System.in)究竟是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 19:37