Java Array初学者菜单

时间:2014-02-09 01:31:16

标签: java arrays

我正在尝试制作一个菜单,用户可以选择在数组中添加数字,从技术上讲,他们可以一次添加一个他们想要的值。所以当他们选择在数组中添加一个数字时,他们会输入一个数字,然后再次提示菜单。我在将数字添加到阵列和放大器时遇到了问题。显示数组。我会添加两个数字&显示数组以查看它&我想,因为我的数组最大值,我得到300000000000000000000000000000000000000000000000000000000000000。我想要的只是当我想输入它时它只添加我输入到数组的数字&继续那样做。

虽然我怎么解决这个问题?我希望用户能够完全控制数组的大小等等。

import java.util.*;

public class arrayMenu
{
   public static void main(String[] args)
   {
      Scanner kb;
      int option;
      kb = new Scanner(System.in);
      option = menu(kb);
      int[] myArray = new int[99];

      while (option != 6)
      {
         switch (option)
         {
            case 1:
               myArray = newNum(kb, myArray);
               break;
            case 2:
               display(myArray);
               break;
            case 3:

               break;
            case 4:

               break;
            case 5:

               break;
         }
         option = menu(kb);
      }
      if (option == 6)
      {
         System.out.println();
         System.out.println("Thank you. Have a nice day.");
      }
   }
   public static int menu(Scanner kb)
   {
      int myOption = 0;
      while (myOption != 1 && myOption != 2 && myOption != 3 && myOption != 4 && myOption != 5 && myOption != 6)
      {
         System.out.println();
         System.out.println("Please select from the following menu choices.");
         System.out.println();
         System.out.println("1. Add a number to the array \n2. Display the mean \n3. Display the median \n4. Print the array to the screen \n5. Print the array in reverse order \n6. Quit");
         System.out.println();
         System.out.print("Choice --> ");
         myOption = kb.nextInt();
         kb.nextLine();
         if (!(myOption == 1 || myOption == 2 || myOption == 3 || myOption == 4 || myOption == 5 || myOption == 6))
            System.out.println("I am sorry that is an invalid menu choice.\nPlease try again"); 
      }
      return myOption;
   }
   public static int intNum(Scanner kb)
   {
      int num = -1;
      while (!(num >= 0))
      {
         System.out.print("Please enter a non-negative integer -->");
         num = kb.nextInt();

         if (num < 0)
            System.out.print("I am sorry that is not a non-negative integer.  \n");
      }
      return num;
   }
   public static int[] newNum(Scanner kb, int[] array) 
   {  
      for (int i = 0; i < 1; i++) 
      { 
         System.out.print("Please enter a number:"); 
         array[i] = kb.nextInt(); 
      } 
      return array;
   }
   public static void display(int[] array)
   {
      for (int myValue : array)
      {
         System.out.print(myValue);
      }
   }

}

1 个答案:

答案 0 :(得分:0)

newNum方法看起来很有问题。由于循环计数器测试检查&lt;循环仅循环一次。 1.我将始终为0,您将始终将新数字添加到数组中的[0]位置。您没有“当前索引”变量来跟踪数组中当前位置的位置。该数组将为1 int,其余值为0 - 这与您在发布中包含的内容类似。