我想做一個菜單,用戶有一個選項可以將數字添加到數組中,從技術上講,他們可以添加多少個值,但一次只能添加一個。所以當他們選擇向數組添加數字時,他們會輸入一個數字,然後再次提示菜單。將數字添加到顯示陣列的數組&中時遇到問題。我會添加兩個數字&顯示數組看看它&我得到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);
}
}
}
Java不是JavaScript。你應該刪除這個問題的javascript標籤。 – chiliNUT
我究竟該如何解決這個問題?我希望用戶能夠完全控制陣列的大小,等等。 – user3230008