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.
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();
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.
Related
Hey there I got into some trouble with my java Code.
I try to code a bit around with java for a few hours and I dont know much thats why im asking. I learn best by trying but I get into so many problems.
So: I want the scanner to scan the next Statement and if its "ja" it should do the if thing etc.
The problem is, when i try to compile it it has an error with the = s.nextInt thing. In the console it says: "cannot find symbole". I tried so many things I dont know what to do. Allready tried so much.
import java.util.Scanner;
public class Brotcrunsher {
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
System.out.println ("Hallo");
System.out.println ("A flag has more then 1 color right?");
String a = s.NextInt();
if (a.equals("ja")) {
System.out.println ("You arent dumb, nice.");
} // end of if
else {
System.out.println ("You arentn a genie");
} // end of if-else
}
}
thanks in advance.
EDIT: Problem solved. Thank you for every awnser. I try my best to Tag my posts better and to format my code better
Here:
String a = s.NextInt();
You want a to be String (which makes sense, as you want to compare it against other Strings later on); so you better use:
String a = s.nextLine();
instead!
The other method a) does not exist and b) nextInt() ... returns a number, not a string
I can see two errors, firstly you are taking a string input from the command line user so your scanner must be "scanner.nextLine()" which takes a string, as it stands you are expecting an integer value.
Second your "s.scanner" is not calling anything, you have declared your scanner with the name "scan", so you need to change that to "scan".
import java.util.Scanner;
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("A flag has more than one colour?");
String input = scan.nextLine();
if (input.equals("yes")) {
System.out.println("well done");
} else {
System.out.println("wrong answer");
}
}
Try:
import java.util.Scanner;
public class Brotcrunsher {
public static void main(String args[]){
Scanner scan = new Scanner(System.in);
System.out.println ("Hallo");
System.out.println ("A flag has more then 1 color right?");
String a = scan.nextLine();
if (a.equals("ja")) {
System.out.println ("You arent dumb, nice.");
} // end of if
else {
System.out.println ("You arentn a genie");
} // end of if-else
}
}
You have got a compilation error that should be
String a = scan.next();
Since scan is your scanner object where you are using String a = s.NextInt(); which is not at all an object of scanner.
Two issues, one is a is a String not an int and the second is Scanner.nextLine() (or nextInt() or next()). And, the local reference is scan (not s). Like,
String a = scan.nextLine();
You can use like this.
import java.util.Scanner;
class ScannerTest{
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
System.out.println("Enter your rollno");
int rollno=sc.nextInt();
System.out.println("Enter your name");
String name=sc.next();
System.out.println("Enter your fee");
double fee=sc.nextDouble();
System.out.println("Rollno:"+rollno+" name:"+name+" fee:"+fee);
sc.close();
}
}
refrence: http://www.javatpoint.com/Scanner-class
I ran into an issue. Below is my code, which asks user for input and prints out what the user inputs one word at a time.
The problem is that the program never ends, and from my limited understanding, it seem to get stuck inside the while loop. Could anyone help me a little?
import java.util.Scanner;
public class Test{
public static void main(String args[]){
System.out.print("Enter your sentence: ");
Scanner sc = new Scanner (System.in);
while (sc.hasNext() == true ) {
String s1 = sc.next();
System.out.println(s1);
}
System.out.println("The loop has been ended"); // This somehow never get printed.
}
}
You keep on getting new a new string and continue the loop if it's not empty. Simply insert a control in the loop for an exit string.
while(!s1.equals("exit") && sc.hasNext()) {
// operate
}
If you want to declare the string inside the loop and not to do the operations in the loop body if the string is "exit":
while(sc.hasNext()) {
String s1 = sc.next();
if(s1.equals("exit")) {
break;
}
//operate
}
The Scanner will continue to read until it finds an "end of file" condition.
As you're reading from stdin, that'll either be when you send an EOF character (usually ^d on Unix), or at the end of the file if you use < style redirection.
When you use scanner, as mentioned by Alnitak, you only get 'false' for hasNext() when you have a EOF character, basically... You cannot easily send and EOF character using the keyboard, therefore in situations like this, it's common to have a special character or word which you can send to stop execution, for example:
String s1 = sc.next();
if (s1.equals("exit")) {
break;
}
Break will get you out of the loop.
Your condition is right (though you should drop the == true). What is happening is that the scanner will keep going until it reaches the end of the input. Try Ctrl+D, or pipe the input from a file (java myclass < input.txt).
it doesn't work because you have not programmed a fail-safe into the code. java sees that the scanner can still collect input while there is input to be collected and if possible, while that is true, it keeps doing so. having a scanner test to see if a certain word, like EXIT for example, is fine, but you could also have it loop a certain number of times, like ten or so. but the most efficient approach is to ask the user of your program how many strings they wish to enter, and while the number of strings they enter is less than the number they put in, the program shall execute. an added option could be if they type EXIT, when they see they need less spaces than they put in and don't want to fill the next cells up with nothing but whitespace. and you could have the program ask if they want to enter more input, in case they realize they need to enter more data into the computer.
the program would be quite simplistic to make, as well because there are a plethera of ways you could do it. feel free to ask me for these ways, i'm running out of room though. XD
If you don't want to use an EOF character for this, you can use StringTokenizer :
import java.util.*;
public class Test{
public static void main(){
Scanner sc = new Scanner (System.in);
System.out.print("Enter your sentence: ");
String s=sc.nextLine();
StringTokenizer st=new StringTokenizer(s," ");//" " is the delimiter here.
while (st.hasMoreTokens() ) {
String s1 = st.nextToken();
System.out.println(s1);
}
System.out.println("The loop has been ended");
}
}
I had the same problem and I solved it by reading the full line from the console with one scanner object, and then parsing the resulting string using a second scanner object.
Scanner console = new Scanner(System.in);
System.out.println("Enter input here:");
String inputLine = console.nextLine();
Scanner input = new Scanner(inputLine);
List<String> arg = new ArrayList<>();
while (input.hasNext()) {
arg.add(input.next().toLowerCase());
}
You can simply use one of the system dependent end-of-file indicators ( d for Unix/Linux/Ubuntu, z for windows) to make the while statement false. This should get you out of the loop nicely. :)
Modify the while loop as below. Declare s1 as String s1; one time outside the loop. To end the loop, simply use ctrl+z.
while (sc.hasNext())
{
s1 = sc.next();
System.out.println(s1);
System.out.print("Enter your sentence: ");
}
I want to take input form user, i am sure my code is right but it don't work at all. Please help is there any thing that i am doing wrong?
`public void edit() throws IOException {
sll.insertAfter();
System.out.println("Enter text: ");
String sen;
sen = keyboard.next();
Object obj = sen;
sll.put(obj);
}
when i execute this an error appears at this line
sen = keyboard.next();
import java.util.*;
public class Example
{
public static void main(String[] args)
{
Edit();
}
public static void Edit()
{
Scanner scan = new Scanner(System.in);
String random;
System.out.print("Please input some text: ");
random = scan.nextLine();
System.out.println("You entered: " + random);
}
}
I don't know what your main method looks like so I can only assume it's empty That being said I can tell you why your current code doesn't work based off of the information you've given us.
Your edit method is not static, and in this situation assuming you've laid out your program simillar to this it must be static as it is in my example.
You've not setup a scanner, or maybe you did outside of your edit method but failed to make it static?
Scanner scan = new Scanner(System.in);
Why are you using Object, if you want to edit the string just use a for loop and substring.
Object
If you provide us with more information, your full code and the error you're getting we can better help you!
I have tried to solve the 3n+1 problem, and got very close. I think what happens here is the answer should accept multiple lines of input at once should not ask the user to give input again. I have tried the nextLine() method in a loop conditioned by the hasNextLong(), but the problem is whenever it does not find any more long types, it asks the user to give another input instead of breaking the loop. Is there any way to make sure it takes input only once, regardless of how many lines the user inputs?
The loop breaks if I enter a String. What I want to do is break when only the first input has no more long variables to deal with.
import java.util.Scanner;
import java.io.*;
public class te{
public static void main(String[] args){
Scanner key=new Scanner (new BufferedInputStream(System.in));
String s="";
while(key.hasNextInt()){
System.out.println("Entered loop");
s=s+""+key.nextLong();
}
System.out.println(s);
}
}
Not 100% sure what your trying to accomplish, but to answer this problem:
"..whenever it does not find any more long types, it asks the user to give another input instead of breaking the loop."
I just used a try/catch block. If the input is not a number, it breaks the loop. You can keep inputting numbers and hitting enter, and if an input is not a number, the loop will break; and it will print out the concatenated numbers.
import java.util.Scanner;
public class StackOverflow {
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
String s = "";
System.out.println("Enter Numbers: ");
while (true) {
try {
s += String.valueOf(scanner.nextInt()); // if input is not an int
} catch (Exception ex) { // it will throw exception
break;
}
}
System.out.println(s);
}
}
Edit: Scanning a line
Scanner input = Scanner(System.in);
System.out.printline("Enter some numbers: ");
String line = scanner.nextLine();
Scanner lineScanner = new Scanner(line);
while (lineScanner.hasNextLong()){
long num = lineScanner.nextLong();
// do something with num
}
I ran into an issue. Below is my code, which asks user for input and prints out what the user inputs one word at a time.
The problem is that the program never ends, and from my limited understanding, it seem to get stuck inside the while loop. Could anyone help me a little?
import java.util.Scanner;
public class Test{
public static void main(String args[]){
System.out.print("Enter your sentence: ");
Scanner sc = new Scanner (System.in);
while (sc.hasNext() == true ) {
String s1 = sc.next();
System.out.println(s1);
}
System.out.println("The loop has been ended"); // This somehow never get printed.
}
}
You keep on getting new a new string and continue the loop if it's not empty. Simply insert a control in the loop for an exit string.
while(!s1.equals("exit") && sc.hasNext()) {
// operate
}
If you want to declare the string inside the loop and not to do the operations in the loop body if the string is "exit":
while(sc.hasNext()) {
String s1 = sc.next();
if(s1.equals("exit")) {
break;
}
//operate
}
The Scanner will continue to read until it finds an "end of file" condition.
As you're reading from stdin, that'll either be when you send an EOF character (usually ^d on Unix), or at the end of the file if you use < style redirection.
When you use scanner, as mentioned by Alnitak, you only get 'false' for hasNext() when you have a EOF character, basically... You cannot easily send and EOF character using the keyboard, therefore in situations like this, it's common to have a special character or word which you can send to stop execution, for example:
String s1 = sc.next();
if (s1.equals("exit")) {
break;
}
Break will get you out of the loop.
Your condition is right (though you should drop the == true). What is happening is that the scanner will keep going until it reaches the end of the input. Try Ctrl+D, or pipe the input from a file (java myclass < input.txt).
it doesn't work because you have not programmed a fail-safe into the code. java sees that the scanner can still collect input while there is input to be collected and if possible, while that is true, it keeps doing so. having a scanner test to see if a certain word, like EXIT for example, is fine, but you could also have it loop a certain number of times, like ten or so. but the most efficient approach is to ask the user of your program how many strings they wish to enter, and while the number of strings they enter is less than the number they put in, the program shall execute. an added option could be if they type EXIT, when they see they need less spaces than they put in and don't want to fill the next cells up with nothing but whitespace. and you could have the program ask if they want to enter more input, in case they realize they need to enter more data into the computer.
the program would be quite simplistic to make, as well because there are a plethera of ways you could do it. feel free to ask me for these ways, i'm running out of room though. XD
If you don't want to use an EOF character for this, you can use StringTokenizer :
import java.util.*;
public class Test{
public static void main(){
Scanner sc = new Scanner (System.in);
System.out.print("Enter your sentence: ");
String s=sc.nextLine();
StringTokenizer st=new StringTokenizer(s," ");//" " is the delimiter here.
while (st.hasMoreTokens() ) {
String s1 = st.nextToken();
System.out.println(s1);
}
System.out.println("The loop has been ended");
}
}
I had the same problem and I solved it by reading the full line from the console with one scanner object, and then parsing the resulting string using a second scanner object.
Scanner console = new Scanner(System.in);
System.out.println("Enter input here:");
String inputLine = console.nextLine();
Scanner input = new Scanner(inputLine);
List<String> arg = new ArrayList<>();
while (input.hasNext()) {
arg.add(input.next().toLowerCase());
}
You can simply use one of the system dependent end-of-file indicators ( d for Unix/Linux/Ubuntu, z for windows) to make the while statement false. This should get you out of the loop nicely. :)
Modify the while loop as below. Declare s1 as String s1; one time outside the loop. To end the loop, simply use ctrl+z.
while (sc.hasNext())
{
s1 = sc.next();
System.out.println(s1);
System.out.print("Enter your sentence: ");
}