Java program using arrays simple coding for project

后端 未结 2 1231
渐次进展
渐次进展 2021-01-29 16:02

I just want \"Jan Expenditure\" to appear however only expenditure comes out. How do I do it? Jan is from my monthsArrays. Is there anything missing?

import java         


        
2条回答
  •  有刺的猬
    2021-01-29 16:37

    From the looks of your monthsArray, the first element is a blank string. Remember that arrays are zero-based, and you asked your user for a month between 1 and 12 (which is fine, because nobody thinks of January as month 0, right?). Later in your code, you do this:

    String monthChoice = monthsArray[month - 1];
    

    However, your array actually contains 13 elements, because you added that blank space, so in your case, you're actually safe to simply use the unaltered month index, like so:

    String monthChoice = monthsArray[month];
    

    OR, get rid of the empty string at the beginning of the array, and leave your monthChoice line as is (depends on how your implementation is supposed to work. That is purely your choice).

    Some side notes:

    You are presently declaring your monthArray in the body of the switch statement, which is unnecessary. It would be better to declare it at the top of the method, OR even better, as a constant in the class, like so:

    private static final String[] monthsArray = { "", "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sept", "Oct", "Nov", "Dec" };
    

    Also, this line:

    for (int i=0; i < monthsArray.length; i++)
    

    is useless. I don't know whether this is part of an unfinished solution, however all it is doing is repeating the statement that immediately follows it, which as as far as I can tell, is unnecessary. Basically it is the same as this:

    for (int i=0; i < monthsArray.length; i++){
        String monthChoice = monthsArray[month - 1];
    }
    

    So you should be safe to get rid of it.

提交回复
热议问题