2017-03-25 36 views
0

新的阵列我有这个数组: String[][] hej = {{"9.8", "0", "hi", "0"}, {"0", "3.4", "yes", "no"}};爪哇 - 创建无零

而且我想没有所有的零,以创建一个新的阵列。

我开始创建一个新的数组:

String[][] zero = new String[hej.length][hej[0].length];

我试图只插入不属于这个零for循环的元素:

for(int c = 0; c < zero.length; c++) { 
    int i = 0; 
    if(hej[i][c] != "0") { 
    zero[i][c] = hej[i][c]; 

但事实并非如此工作,我不明白为什么。

如果我这样做,没有一个循环是这样的: `如果(!HEJ [0] [0] = “0”) 零[0] [0] = HEJ [0] [0];

if(hej[0][1] != "0") 
    zero[0][1] = hej[0][1]; 

if(hej[0][2] != "0") 
    zero[0][2] = hej[0][2]; 

if(hej[0][3] != "0") 
    zero[0][3] = hej[0][3];` 

但是,我仍然不知道如何使阵列更短,没有去除零点。

  • 任何人都可以帮助我理解为什么我的for循环不起作用,以及如何使循环遍历整个[] []数组?

  • 任何人都可以帮助我理解如何同时创建一个没有零点的新动态数组?

谢谢!

+0

是你的标题应该说“数组”?你能过滤内部列表吗?如果你用for循环来做,你需要2个嵌套循环。第二个循环检查内部列表。 – Carcigenicate

+0

是的。抱歉。我可以编辑它吗? –

+0

你可以很容易。在您的帖子下按“编辑”。 – Carcigenicate

回答

0

任何人都可以帮助我理解为什么我的for循环不起作用以及如何让循环遍历整个[] []数组?

你必须迭代与两个循环二维数组像for inside a for loop如下

public static void eliminateZerosWithStaticArray() throws Exception { 
    String[][] hej = {{"9.8", "0", "hi", "0"}, {"0", "3.4", "yes", "no"}}; 
      int width = hej.length; 
      int height = hej[0].length; 
      String[][] zero = new String[width][height]; 

      for(int c=0; c < width; c++) { 
       for(int d=0,i=0; d<height; d++) { 
        if(!"0".equals(hej[c][d])) { 
         zero[c][i] = hej[c][d]; 
         i++; 
        } 
       } 
      } 
      System.out.println("Printing the values within zero array ::: "); 
      for(int i=0; i<zero.length; i++) { 
       for(int j=0; j<zero[i].length; j++) { 
        System.out.println("The values are : "+ zero[i][j]); 
       } 
      } 
    } 

任何人谁可以帮助我了解如何在同一时间创建一个新的 动态数组没有从零点?

这就是ArrayList成立的地方。这里是关于如何add elements to add elements dynamically into an array in java.

public static void eliminateZerosWithDynamicArray() throws Exception { 
     String[][] hej = {{"9.8", "0", "hi", "0"}, {"0", "3.4", "yes", "no"}}; 
     int width = hej.length; 
     int height = hej[0].length; 
     List<List<String>> result = new ArrayList<List<String>>(width); 

     //Iterate the original array 
     for(int c=0; c < width; c++) { 
      List<String> templist = new ArrayList<String>(); 
      for(int d=0; d<height; d++) { 
       if(!"0".equals(hej[c][d])) { 
        templist.add(hej[c][d]); 
       } 
       result.add(templist); 
      } 
     } 
     //Print the list content 
     for(int c=0; c<result.size(); c++) { 
      System.out.println("List content : "+result.get(c)); 
     } 
    }