Java程序使用数组简单编码项目

我只想要“Jan支出”出现,但只有支出出来。 我该怎么做? Jan来自我的monthsArrays。 有什么遗漏?

import java.util.Scanner; public class Project { static int choice; public static void main(String[] args) { { Scanner input = new Scanner(System.in); System.out.println("***************Expenditure***************"); System.out.println("1)Enter monthly expenses"); System.out.println("2)Display detailed expenditure by month"); System.out.println("3)Quick glance at monthly expenses"); System.out.println("4)Exit"); System.out.println("Please select your choice :"); choice = input.nextInt(); switch (choice) { case 1: int count = 0; String[] monthsArray = { "", "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sept", "Oct", "Nov", "Dec" }; System.out.println("*******************************************"); System.out.println("\t\t\t\t"); System.out.print("Enter month :"); int month = input.nextInt(); for (int i=0; i < monthsArray.length; i++) String monthChoice = monthsArray[month - 1]; System.out.println("-------------------------------------"); System.out.println(monthChoice + "expenditure (max 10 items)"); 

这是我目前得到的输出

** * *** 支出 * ** * **

1)输入每月费用

2)按月显示详细支出

3)快速浏览每月费用

4)退出

请选择您的选择:1


输入月份:1


支出(最多10项)

输入第1项:

正如您所看到的,数组“Jan”没有出现。

monthsArray的外观monthsArray ,第一个元素是空字符串。 请记住,数组是从零开始的,并且您向用户询问了1到12之间的一个月(这很好,因为没有人认为1月是0,对吧?)。 稍后在您的代码中,您执行此操作:

 String monthChoice = monthsArray[month - 1]; 

但是,您的数组实际上包含13个元素,因为您添加了该空格,因此在您的情况下,您实际上可以安全地使用未更改的month索引,如下所示:

 String monthChoice = monthsArray[month]; 

或者,删除数组开头的空字符串,并保留monthChoice行(取决于您的实现应该如何工作。这纯粹是您的选择)。

一些附注:

您目前在switch语句的正文中声明了monthArray ,这是不必要的。 最好将它声明在方法的顶部,或者甚至更好,作为类中的常量,如下所示:

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

另外,这一行:

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

没用 我不知道这是否是未完成解决方案的一部分,但它所做的只是重复紧随其后的声明,据我所知,这是不必要的。 基本上它与此相同:

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

所以你应该安全地摆脱它。

您的代码中存在典型的+/- 1错误。

您的monthsArray在位置0处有一个空字符串,您从月份-1获取显示的字符串。 简单地输入2并获得“Jan支出(最多10项)”应该是一个很好的暗示。