我是java的初学者。在我的程序中,我编写了随机n个数组的代码,偶数索引,奇数元素,反转元素,数组的第一个,最后一个元素。现在我想使用单独的方法实现我的程序。我该怎么办? 是什么?
public class Rand {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner (System.in);
System.out.print("Enter the number of values:");
int[] values = new int[input.nextInt()];
Random rand = new Random();
for (int i = 0; i < values.length; i++) {
int n = rand.nextInt(20);
values[i] = n;
}
System.out.print("Array: ");
for (int i = 0; i < values.length; i++) {
System.out.print( " " + values[i]);
}
System.out.println();
System.out.print("Even index: ");
for (int i = 0; i < values.length; i++) {
if (i % 2 == 0) {
System.out.print( " " +values[i]);
}
}
System.out.println();
System.out.print("Odd element:");
for (int i = 0; i < values.length; i++) {
if (values[i] % 2 != 0) {
System.out.print(" " + values[i]);
}
}
System.out.println();
System.out.print("Reverse order:");
for (int i = values.length - 1; i > -1; i--) {
System.out.print( " "+ values[i]);
}
System.out.println();
System.out.print("First, middle and last element:");
System.out.print(" " + values[0]);
if (values.length %2 ==0)
{
System.out.print(" " + values[(values.length /2)-1]);
System.out.print(" " + values[values.length /2]);
}
System.out.print( " " + values[values.length - 1]);
}
}
答案 0 :(得分:1)
好的示例您可以在main
Scanner input = new Scanner (System.in);
System.out.print("Enter the number of values:");
int[] values = new int[input.nextInt()];
Random rand = new Random();
for (int i = 0; i < values.length; i++) {
int n = rand.nextInt(20);
values[i] = n;
}
与
int[] values = getValues ();
getValues
看起来像
private static int [] getValues () {
Scanner input = new Scanner (System.in);
System.out.print("Enter the number of values:");
int[] values = new int[input.nextInt()];
Random rand = new Random();
for (int i = 0; i < values.length; i++) {
int n = rand.nextInt(20);
values[i] = n;
}
// lets also close the Scanner
input.close ();
return values;