首先,我是Java的初学者。在这个中等简单的程序中,我需要使用对象实例构造OneDimensionalArrays
类的实例,调用createIntegers
来创建一个整数数组。
我无法弄清楚如何从我的主要文件中允许用户输入他们希望创建的数组的大小,并使用OneDimensionalArray
和printArray
方法创建用户想要的数组和大小
package one_dimensional_array;
import java.util.Scanner;
public class OneDimensionalArrays {
static int[] createIntegers(int size_of_array)
{
int myArray[];
myArray = new int [10];
myArray[0] = 0;
myArray[1] = 100;
myArray[2] = 200;
myArray[3] = 300;
myArray[4] = 400;
myArray[5] = 500;
myArray[6] = 600;
myArray[7] = 700;
myArray[8] = 800;
myArray[9] = 900;
return myArray;
}
void printArray(int[] myArray)
{
for(int i = 0; i < myArray.length; i++){
System.out.println(i);
}
}
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter size of array to create: ");
int num = keyboard.nextInt();
}
}
答案 0 :(得分:0)
您可以通过执行以下操作让用户定义数组的大小:
static int[] createIntegers(int size_of_array)
{
int[] myArray= new int [size_of_array];
//You can use this to allow the user to set each element with the value
//that they want
for(int ii = 0; ii < myArray.length; ii++){
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter array value for element " + ii + ": ");
int num = keyboard.nextInt();
myArray[ii] = num;
}
return myArray;
}
static void printArray(int[] myArray)
{
//Check to make sure the array has values to prevent errors
if((myArray.length != 0) && (myArray != null)){
for(int i = 0; i < myArray.length; i++){
System.out.println("Array Value: " + myArray[i]);
}
}
}
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter size of array to create: ");
int num = keyboard.nextInt();
//Call the static method, returning the results
int[] myArray = OneDimensionalArrays.createIntegers(num);
//Close scanner
keyboard.close();
//Pass results into static method to be printed out
OneDimensionalArrays.printArray(myArray);
}
这也会打印出数组的结果。这是一个示例输出:
输入要创建的数组大小:5
输入元素0的数组值:1
输入元素1的数组值:2
输入元素2的数组值:3
输入元素3的数组值:4
输入元素4的数组值:5
数组值:1
数组值:2
数组值:3
数组值:4
数组值:5
注意,使用静态方法不使用对象实例。静态方法是可以在不创建对象的情况下使用的方法。