我有一个问题。我刚开始学习java中的数组。我理解数组以及它们的工作方式,以及存储数据的程度。但这是我的问题,我试图通过使用菜单向数组添加现有的整数。但是,我不明白为什么我的程序似乎不起作用。
import java.util.Scanner;
public class ArraySorting
{
public static void main(String[] args)
{
int option;
int integer = 0;
int optionOne;
Scanner kb = new Scanner(System.in);
System.out.println("Please enter a non-negative integer: ");
integer = kb.nextInt();
while((integer < 0))
{
System.out.println("I am sorry that is not a non-negative integer.");
System.out.println("");
System.out.println("Please enter a non-negative integer: ");
integer = kb.nextInt();
}
option = displayMenu(kb);
while (option != 6)
{
switch (option)
{
case 1:
optionOne();
System.out.println("Done with Option 1. Please enter another option.");
break;
case 2:
//optionTwo();
System.out.println("Done with Option 2. Please enter another option.");
break;
case 3:
//optionThree();
System.out.println("Done with Option 3. Please enter another option.");
break;
case 4:
//optionFour();
System.out.println("Done with Option 4. Please enter another option.");
break;
case 5:
//optionFive();
System.out.println("Done with Option 5. Please enter another option.");
break;
}
option = displayMenu(kb);
}
if (option == 6)
{
System.out.println();
System.out.println("Thank you. Have a nice day.");
}
}
private static int displayMenu(Scanner kb)
{
int option = 0;
while (option != 1 && option != 2 && option != 3 && option != 4 && option !=5 && option !=6)
{
System.out.println("\t\t1. Add a number to the array\n\t\t2. Display the mean\n\t\t3. Display the median \n\t\t4. Print the array to the screen \n\t\t5. Print the array in reverse order \n\t\t6. Quit");
option = kb.nextInt();
if (!(option == 1 || option == 2 || option == 3 || option == 4 || option == 5 || option == 6))
System.out.println("I am sorry that is an invalid choice. Please try again.");
}
return option;
}
private static int optionOne()
{
Scanner input = new Scanner(System.in);
int[] numbers = new int[99];
for (int i = 0; i < numbers.length; i++)
{
System.out.println("Please enter number");
numbers[i] = input.nextInt();
}
return numbers;
}
}
答案 0 :(得分:1)
代码有问题。
事情是你的函数optionOne应该返回一个整数数组。您已将返回类型设置为单个整数。
其中一个需要改变
如果必须返回数组,我认为是这种情况,那么函数看起来应该是这样的。
private static int[] optionOne()
{
Scanner input = new Scanner(System.in);
int[] numbers = new int[99];
for (int i = 0; i < numbers.length; i++)
{
System.out.println("Please enter number");
numbers[i] = input.nextInt();
}
return numbers;
}
干杯。