Lucas Hoage
Lucas Hoage

Reputation: 5

Input from scanner to multidimensional array to a string for output

A similarly written code will work but only if there is a single array. When I try this using multidimensional arrays, it tells me that it cannot be converted from an array to a string.

Why is this happening?

What direction can I take to learn how to solve his problem?

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        String[][] sentence = new String[3][2];
        Scanner scaninput = new Scanner(System.in);

        for (int row = 0; row < sentence.length; row++) {
            for (int col = 0; col < sentence[row].length; col++) {
                System.out.println("Enter some words: ");
                sentence[row][col] = scaninput.nextLine();
            }
        }

        for (String sentences : sentence) {
            System.out.println(sentences + " ");
        }
    }
}

Upvotes: 0

Views: 259

Answers (1)

leetcode269
leetcode269

Reputation: 401

The variable sentence is a reference to an array of arrays. You need to do something like the following to access individual string.

for(String[] sentences : sentence){
    for(String s : sentences){
      \\Do something
    }
}

Upvotes: 1

Related Questions