user2883800
user2883800

Reputation: 145

Repeat error message when adding an array

I have been working on java since first week of october and I can't seem to continue this problem. I fix one problem and another keeps showing up. I am using Blue J and I am trying to add an array to the responses array. here is the code:

public class eDiary{
    public static void main (String args[]){
        int [] days = {1,2,3,4,5,6,7};
        String [] responses;
        int i = 0;

        for(i=0; i<7; i++){
            String response = Console.readString("What is your major event for day " + days[i]);
            responses[responses.length] = responses;

        }
    }


}

I am trying to make the user type in a major event for the day. Each event is supposed to add itself to the responses array as it corresponds to the days array (response 1 corresponds to day 1) I am not finished with the code but this is part one. The error keeps mentioning incompatible types on "responses[responses.length] = responses; How can I take care of this. There could be more errors as BlueJ seems to show them one at a time.

Upvotes: 0

Views: 169

Answers (2)

Bhanu Kaushik
Bhanu Kaushik

Reputation: 864

In the line

 responses[responses.length] = responses;

responses is an array. You can only assign a String

May be you want to do this

 responses[responses.length] = response;

In the context of the question

Recommended Changes :

  1. Also, you should use i instead of responses.length:

    responses[i] = response;

  2. Initialize responses:

    String [] responses;

    To->

    String [] responses = new String[7]; // Provided 7 is fixed length.

Upvotes: 5

Richard Tingle
Richard Tingle

Reputation: 17226

You never initialise responses, it is null at all times, most likely you want

String[] responses=new String[days.length]; //Assuming responses should be the same length as days

then you can add each response to this (now non null) array, so

   for(i=0; i<7; i++){
        String response = Console.readString("What is your major event for day " + days[i]);
        responses[i] = response; //Note response not responses

    }

Here you add a String into each of the 7 "boxs" of the array,

Upvotes: 1

Related Questions