Stacey
Stacey

Reputation: 1

Method that takes parameter and asks for month?

Write a method that takes a parameter for the number of a month and prints the month's name. You may assume that the actual parameter value passed to the method is always between 1 and 12 inclusive.

This method must be called monthName() and it must have an integer parameter.

Calling monthName(8) should print August to the screen.

You can call your method in the program's main method so you can test whether it works, but you must remove or comment out the main method before checking your code for a score.

I've been having a lot of trouble with this however I keep getting two errors- would anyone mind reading through my code and giving me corrections?

Errors: /tmp/sub-049616211/U5_L2_Activity_One.java:16: error: illegal initializer for String
{"January","February","March","April","May",
^

/tmp/sub-049616211/U5_L2_Activity_One.java:21: error: array required, but String found
System.out.println(months[month]);
public static void monthName(int month) {
    String months =
        { "January", "February", "March", "April", "May", 
        "June", "July", "August", "September", "October", "November", "December" };

    if (month <= 0 || month > 12) {
        System.out.println("That's not within the range 1 -12");
    } else {
        System.out.println(months[month]);
    }
}

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);

    System.out.println("Enter a number of Month:");

    int m = sc.nextInt();

    monthName(m);

    sc.close();
}

}

Upvotes: 0

Views: 1100

Answers (2)

Puce
Puce

Reputation: 38142

Errors: /tmp/sub-049616211/U5_L2_Activity_One.java:16: error: illegal initializer for String {"January","February","March","April","May", ^

/tmp/sub-049616211/U5_L2_Activity_One.java:21: error: array required, but String found System.out.println(months[month]);

Both error messages tell you, that you declared months as String, not String[].

Also consider to use the Month class.

Upvotes: 0

Stultuske
Stultuske

Reputation: 9437

On this line is your original error:

String months= {"January","February","March","April","May", "June","July","August","September","October","November","December"};

The object you have is an array of Strings, yet you declare it as a String. Change

String months= ....

to:

String[] months= ...

to indicate that months is an array, not a single String.

A second issue you'll have, in Java, arrays are 0 based:

if(month <= 0 || month > 12) {
    System.out.println("That's not within the range 1 -12");
}else {
    System.out.println(months[month]);
}

Now, once you type 1, you'll want "January" to be printed, but it won't. The correct index for January is 0. So, change the above to:

if(month <= 0 || month > 12) {
    System.out.println("That's not within the range 1 -12");
}else {
    System.out.println(months[month-1]);
}

Upvotes: 1

Related Questions