panoskarajohn
panoskarajohn

Reputation: 1988

Scanner read an array of inputs from console

Hi how can i achieve the same effect in java? The code below is in C#.

 for(int arr_i = 0; arr_i < 6; arr_i++)
{
           string[] arr_temp = Console.ReadLine().Split(' ');
           arr[arr_i] = Array.ConvertAll(arr_temp,Int32.Parse);
}

Upvotes: 0

Views: 5800

Answers (2)

Ousmane D.
Ousmane D.

Reputation: 56423

It seems that you're working with jagged arrays in C# where each element of the array is another array. In Java you'll need to use a Scanner#nextLine() to imitate Console.ReadLine() in C#.

Scanner scanner = new Scanner(System.in);
...
...
...
for(int arr_i = 0; arr_i < 6; arr_i++)
{
     String[] arr_temp = scanner.nextLine().split(" ");
     arr[arr_i] = Arrays.stream(arr_temp).mapToInt(Integer::parseInt).toArray();
}

in Java 8 you can use Stream#mapToInt to imitate Array.ConvertAll in C#.

Upvotes: 3

Nabin Bhandari
Nabin Bhandari

Reputation: 16389

In Java split() method returns an array of String. You have to parse the individual String in the array to Integer.

Try something like this:

public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    String[] data = in.nextLine().split(" ");
    int[] numbers = new int[data.length];
    for (int i = 0; i < data.length; i++) {
        numbers[i] = Integer.parseInt(data[i]);
    }
    System.out.println(Arrays.toString(numbers));
}

Upvotes: 3

Related Questions