简体   繁体   English

如何使用Scanner.nextLine()

[英]How to use Scanner.nextLine()

I use this code to input something in the String variable n, after I type what is asked, I don't want the program to print what I typed. 我使用这段代码在String变量n中输入一些东西,在我输入要求的内容之后,我不希望程序打印出我输入的内容。

The code: 编码:

String n= Scanner.nextLine(); String n = Scanner.nextLine();

I feel is something you type after Scanner. 我觉得你是在Scanner之后输入的东西。 , but I don't know what is it. ,但我不知道它是什么。

EDITED: Thanks for answer, but I don't know how to Close the Scanner. 编辑:谢谢你的回答,但我不知道如何关闭扫描仪。 Here is the program...: 这是程序......:

My program: 我的节目:

import java.util.Scanner;
public class A{
    public static void main(String args[]){
        String n;
        Scanner bananas=new Scanner(System.in); 
        System.out.println("First Digit: ");
        n=bananas.nextLine();
    }
}

When I run the program, on the screen appears: "First Digit:", then type, let's say I type "apple", the String n will be equals to "apple", it's ok, that is what I want, what I don't like is that the program prints on the screen the String n, I didn't want the program to do that, this is what happens: 当我运行程序时,在屏幕上显示:“First Digit:”,然后键入,假设我键入“apple”,String n将等于“apple”,没关系,这就是我想要的,我是什么不喜欢的是程序在屏幕上打印字符串n,我不希望程序这样做,这就是发生的事情:

First Digit: apples 第一个数字:苹果

What I want I the program to print is just: "First Digit: ", without showing what I typed, just keep it. 我想要的是我打印的程序只是:“First Digit:”,没有显示我输入的内容,只需保留它。

Thanks. 谢谢。

First, you have to instantiate the Scanner, like so: 首先,您必须实例化Scanner,如下所示:

Scanner scanner = new Scanner(System.in);  //if you want to read from the console

Then, you can receive your input. 然后,您可以收到您的输入。

String n = scanner.nextLine();

Make sure you close your scanner when you don't need it anymore: 确保在不再需要时关闭扫描仪:

scanner.close();

There is nothing tricky about it. 这没有什么棘手的。 You can do it like below and still your variable will hold your desired value. 你可以像下面这样做,你的变量仍然可以保持你想要的值。

import java.util.Scanner;
public class A{
    public static void main(String args[]){
        String n;
        Scanner bananas=new Scanner(System.in); 
        System.out.println("First Digit: ");
        n=bananas.nextLine();        // once you are done with input
        bananas.close();
    }
}

Even if you don't close scanner it won't make any difference as far as your code execution is concerned. 即使您不关闭扫描程序,就代码执行而言也不会有任何区别。 Only a warning some where in your class will arise which doesn;t really affect your code. 只会警告你班级中某些地方会出现哪些不会影响你的代码。 But still it is better to close the scanner once you are done with it. 但是一旦完成扫描,最好关闭扫描仪。 Its a good practice. 这是一个很好的做法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM