scanner i java doesn't work for all inputs [duplicate] - java

This question already has answers here:
Scanner doesn't work properly after reading double [duplicate]
(3 answers)
Closed 7 years ago.
I want to read several things ( long, string ) from console but I don't know why for, for example just several first input it works and then it doesn't work for others:
below is the code what I'm talking about, it doesn't ask for adress
public void getInfo(PhoneBook PB)
{
Scanner keyboard = new Scanner(System.in).useDelimiter("\n");
String c1 = "yes";
do {
System.out.print("Name:");
PB.setName(keyboard.nextLine());
System.out.print("Family:");
PB.setFamily(keyboard.nextLine());
System.out.print("Address:");
PB.setAddress(keyboard.nextLine());
System.out.print("Number:");
PB.setNumber(keyboard.nextLong());
System.out.println("Do you want to continue(yes/no)");
c1 = keyboard.nextLine();
phoneBooks.add(PB);
}while (c1.equals("yes"));
}
Thanks in advance

When you call nextLong() (or nextInt(), nextDouble(), next()...), you are reading in a token with the Scanner, but are not reading in the end-of-line (EOL) token, thus leaving it dangling. This dangling EOL token will then be scooped up immediately with your next call to nextLine(), and so that call will not get the user's input, messing your program up. To fix this, add an additional call to nextLine()after getting your nextLong(), ignoring any result returned since it will just be the EOL token.
So change this:
System.out.print("Number:");
PB.setNumber(keyboard.nextLong());
System.out.println("Do you want to continue(yes/no)");
c1 = keyboard.nextLine();
to this:
System.out.print("Number:");
PB.setNumber(keyboard.nextLong());
keyboard.nextLine(): // **** add this ****
System.out.println("Do you want to continue(yes/no)");
c1 = keyboard.nextLine();

Related

Can't get program to break on specific string [duplicate]

This question already has answers here:
Scanner only reads first word instead of line
(5 answers)
Closed 2 years ago.
The code works for the most part, but if I type "No way" it still stops the loop. Should I set it up a different way or use a length function ? Everything I've searched on breaking a loop used integers.
See the code below:
import java.util.Scanner;
public class CarryOn {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("Shall we carry on?");
String answer = String.valueOf(scanner.next());
if (answer.equalsIgnoreCase("no")){
break;
}
}
}
}
Using .next in this case only stores "no" in "no way". Use .nextLine instead:
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("Shall we carry on?");
String answer = String.valueOf(scanner.nextLine());
if (answer.equalsIgnoreCase("no")){
break;
}
}
Output:
Shall we carry on?
no way
Shall we carry on?
no
Check this post for more information.
scanner.next()
only reads a single token. No way is two tokens: No and way.
Use scanner.nextLine() instead, if you want to read the whole line.

How to print a line and type input in the same line [duplicate]

This question already has answers here:
How to keep my user input on the same line after an output?
(4 answers)
Closed 3 years ago.
I want to print a line like this:
Result: [the result are input here and after click on Enter to continue]
How can I do that?
EDIT:
This is what I want:
Scanner user1 = new Scanner(System.in);
int x = user1.nextInt();
System.out.println("Result: "+x);
But the last line won't print unless I type my input and press Enter.
Using java, you simply could use System.out.print(); to display it in console and after adding the capture info:
System.out.print("Result: ");
int x = user1.nextInt();
This is a very old thread but since there doesn't seem to be an accepted answer, I am answering. Hope it would help someone else...
Here is what you are looking for
Scanner input = new Scanner (System.in);
System.out.print("Enter a number : ");
int num = input.nextInt();
System.out.println("Hello you entered "+num);
Note that when you use println the cursor moves to next line.
If you use just print the next statement continues on the same line.
Hope this one will work. Please try
Input str =scanner. readLine("Result:" ) ;
Int inp =integer.parseInt(star) ;
The last line will not print unless you type an input and press enter as the code is run line by line. First you have to enter the value. Since it runs on console for the next step to be pressed you have to press enter.
So whatever you said will naturally happen and cannot be avoided.
Based on the code snippet you sent there is nothing wrong with the code and the logic in it and these are basic java steps.

Java - program skips Scanner(System.in) [duplicate]

