user2831805
user2831805

Reputation:

Passing a string array in a main method

I have homework where I have to write a small program that asks for a number and returns the month assigned to that number.

So far I have written two different classes, one to prompt the user for int, and the other with the arrays of month. Now my problem is to pass over the months to the main class when the user enters a number.

So far for the main class I have this and I have no idea on how to proceed... I get:

java:17: error: array required, but Date found System.out.println(monthName[index]); 

I tried to be as detailed as possible.

    import java.util.Scanner;

public class Driver {

    public static void main(String[] args)
    {
        Utility input = new Utility();
        final int MONTH_NAMES = 12;
        int[] month = new int[MONTH_NAMES];
        Date monthName = new Date();
        {
        System.out.println(input.queryForInt("Enter the number for a month ")) ;
        }


    for (int index = 0; index < 12; index++)
        System.out.println(monthName[index]);
}
}

Upvotes: 1

Views: 765

Answers (4)

Basil Bourque
Basil Bourque

Reputation: 338406

java.time.Month

Java has java.time classes for your date-time needs.

The Month enum defines an object for each of the months, January-December, numbered 1-12.

int monthNumber = … ;  // Solicit from user.
Month month = Month.of ( monthNumber ) ;

Generate localized text. Specify a Locale to determine the human language and cultural norms to be used in localizing. For English language, use en. For United States cultural norms, use US.

TextStyle style = TextStyle.FULL_STANDALONE ;  // How long or abbreviated.
Locale locale = Locale.of ( "fr" , "CA" ) ;    // French language, Canada cultural norms.
String output = month.getDisplayName ( style , locale ) ;

You said:

So far I have written two different classes, one to prompt the user for int, and the other with the arrays of month.

Java provides the second, java.time.Month. No need for you to write.

Month[] months = Month.values() ; 
someObject.someMethod ( months ) ;  // Pass array to method. 

Upvotes: 1

Stephanie Yang
Stephanie Yang

Reputation: 262

mouthName is a Date object, not an array. Also, why use a for loop to print out a whole year's mouth?

I think it can change the last for loop to System.out.printLn(mouthName.getMouth()) if the input.queryForIntmethod can successfully pass the int mouth to the mouthName object.

Upvotes: 0

I don't think you intended to use Date monthName here

System.out.println(monthName[index]);

Judging by the number of indexes your for loop is counting, it looks like you wanted to use int[] month.

System.out.println(month[index]);

Upvotes: 0

Tyler Iguchi
Tyler Iguchi

Reputation: 1074

Your System.out line is not referencing the array you named month.

Upvotes: 0

Related Questions