Reputation: 5
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.
The code:
String n= Scanner.nextLine();
I feel is something you type after 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: apples
What I want I the program to print is just: "First Digit: ", without showing what I typed, just keep it.
Thanks.
Upvotes: 0
Views: 475
Reputation: 238
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.
Upvotes: 1
Reputation: 4541
First, you have to instantiate the Scanner, like so:
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();
Upvotes: 1