This question already has an answer here:
How to use java.util.Scanner to correctly read user input from System.in and act on it?
(1 answer)
Closed 5 years ago.
public static char[] puzzleInput() {
printEnterPuzzleMessage();
Scanner puzzleS = new Scanner(System.in);
if(puzzleS.hasNext()) {
char[] puzzle = puzzleS.next().toCharArray();
while(!isLegalPuzzleStructure(puzzle)) {
printIllegalPuzzleMessage();
puzzleInput();
}
return puzzle;
}
puzzleS.close();
return null;
}
public static void main(String[] args) throws Exception{ //Q - 8
Scanner fileName = new Scanner(System.in);
if(!fileName.hasNext()) {
System.out.println("No argument has been received");
System.exit(0);
}
String filePath = fileName.nextLine();
fileName.close();
Scanner vocabulary = new Scanner(new File(filePath));
String[] vocabularyArr = scanVocabulary(vocabulary);
vocabulary.close();
printReadVocabulary(filePath, vocabularyArr.length);
printSettingsMessage();
printEnterPuzzleMessage();
char[] puzzle = puzzleInput();
Hi, a beginner in Java is here.
In the function puzzleInput, I open a Scanner to get an input from the user. For some reason, the program won't give me a chance to put in input, and therefor the argument (puzzle) gets a null as default, and later when puzzle is needed not as a null - throws a NullPointerException.
There are many other functions in the code, but most of them are just a print commands, and the ones who are not were being checked by me, and are OK.
The problem is just the scanner won't give me a chance to put in an input.
Some points I'd like to clarify further:
1. The first Scanner (fileName) is not being skipped by the program, and I'm able to give it an argument.
2. I made sure I closed all the other scanners i've opened before.
Can someone explain me what I'm doing wrong?
program won't give me a chance to put in input
Your problem is that you are closing your Scanner in main:
Scanner fileName = new Scanner(System.in);
...
fileName.close();
This in turn closes the System.in input-stream which then cannot be reused in your puzzleInput() method because it is already closed. The right thing to do here is to pass in the Scanner variable into your puzzleInput() method and continue to reuse it there and not try to open up a new Scanner.
public static char[] puzzleInput(Scanner scanner) {
printEnterPuzzleMessage();
if(scanner.hasNext()) {
...
// don't close it here
return null;
}
...
Scanner scanner = new Scanner(System.in);
...
puzzleInput(scanner);
Couple of other comments:
Calling a Scanner fileName is not a good pattern. Choosing good names for your variables will help make the code self-documenting. scanner would be a better name of course.
When dealing with any input/output, it is a good practice to wrap any opening method in a try/finally block so it gets close properly. See also the try-with-resources functionality added in Java 7.
If you want a chance to do something with the input with a prompt, why not assign it to a String variable? This allows you to manipulate the input however you want later on too.
String input = scannerName.nextLine();

Java Using Scanner Multiple Times [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 26 days ago.
I am having this problem a lot. When I use a Scanner a lot of times, it doesn't get input from user.
Scanner scan = new Scanner(System.in);
System.out.println("1---");
int try1 = scan.nextInt();
System.out.println("2---");
int try2 = scan.nextInt();
System.out.println("3---");
String try3 = scan.nextLine();
System.out.println("4---");
String try4 = scan.nextLine();
When I run this code, result it :
1---
12
2---
321
3---
4---
aa
As you can see, it skipped at 3rd input. Why this is happening? I solve this problem by using new Scanners, sometimes I have 5-6 different Scanners and it looks so complicated.
Another problem is : there is an error "Resource leak: scan is never closed". I am really confused.
The problem is that by using scanner.nextInt() you only read an integer value, but not the whole line and you don't consume the newline character (\n) that is appended to the line when you press Enter.
Then, when you process reading with scanner.nextLine() you consume the newline character (\n) and from the previous row and don't read the line you want to read. In order to force it to read it, you have to add an additional input.nextLine() statement.
System.out.println("2---");
int try2 = scan.nextInt();
System.out.println("3---");
scan.nextLine(); //<-- fake statement, to move the cursor on the next line
String try3 = scan.nextLine();
Not related to the question, you have to close the Scanner, after finishing work, otherwise the compiler complains with a warning:
scan.close();
Use next API rather than nextLine as when you do nextInt you press enter and it generates number + \n and nextInt is only going to take an integer and won't take \n which in turn gets passed to next input i.e. try3 which is why it gets skipped.
Scanner scan = new Scanner(System.in);
System.out.println("1---");
int try1 = scan.nextInt();
System.out.println("2---");
int try2 = scan.nextInt();
System.out.println("3---");
String try3 = scan.next();
System.out.println("4---");
String try4 = scan.next();
Well, for the first question use
scan.next()
insted of using
scan.nextLine();
For the second question I'd recommend using try, assuming you need to close your scan as your compiler is warning: "Resource leak: scan is never closed"
Scanner scanner= null;
try {
scanner= new Scanner(System.in);
}
finally {
if(scanner!=null)
scanner.close();
}

Java is skipping a line (Strings in a Scanner ??) [duplicate]

This question already exists:
Scanner issue when using nextLine after nextXXX [duplicate]
Closed 9 years ago.
I am learning Java, and I'm not very far into it, and I don't know why but Java seemed to skip a line. I don't think the code from all my pages is really neccesery so I will just put the first page and the result I get when using it. Thanks!
import java.util.Scanner;
public class First {
public static void main(String args[]){
Scanner scanz = new Scanner(System.in);
System.out.println("Hello, please tell me your birthday!");
System.out.print("Day: ");
int dayz = scanz.nextInt();
System.out.print("Month: ");
int monthz = scanz.nextInt();
System.out.print("Year: ");
int yearz = scanz.nextInt();
System.out.println("Now, tell me your name!");
System.out.print("Name: ");
String namez = scanz.nextLine();
Time timeObject = new Time(dayz,monthz,yearz);
Second secondObject = new Second(namez,timeObject);
System.out.println("\n\n\n\n\n" + secondObject);
}
}
It skips the line
String namez = scanz.nextLine();
Console output: (excuse the birthday bit, it is other stuff)
Hello, please tell me your birthday!
Day: 34
Month: 234
Year: 43
Now, tell me your name!
Name:
My name is and my birthday is 00/00/43
It doesn't give you a chance to give a name, it just skips straight past and takes the name as null. Please, if anyone could, tell me why! I want to learn Java, and this little annoyance is standing in my way.
Thanks!
The problem is that the nextLine gets any characters on the line, and the \n (newline character) is left over from the scanner inputs above.
So instead of letting you enter something new, it takes the \n as the input and continues.
To fix, just put two scanners back to back like this:
System.out.print("Name: ");
scanz.nextLine();
String namez = scanz.nextLine();
Just using:
String namez = scanz.next();
will work too, but will limit the names to be one word. (aka first name only)
I believe the intended use of nextLine is correct. The problem however is that nextInt does not create a newline token, and it's instead reading the rest of that line (which is empty). I believe that if another nextLine statement would be added after that, the code would work. Next on the other hand only recognizes the first word so that might not be the correct solution.

Categories