如果数组为空则向用户打印消息

Printing message to user if array is empty

编辑 我应该将每个变量的 setter 方法放在我的主要方法中的什么地方?

我在 java 中遇到一些数组问题。我正在制作一个应用程序,用户通过选择选项 1 向菜单添加输入,我正在为其使用 switch 语句。这个数组需要所有其他开关案例都可以访问,所以我在案例 1 之外声明了它:

    //Menu loop
    //variable & array declaration
     int myMonths[] = new int[amountOfProjects];
     int index = 0;
     int num;

    while(choice !=6){ //while option 6 is not chosen keep showing the menu

       switch (choice){

            case 1:

数组长度是用户希望在应用程序中存储的项目数量。对于案例 2,我需要显示数组索引的 elements/value。如果到目前为止用户还没有输入任何内容,它应该显示一条消息说明这一点。这是我的代码:

            case 2:

            if(myMonths.length > 0){
                 // print the values
                for(int i=0; i < myMonths.length; i++){
                    System.out.println(myMonths[i] + " ");
                 }

             }else {
              System.out.println("No values entered");
            }
             break;         

问题 我的代码不会在情况 2 中执行 else 语句。它只是打印出用户分配的数组长度的零,所以我猜我只是要求它检查数组长度而不是元素。如果数组为空,有没有办法让代码执行错误语句?

添加 我不确定这是否重要,但我在数组的单独文件上使用了 setter 方法:

public class MenuTestClass{


 private int myMonths[];

 public MenuTestClass(){
    myMonths = new int[5];
    }
 public MenuTestClass(int[] myMonths){
   this.myMonths = myMonths;
   }
 public void setMyMonths(int[] values){ //declare setter method
   myMonths = values;
   }

提前致谢!到目前为止你们都对我很有帮助。

更新:

 int myMonths[] = new int[amountOfProjects];
     int index = 0;
     int num;

    while(choice !=6){ //while option 6 is not chosen keep showing the menu

       switch (choice){

            case 1:

            int n = 1;    //int n = number of projects
            Scanner sc = new Scanner(System.in);

           //myMonths = new int[amount];

            System.out.println("** Only projects with a duration between 2 and 12 months can be included **");
            System.out.println("What was the duration of your projects in months?");

              for(int i=0; i<1; i++){
               int a = sc.nextInt();

                //display error message
               if((a < 2) || (a > 12)){
                System.out.println(" Please enter an amount between 2 and 12 months. ");}

               //add to the array
               else{myMonths[index++] = a;}
               }

             calc.setMyMonths(myMonths); //creating the object
             break;


            case 2:

            if(myMonths.length > 0){
                 // print the values
                for(int i=0; i < myMonths.length; i++){
                    System.out.println(myMonths[i] + " ");
                 }

            } else {

                  System.out.println("No values entered");

     }
        break;

            case 3:
            //display all elements with the same state
            //get number user wishes to search for

            boolean found = false;
             Scanner input = new Scanner(System.in);
             System.out.print("Please enter the number you wish to search for");

             //read user input
             num = input.nextInt();

             //traverse array
             int k = 0;
             for(k=0; k < myMonths.length; k++){
                 if(myMonths[k] == num){
                     found = true;
                     System.out.println("Your value has been found at the following indices: " + k);
                      }

                 }


                 if(!found){System.out.println("not found");}

            break;


            //display averages
            case 4:
            System.out.println("Choice 4 selected\n");

            // processing: invoke/call the method calculateAverage() to calculate the average value of the array's elements
            calc.calculateAverage();

            // output
            // use the getter method getAverageCanBeCalculated() to retrieve the value which shows if the average could be calculated
            boolean isMenuCalculated = calc.getAverageCanBeCalculated();
            if (isMenuCalculated){ // average has been calculated (i.e. there were numbers in the array)
                    double avg = calc.getAverage();// use the getter method to retrieve the average value
                        // display the average value
                        System.out.println("average is: " + avg);
                    }
                    else { // the instance variables f the
                        System.out.println("the object's array instance variable has no numbers (i.e. empty array)");
                        }
                break;




            case 5:

            //invoke/call the method calculateMax() to calculate the maximum element of the array
            calc.calculateMax();

            // use the getter method to retrieve the maximum value
            int max = calc.getMax();
            // display the maximum value
            System.out.println("maximum is " + max);
            break;

            default:
             System.out.println("Please enter a valid number");

            }

             //display menu again
             displayMenu();
             //Get user choice
             choice = in.nextInt();

     }

您可以通过三种方式处理此问题,

  1. 使用 apache 库

    进口org.apache.commons.lang.ArrayUtils;

    ArrayUtils.isEmpty(我的月数);

2).每当将值输入到数组中时,使用布尔标志并将其设置为 true。这样你就可以检查那个标志了。

3).遍历数组,检查数组中的值是否不为0。

如果您需要进一步的帮助,请告诉我。

您确定这些值正在更新吗?根据发布的代码,“while(”循环没有退出条件。而且似乎没有办法完成循环。

我建议在 while 循环开始后添加一个 printout/breakpoint 以查看您的“选择”是否实际更新。

...
while (choice != 6) { // while option 6 is not chosen keep showing the menu
    System.out.println(choice);
...