0

I want to take input from the console firstly, an integer and then an array of integer separated by comma and space. The input is as follows:
5

55, 24, 32, 22, 89

and my code is:

public static void main (String[] args) {
    //code
     Scanner sc = new Scanner(System.in);
    int num = sc.nextInt();
    int[] array = new int[num];
    String line = sc.nextLine();
    line = line.replaceAll(" ","");
    String[] temp = line.split(",");
    for(String i :temp)
    {
        System.out.print(i+" ");
    }
}

but it is showing InputMismatchException.

Asheesh Sahu
  • 192
  • 10

1 Answers1

1

Try adding sc.nextLine(); before String line = sc.nextLine();

Try this code :-

import java.util.*;

public class Main {
  public static void main(String[] args) {
    // code
    Scanner sc = new Scanner(System.in);
    int num = sc.nextInt();
    int[] array = new int[num];
    sc.nextLine(); // advance to new line
    String line = sc.nextLine();
    line = line.replaceAll(" ", "");
    String[] temp = line.split(",");
    for (String i : temp) {
      System.out.print(i + " ");
    }
  }
}

Output :-

5
55, 24, 32, 22, 89
55 24 32 22 89 
anoopknr
  • 2,505
  • 2
  • 14
  • 25