简体   繁体   中英

Java: Getting a desired print/output from my custom method

I am studying Java with a help of online tasks and was messing around with methods. The goal is to write a program that uses a method which has a year, month, day and an out print form as parameters. Then the program prints the entire date using the chosen format. With the formats, I mean something like, normal: 10. July 2016 / shorten: 10.07.2016 / official: 10-07-16

My problem is I am not entirely sure how would I do this, but so far I have made it this far I have been trying to use String arrays for the normal format but can't seem to get it work.

EDIT: I got it kind of working as intented, but it still has some minor issues such as the last userinput is alos printed at the end and I dont seem to get thrid format (offical) quite work as intented as its not printin the 0s infront of the values under 10.

Sorry if It's not easy to understand what I am trying to say, English is not my native language.

Thank you

public static int returnCorrectFormat(int year, int month, int day, int format) {

        switch(format) 
    { 
        case 1: 
                switch (month)
                {
                    case 1: System.out.println(day +"." + " January " + year); 
                        break;
                    case 2: System.out.println(day +"." + " February " + year); 
                        break;
                    case 3: System.out.println(day +"." + " March " + year); 
                        break;
                    case 4: System.out.println(day +"." + " April " + year); 
                        break;
                    case 5: System.out.println(day +"." + " May " + year); 
                        break;
                    case 6: System.out.println(day +"." + " June " + year); 
                        break;
                    case 7: System.out.println(day +"." + " July " + year); 
                        break;
                    case 8: System.out.println(day +"." + " August " + year); 
                        break;
                    case 9: System.out.println(day +"." + " September " + year); 
                        break;
                    case 10: System.out.println(day +"." + " October " + year);  
                        break;
                    case 11: System.out.println(day +"." + " November " + year);  
                        break;
                    case 12: System.out.println(day +"." + " December " + year); 
                        break;
                    default:
                        break;
                }
            break;  

        case 2:
                System.out.println(day + "." + month +  "." + year);
                break;

        case 3: if(( day < 10) && (month < 10))
            {
                System.out.println(year + "-" + "0" + month +  "-" + "0" + day);
            }

        else{
                System.out.println(year + "-" + month +  "-" + day);
            }   
    }   
    return format;
}


public static void main(String[] args) {

    try{

        int printableInfo;
        int year;
        int date;
        int month;
        int format;

        System.out.println("The programm will ask you to input year,date, month and then choose a format for printing.");
        System.out.println("Insert year: ");
        year = input.nextInt(); 

        System.out.println("Insert date: ");
        date = input.nextInt(); 

        System.out.println("Insert month: ");
        month = input.nextInt(); 

        System.out.println("Choose format: [1] normal [2] shorten [3] official ");
        format = input.nextInt(); 

        printableInfo = returnCorrectFormat(year,date,month,format);
        System.out.println(printableInfo);
    }
    catch (Exception e) 
    {
        System.out.println("ERROR: closing program..");
        System.exit(1);
    }
}

OK, the OP is lacking a bit information as to what you are trying to do exactly but anyway.

Consider the following:

1) Your returnCorrectFormat method should not return an int. The method should take all the parameters needed to format the date accordingly and then proceed to return a String with the formatted date.

2) As stated above using a HashMap will be quiet efficient for what you want to do.

More specifically:

1) You'll need a method that will return a hashmap with key - object values like so:

1, "January" and so on.

The values needed to create this hashmap will be a hardcoded String array with months' names and a hardcoded int array with the months' number that'll server as the maps key.

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

    int[] numMothns = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};

Both those array will be place in you main method. After this you'll need the method that will create the actual HashMap.

public static HashMap<Integer, String> initMonthMap (int[] numM, String[] m) {
        HashMap<Integer, String> monthsMap = new HashMap<>();

        for (int i = 0; i <= numM.length i++) {
            for (int j = 0; j <= m.length; j++){
                monthsMap.put(numM[i], m[i]);
            }
        }

        return monthsMap;
    }

This will effectively loop both arrays and put the key - value you'll need in the new HashMap and then return back to it's caller. You'll be needing to call this method from your main method after the declaration of your variables.

Then you'll need to make some minor alterations in your formatter method. More specifically, instead of return an integer (why would you do that in the first place?) you'll be returning a String. You can use a StringBuilder in order to create your new String. Also the method's signature will be changed to include the hashMap in it's parameter list.

Furthermore, now in case of the 'normal' format you'll just be retrieving the name of the month based on the it's key (ie that is the number of the month).

public static String formatDate(int format ,int year, int month, int day, HashMap<Integer, String> monthsMap) {
        StringBuilder sb = new StringBuilder();

        switch (format) {
            case 1:
                sb.append(day + " " + month + " " + year);
                break;
            case 2:
                sb.append(day + "." + month + "." + year);
                break;
            case 3:
                sb.append(day + " " + monthsMap.get(month) + " " + year);
                break;
        }
        return sb.toString();
    }

These are more or less the changes you'll be requiring to make in order to have this work.

You can use a HashMap<> for your "normal" format, each number from 1 to 12 would be a key and the values would be the corresponding months. example:

HashMap<Integer, String > monthMap = new HashMap<>();
monthMap.put(5,"May");

java.time

You can use the java.time classes built into Java 8 and later to do this. Search Stack Overflow for thousands of examples.

If those formats are defined as cultural norms for a particular locale, then let java.time automatically localize for you.

First define a DateTimeFormatter with a particularLocale and a FormatStyle .

DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDate( FormatStyle.MEDIUM );
Locale locale = Locale.CANADA_FRENCH;
formatter = formatter.withLocale( locale );

Next, apply to a date value.

LocalDate localDate = LocalDate.of( 2016 , Month.JULY , 10 );
String output = localDate.format( formatter );

Again search Stack Overflow as your Question is really a duplicate of many others. If this is a homework exercise so you really do not want to use a library to assist, you should say so in your Question.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM