java比较二维数组每一列最小值并输出到一维数组中去。

别找百度那个{1,5,3}那个,现在是{1,2,3}{4,5}最小值输出到一维数组中去结果为{1,4}。

import java.util.Arrays;

public class MyDemo {
public static void main(String[] args) {
int[][] arys = { { 1, 2, 3 }, { 4, 5 }};//二维数组
int[] min = new int[arys.length];//一位数组的长度是和二维数组的长度一样
for (int i = 0; i < arys.length; i++) {//外循环, 每次是一行
int mintemp = arys[i][0];// 得到第i行的下标为0个元素假设他是最小值
for (int j = 1; j < arys[i].length; j++) {//然后从下标是1的元素开始循环比较
int temp = arys[i][j];
if(mintemp>temp){//如果比假设的最小值还要小. 那么就设置temp元素为最小值
mintemp=temp;
}
}
min[i]=mintemp;//存入一维数组中
}
System.out.print("{");//打印左边的花括号
for (int i = 0; i < min.length-1; i++) {//只循环到倒数第二个元素位置
System.out.print(min[i]+",");//输出元素,并追加逗号

}
System.out.print(min[min.length-1]+"}");//倒数第一个元素后面不需要追加逗号

//System.out.println("\n"+Arrays.toString(min)); 输出[1,4]
}
}

运行测试

{1,4}

结果截图

温馨提示:答案为网友推荐,仅供参考
第1个回答  推荐于2018-03-08
// 这样差不多满足要求了吧?
import java.util.Arrays;

public class GoGoGo {

public static void main(String[] args) {
int[][] arr2 = { {2, 1, 3 }, { 4, 5 }, {12, 111, 23, 999, 8, 998 } };
int[] result = new int[arr2.length];
int index = 0;
for (int[] arr : arr2) {
Arrays.sort(arr);
result[index++] = arr[0];
}
for (int x : result) {
System.out.println(x);
// Console :
// 1
// 4
// 8
}
}
}

追问

要求输出的结果为{1,4}

追答// 唉,看的我也是醉了。
// 我现在开始质疑自己,这种答题的方式真的好吗。
// 上面的例子,我特意多构造了一组数据,是想展示给你如何把程序做的更有扩展性。
// 而你仅仅只想要一份作业。
import java.util.Arrays;

public class GoGoGo {
 
    public static void main(String[] args) {
        int[][] arr2 = { {2, 1, 3 }, { 4, 5 }};
        int[] result = new int[arr2.length];
        int index = 0;
        for (int[] arr : arr2) {
            Arrays.sort(arr);
            result[index++] = arr[0];
        }
        for (int x : result) {
            System.out.println(x);
            // Console :
            // 1
            // 4
        }
    }
}

本回答被网友采纳
第2个回答  2015-11-26
public class Egg{
    public static void main(String[] args){
        int[][] arr = {
            {1,2,3},
            {4,5}
        };
        int[] dest = new int[0];
        for(int i = 0; i < arr.length; i++){
            int min = Integer.MAX_VALUE;
            for(int j = 0; j < arr[i].length; j++){
                min = arr[i][j] < min ? arr[i][j] : min;
            }
            int[] cloned = new int[dest.length + 1];
            System.arraycopy(dest,0,cloned,0,dest.length);
            cloned[cloned.length - 1] = min;
            dest = cloned;
        }
        for(int i = 0; i < dest.length; i++){
            System.out.print(dest[i] + " ");
        }
    }
}

追问

要输出到一维数组中去。。。

追答

dest就是我的一度数组,你如果这个都看不懂,就不要来追问我,
这个答案就送给你了,大白痴,而且只知道怀疑别人去百度的白痴。
KEEP FAR AWAY FROM ME

第3个回答  2015-11-26
int[][] a = {{4,5,2},{12,56,9}};

List list = new ArrayList();
int mm;
for (int i = 0; i < a.length; i++) {
mm = a[i][0];
for (int j = 0; j < a[i].length; j++) {
System.out.println(a[i][j]);

if(a[i][j]<mm){
mm = a[i][j];
}

}
list.add(mm);
}
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
相似回答