How does nextLine work with scanner? - java

I am trying to split "sisestus" into different words by using space as a separator, but by just using sc.next() doesn't allow me to enter a string with spaces so i read that i should use .nextLine(), but it doesn't work at all. How do i solve it?
public class Sisestamine {
int read;
int veerud;
double Maatriks[][];
java.util.Scanner sc = new java.util.Scanner(System.in);
Sisestamine() {
System.out.println("Enter matrix dimensions (format NxM)");
String[] abi = sc.next().split("x");
this.read = Integer.parseInt(abi[0]);
this.veerud = Integer.parseInt(abi[1]);
this.Maatriks = new double[read][veerud];
System.out.println("Enter the matrix: (x x x x etc..)");
for (int i = 0; i < read; i++) {
String sisestus = sc.next();
//String sisestus = sc.nextLine();
abi = sisestus.split(" ");
System.out.print(abi);
for (int j = 0; j < abi.length; j++) {
this.Maatriks[i][j] = Double.parseDouble(abi[j]);
}
}
}
}

Your problem could be because you're using sc.next() at one part of your program and then sc.nextLine() later, and the second call swallows the end of line (EOL) token that was left hanging from the prior call to next(). A solution is to use sc.nextLine() for all invocations. In other words, change all sc.next() to sc.nextLine().

Related

How to take input of every next line from console in java ? I have made a code but it's not giving the desired output

I want to take the input from the console like as follows:
3(int type)
1(int type)
4(int type)
1100(String type)
1010(String type)
0000(String type)
My Code is as follows :
int numberOfFriends = sc.nextInt();
int forbidden = sc.nextInt();
int binaryOptions = sc.nextInt();
String[] friendsOrder = new String[numberOfFriends];
System.out.println(numberOfFriends);
System.out.println(forbidden);
System.out.println(binaryOptions);
for(int j=0;j<numberOfFriends;j++)
{
friendsOrder[j] = sc.nextLine();
}
for(int j=0;j<numberOfFriends;j++)
{
System.out.println(friendsOrder[j]);
}
but it's output is :
3
1
4
1100
1010
It's not printing all the string inputs, besides its printing null why so?
You should change
for(int j=0;j<numberOfFriends;j++)
{
friendsOrder[i] = sc.nextLine();
}
to
for(int i=0;i<numberOfFriends;i++)
{
friendsOrder[i] = sc.nextLine();
}
as looping over j and using i as index inside the loop makes no sense.
After 3rd sc.nextInt() you will have to use an extra sc.nextLine() to go to the next line. From there use sc.nextLine() to read your 3 lines.
Updated code
int numberOfFriends = sc.nextInt();
int forbidden = sc.nextInt();
int binaryOptions = sc.nextInt();
sc.nextLine(); // extra sc.nextLine call
String[] friendsOrder = new String[numberOfFriends];
System.out.println(numberOfFriends);
System.out.println(forbidden);
System.out.println(binaryOptions);
for(int j=0;j<numberOfFriends;j++)
{
friendsOrder[j] = sc.nextLine(); // there is also a small mistake here, use j instead of i
}
for(int j=0;j<numberOfFriends;j++)
{
System.out.println(friendsOrder[j]);
}
Whats happening is after 3rd sc.nextInt(), the next call to sc.nextLine() reads the same line which contains 3rd integer till the end of line.
Scanner.nextLine() read up to the first newline character('\n'). After reading the int, '\n' is still in the stream and hence on the first run of your for loop, nextLine() method is reading that '\n' character and returns. You have to call newLine() again to read the entered string. The updated code will be:
int numberOfFriends = sc.nextInt();
int forbidden = sc.nextInt();
int binaryOptions = sc.nextInt();
String[] friendsOrder = new String[numberOfFriends];
System.out.println(numberOfFriends);
System.out.println(forbidden);
System.out.println(binaryOptions);
for(int j=0;j<numberOfFriends;j++)
{
sc.nextLine();
friendsOrder[i] = sc.nextLine();
}
for(int j=0;j<numberOfFriends;j++)
{
System.out.println(friendsOrder[j]);
}

How do you take an undefined amount of inputs from scanner?

