Revi
Revi

Reputation: 11

Incompatible types in arrays in java

I am quite new to java and for an assignment I have to ask for three words and then print these vertically in an array, column by column. I think I've gotten quite far, but I can't get the numbers printed due to an incompatible types issue. The error is given for array[numb1][0]= word1.charAt(numb1);. The numb1 is not accepted here by java, how can I fix this?

import java.util.Scanner;
import java.util.Arrays;
import java.lang.String;

public class assignment51
{
   static void main()
  {
      Scanner read=new Scanner(System.in);
      System.out.println("Please enter the first of three words:");
      String word1= read.nextLine();

      System.out.println("Please enter the second of three words:");
      String word2= read.nextLine();

      System.out.println("Please enter the third of three words:");
      String word3= read.nextLine();

      int count1 = word1.length();
      int count2 = word2.length();
      int count3 = word3.length();


      int [] nums = new int [] {count1,count2,count3};
      int max = 0;
      for (int i = 0;i<nums.length;i++)
      {
          if (nums[i] >max)
          {
              max=nums[i];
            }
        }      

        max=max-1;
      String [][] array=new String[max][2];

      for (int numb1 = 0; numb1<(count1-1); numb1++)
      {
          array[numb1][0]= word1.charAt(numb1);
  }

        for (int numb2 = 0; numb2<(count2-1); numb2++)
      {
          array[numb2][1]= (word2.charAt(numb2));
  }

        for (int numb3 = 0; numb3<(count3-1); numb3++)
      {
          array[numb3][2]= (word3.charAt(numb3));
  }


}
}

Upvotes: 1

Views: 1401

Answers (2)

rgettman
rgettman

Reputation: 178333

The return of the charAt method is a char, but you are attempting to assign the char to an element of your 2D String array. You can't assign a char directly to a String; there is no such implicit conversion.

Because you are only assigning chars, change the datatype of array to a char[][].

Upvotes: 1

Mike Nakis
Mike Nakis

Reputation: 62130

You are trying to assign a character to a string. That won't work. Characters and strings are entirely different animals in Java.

Your array should be declared as char[][].

Upvotes: 1

Related Questions