我有一个问题。我刚刚开始学习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("tt1. Add a number to the arrayntt2. Display the meanntt3. Display the median ntt4. Print the array to the screen ntt5. Print the array in reverse order ntt6. 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;
}
}
代码有问题。
问题是你的函数选项一个应该返回一个整数数组。您已将返回类型设置为单个整数。
其中之一需要改变
如果必须返回数组,我认为是这种情况,那么函数应该看起来像这样。
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;
}
干杯。