I am making a search engine to find what document matches the words given by the user. The following is my code:
Scanner userInput = new Scanner(System.in);
System.out.println("\n\n\nEnter the words you would like to search your documents for (up to 10):");
String[] stringArray = new String[10];
int i = 0;
// Takes input until user leaves a blank line or max is reached.
while (userInput.hasNext() && i < 9){
stringArray[i] = userInput.next();
i++;
}
for (int j = 0; j < i; j++){
System.out.println(stringArray[j]);
}
This is my method that actually takes the user input and I am going to add to it in a little bit to do the search but I tried to test this much (that's why it prints out the input) to see if it works but It keeps accepting input. What can I change so that it takes as many words as the user puts them until they leave a line blank? I got it to stop at 10 but I thought hasNext() would stop it when they leave a line blank but it just keeps scanning.
hasNext() & next() stop at words, not lines. With your code, the user could put all 10 words on the same line and they'd be done. Also, these methods will skip all whitespace, including newline characters, until they find the next word. You can't look for a blank line using hasNext() and next() can never return an empty string. You want hasNextLine() and nextLine() instead.
Scanner userInput = new Scanner(System.in);
System.out.println("\n\n\nEnter the words you would like to search your documents for (up to 10):");
String[] stringArray = new String[10];
int i = 0;
while (i < stringArray.length
&& userInput.hasNextLine()
&& !(stringArray[i] = userInput.nextLine().trim()).isEmpty()) {
i++;
}
for (int j = 0; j < i; j++) { // just for testing purposes
System.out.println(stringArray[j]);
}
But why limit yourself to just 10 lines? You can use ArrayList instead for more flexibility:
Scanner userInput = new Scanner(System.in);
System.out.println("\n\n\nEnter the words you would like to search your documents for:");
List<String> stringList = new ArrayList<>();
String line;
while (userInput.hasNextLine()
&& !(line = userInput.nextLine().trim()).isEmpty()) {
stringList.add(line);
}
stringList.forEach(System.out::println); // just for testing purposes
Change your while loop to this:
while (!(String temp = userInput.nextLine()).trim().contentEquals("")) {
stringArray[i] = userInput.next();
i++;
}
String line;
int i = 0;
while(!(line = userInput.nextLine()).isEmpty()) {
for (String word :line.split("\\s+")){
stringArray[i]=word;
i++;
}
}
This code assigns every line from Scanner into variable line until is not user input empty. In every iteration it splits line to words and assigns to stringArray.

Java Scanner does not expect next input, ignores nextLine()

I don't really get the behaviour of the Scanner. I want to input a single int first and in the while-loop, as you can see, next line inputs. But after the first input I get an ArrayOutOfBoundsException as you can see below. It just ignores that I want to input next lines. The only solution is when I input the int and the new line separated with a space in one line, but that isn't what I want, because at this point, the user doesn't know, what to input after the first int.
Scanner scanner = new Scanner(System.in);
int i = scanner.nextInt() - 1;
logic.setGameField(games.get(i).getGameField());
// scanner.reset(); //what does that do?
view.displayField(logic.getCompleteGameField(), logic.getGameSize(), logic.getCompleteGameSize());
double time = System.currentTimeMillis();
while (!logic.gameIsFinished()) {
System.out.println("Spalte Reihe Zeichen: X/*");
String s = scanner.nextLine();
char[] tmp = s.toCharArray();
//just for testing
System.out.println(s.length()); //outputs: 0
System.out.println(tmp.length); //outputs: 0
for (int j = 0; j < tmp.length; j++) {
System.out.print(tmp[j] + " " + j);
}
System.out.println();
logic.setSingleField(tmp[1] - CHAR_TO_INT_OFFSET_ROW, tmp[0] - CHAR_TO_INT_OFFSET_COLUMN, tmp[2]); //throws as expected ArrayIndexOutOfBoundsException
This is because Scanner.nextInt() doesn't bring you to the next line. At this point, you are still in current line of input. What you can do is call an additional Scanner.nextLine() after Scanner.nextInt():
int i = scanner.nextInt() - 1;
scanner.nextLine();
logic.setGameField(games.get(i).getGameField());

Scanner skipping first input in loop Java [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 7 years ago.
This is a basic name sorting program. Everything works except for the fact that the user cannot input the first name. This is the code:
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.println("How many names do you want to sort");
int num = sc.nextInt();
String[] names = new String[num];
for (int x = 0; x < names.length; x++){
int pos = x+1;
System.out.println("Enter name " + pos);
//String temp = sc.nextLine();
names[x] = sc.nextLine();
}
String sortedArray[] = sort(names);
for (int i = 0; i < sortedArray.length; i++){
System.out.print(sortedArray[i] + " ");
}
}
Update: I changed the code so if it is the first time, it calls sc.nextLine() and then sets the input equal to names[0]
One problem with .next() is that if a person's first name is 2 words to treats it as two names. This is the updated code that works:
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("How many names do you want to sort");
int num = sc.nextInt();
String[] names = new String[num];
//String[] temp = new String[names.length];
for (int x = 0; x < names.length; x++) {
int pos = x + 1;
if (x == 0) {
System.out.println("Enter name 1");
sc.nextLine();
names[0] = sc.nextLine();
} else {
System.out.println("Enter name " + pos);
//String temp = sc.nextLine();
names[x] = sc.nextLine();
}
}
String sortedArray[] = sort(names);
for (int i = 0; i < sortedArray.length; i++) {
System.out.print(sortedArray[i] + " ");
}
}
Use sc.next(); instead of sc.nextLine();
next() will find and return the next complete token from the input stream.
nextLine() will advance the scanner past the current line and will return the input that was skipped
Also, check below description from Scanner#nextLine().
Advances this scanner past the current line and returns the input that
was skipped. This method returns the rest of the current line,
excluding any line separator at the end. The position is set to the
beginning of the next line.
Since this method continues to search through the input looking for a
line separator, it may buffer all of the input searching for the line
to skip if no line separators are present.
Scanner sc = new Scanner(System.in);
System.out.println("How many names do you want to sort");
int num = sc.nextInt();
String[] names = new String[num];
for (int x = 0; x < names.length; x++){
int pos = x+1;
System.out.println("Enter name " + pos);
//String temp = sc.nextLine();
names[x] = sc.next();
}
/*String sortedArray[] = sort(names);
for (int i = 0; i < sortedArray.length; i++){
System.out.print(sortedArray[i] + " ");
}*/

Java stop reading after empty line

I'm doing an school exercise and I can't figure how to do one thing.
For what I've read, Scanner is not the best way but since the teacher only uses Scanner this must be done using Scanner.
This is the problem.
The user will input text to an array. This array can go up to 10 lines and the user inputs ends with an empty line.
I've done this:
String[] text = new String[11]
Scanner sc = new Scanner(System.in);
int i = 0;
System.out.println("Please insert text:");
while (!sc.nextLine().equals("")){
text[i] = sc.nextLine();
i++;
}
But this is not working properly and I can't figure it out.
Ideally, if the user enters:
This is line one
This is line two
and now press enter, wen printing the array it should give:
[This is line one, This is line two, null,null,null,null,null,null,null,null,null]
Can you help me?
while (!sc.nextLine().equals("")){
text[i] = sc.nextLine();
i++;
}
This reads two lines from your input: one which it compares to the empty string, then another to actually store in the array. You want to put the line in a variable so that you're checking and dealing with the same String in both cases:
while(true) {
String nextLine = sc.nextLine();
if ( nextLine.equals("") ) {
break;
}
text[i] = nextLine;
i++;
}
Here's the typical readline idiom, applied to your code:
String[] text = new String[11]
Scanner sc = new Scanner(System.in);
int i = 0;
String line;
System.out.println("Please insert text:");
while (!(line = sc.nextLine()).equals("")){
text[i] = line;
i++;
}
The code below will automatically stop when you try to input more than 10 strings without prompt an OutBoundException.
String[] text = new String[10]
Scanner sc = new Scanner(System.in);
for (int i = 0; i < 10; i++){ //continous until 10 strings have been input.
System.out.println("Please insert text:");
string s = sc.nextLine();
if (s.equals("")) break; //if input is a empty line, stop it
text[i] = s;
}

Categories