Home > Mobile >  How to take several inputs in the same line in Java
How to take several inputs in the same line in Java

Time:03-04

I have an assignment that I already did most of it. I just can't stop the console to go to new line after taking inputs. Here is the code:

public static double[][] getMatrix(int rows, int columns) {
    // Complete this method according to assignment
    Scanner scan = new Scanner(System.in);
    double matrix [][] = new double[rows][columns];
 for(int i = 0; i < matrix.length; i  ) {
     System.out.print("Row number " (i 1) ":");
     for(int j = 0; j < matrix[i].length; j  ) {
         matrix [i][j] = scan.nextDouble();
         System.out.print("");
     
 }
         
 }
 return matrix;
}

Result looks like this:

Row number 1:1
2
3
Row number 2:4
4
3
Row number 3:456
3
3

What I need it to look like:

Row number 1:1 2 3
Row number 2:4 4 3
Row number 3:456 3 3

Edit 1: I am sorry if I didn't make myself clear. I don't want it to store the inputs as arrays. I just want it to simply put space after user entered an input. Right now in console it goes to next line every single time user enters an input.

CodePudding user response:

you can use scanner inside another scanner which will result in an array format then using iterations you can use the values of the fetched array

Code:

public static void main(String[] args)
    {
        Scanner scanner = new Scanner(System.in);
 
        while (scanner.hasNextLine())
        {
            List<String> tokens = new ArrayList<>();
            Scanner lineScanner = new Scanner(scanner.nextLine());
 
            while (lineScanner.hasNext()) {
                tokens.add(lineScanner.next());
            }
 
            lineScanner.close();
            System.out.println(tokens);
        }
 
        scanner.close();
    }

Sample output: input from user : 1 2 3 this is how it is stored(array) : [1, 2, 3]

CodePudding user response:

You can also use //s that is space plus notation with escape char '/' which means that if user give input with one or multiple spaces, it can be converted it to an array using string.split()

code example:

public static void main(String[] args)
    {
        Scanner scanner = new Scanner(System.in);
 
        while (scanner.hasNextLine())
        {
            String[] tokens = scanner.nextLine().split("\\s");
            System.out.println(Arrays.toString(tokens));
        }
 
        scanner.close();
    }
  • Related