2014-02-09 95 views
0

我想做一個菜單,用戶有一個選項可以將數字添加到數組中,從技術上講,他們可以添加多少個值,但一次只能添加一個。所以當他們選擇向數組添加數字時,他們會輸入一個數字,然後再次提示菜單。將數字添加到顯示陣列的數組&中時遇到問題。我會添加兩個數字&顯示數組看看它&我得到30000000000000000000000000000000000000000000000000000000000因爲我的數組最大,我想。我想要的只是添加我輸入數組時輸入的數字&繼續從那裏進行。Java Array初學者菜單

我該如何解決這個問題?我希望用戶擁有完全控制陣列將多大等

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

Java不是JavaScript。你應該刪除這個問題的javascript標籤。 – chiliNUT

+0

我究竟該如何解決這個問題?我希望用戶能夠完全控制陣列的大小,等等。 – user3230008

回答

0

嘛newNum方法看起來很可疑。由於循環計數器測試將檢查<,因此循環僅進行一次。我將始終爲0,並且您將始終將新數字添加到數組中的[0]位置。您沒有「當前索引」變量來跟蹤您當前在數組中的位置。該數組將是1 int,其餘的值將是0 - 這看起來像你在發佈中包含的內容。

+0

我究竟該如何解決這個問題?我希望用戶能夠完全控制數組的大小等。 – user3230008

+0

爲什麼不使用整數列表 - 您可以繼續向列表中添加數字,並在需要執行一些計算後重複列表它。目前,您的固定大小爲99. – mikemil

+0

它用於數組賦值。 – user3230008