java怎样输出数组中的前n个元素?

n 未知,例如第一次输出1个,第二次输出前2个。。。。。

import java.util.*;

public class Test {
public static void main(String[]args){
int[] arry = new int[]{1,2,3,4,5,6,7,8,9,0,2,4,3,6,5,9,6,5};
//这个数组是您自己定义的,有多少元素自己写就好
Scanner input =new Scanner(System.in);
System.out.println("请输入你想要输出,数组前几个元素:");
int a=input.nextInt();
if(a > arry.length){
System.out.println("个数大于数组长度");
}else{
for(int i = 0; i < a; i++){

System.out.print(arry[i]);
System.out.print(" ");
}

}
}
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2015-06-05
输入数据前n个只需要加个for循环
for(int i=0;i<n;i++) {
    System.out.println(数组[i]);
}

第2个回答  2011-02-23
public class Gamma {
public static void main(String[] args){
int[] arr = new int[]{1,2,3,4,5,6,7,8,9,0};
new Gamma().out(10, arr);
}

public void out(int n, int[] a){
if(n > a.length){
System.out.println("个数大于数组长度");
}else{
for(int i = 0; i < n; i++){
for(int j = 0; j <= i; j++){
System.out.print(a[j]);
System.out.print(" ");
}
System.out.println();
}
}
}
}
第3个回答  2011-02-23
两个for循环啊!
for(int 0;i<n.i++){
int j=i+1;
for(int x=0;x<j;x++)
System.out.println(a[x]);
}
第4个回答  2011-02-23
try{
for (int i = 0; i < n; i++){
System.out.println(a[i]);
}
}catch(Exception e ){}
相似回答