4

When I use scan.nextLine(), input boxes don't work properly. If it's scan.next() ,works perfectly.But Why? Ain't I supposed to use scan.nextLine() for string?

import java.util.Scanner;
public class Test{
public static void main(String[] args){

    Scanner scan = new Scanner(System.in);
    int x = scan.nextInt();
    System.out.println("p");
    String p = scan.nextLine();
    System.out.println("q");
    String q = scan.next();
    System.out.println("m");
    String m = scan.next();
    }  
}
Mritunjay
  • 22,738
  • 6
  • 47
  • 66
2apreety18
  • 73
  • 6

3 Answers3

1

Before using them, try to check the doc's.
Reason :

Scanner.nextLine : The java.util.Scanner.nextLine() method 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.

While, this is not Applicable to Scanner.nextInt

Hence, the Scanner.nextInt method does not consume the last newline character of your input, and thus that newline is consumed in the next call to Scanner.nextLine.

Basic Solution would be to use blank Scanner.nextLine after Scanner.nextInt just to consume rest of that line including newline.

For Example

int myVal1 = input.nextInt();
input.nextLine(); 
String myStr1 = input.nextLine();
Tahir Hussain Mir
  • 2,203
  • 2
  • 18
  • 25
0

This is the solution to the problem I'd use. The above comment by Tahir Hussain Mirwould likely be the cause of the problem

import java.util.ArrayList;
import java.util.Scanner;

public class app {
public static void main(String[] args) {
    // declare scanner
    Scanner scan = new Scanner(System.in);

    // what ever number you need, it could be calculated
    int numberOfInputLines = 3;

    // the list of the lines entered
    ArrayList<String[]> list = new<String[]> ArrayList();

    // add each line to the list
    for (int i = 0; i < numberOfInputLines; i++) {
        // get entire line as a single string
        String input = scan.nextLine();
        // split the line into tokens, and store the array in the array list
        String[] result = input.split("\\s");
        list.add(result);

    }

    // iterate through each line
    for (int i = 0; i < list.size(); i++) {

        // iterate through the line
        for (int j = 0; j < list.get(i).length; j++) {
            if (isInteger(list.get(i)[j]) == true) {
                // do what you want if the input is an int
                //to show it works
                System.out.println("int: " + list.get(i)[j]);

            } else {
                // do what you want if a the token inputed is a string
                //to show it works
                System.out.println("String: " + list.get(i)[j]);

            }

        }

    }

}

// greasy way to check if is an int
private static boolean isInteger(String s) {
    try {
        Integer.parseInt(s);
    } catch (NumberFormatException e) {
        return false;
    } catch (NullPointerException e) {
        return false;
    }
    // only got here if we didn't return false
    return true;
}

}
-1

You should use nextLine and then convert it to your expected types.

In above scenario read the line then cast it to an integer, because next and nextInt just read the input before a whitespace occurred. So when you are calling nextInt it will just consume the number and leave the newLine character which will be consumed in nextLine.

From the question, it looks like this is how you are going to read inputs input.

  1. First integer.
  2. Second a string line.
  3. Third line will have two words separated by space.

This is what your code should be.

    Scanner scan = new Scanner(System.in);
    int x = Integer.parseInt(scan.nextLine()); //read line and then cast to integer
    System.out.println("p");
    String p = scan.nextLine();
    System.out.println("q m");
    String[] linesParts = scan.nextLine().split(" "); // read the whole line and then split it.
    String q = linesParts[0];
    String m = linesParts[1];
Mritunjay
  • 22,738
  • 6
  • 47
  • 66
  • 2
    and why would I do that ? There is a downvote on this answer as well. – Mritunjay Nov 25 '16 at 04:46
  • 3
    whoever is downvoting please leave comments as well. Thanks – Mritunjay Nov 25 '16 at 04:48
  • exactly, whoever is downvoting please leave comments. – lmiguelvargasf Nov 25 '16 at 04:55
  • I was about to up vote this to save your rep, but I just tried testing your code and it crashes anytime you enter an input. Also, I was not the one who down voted it –  Nov 25 '16 at 05:38
  • @holycatcrusher well I have mentioned the input format before the code, if it's in that format, it won't crash. – Mritunjay Nov 25 '16 at 05:59
  • true. I actually think I may have accidentally run the other guys code twice. Saving up vote granted, lol. Not sure who is doing the down voting –  Nov 25 '16 at 06:07