0
我是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]);
}
}
替換此代碼,我想你也應該出臺我dea的方法應該爲程序員節省時間,否則就是一個非常簡潔的答案! – Jerrybibo