如何避免这个java代码的额外输出

时间:2015-07-30 11:46:53

标签: java methods while-loop return

请注意:在仔细阅读之前,请不要只是将此问题视为否定。

输入:

This is for Matra Processing  0 3 3 3 0 0 2 2 0 0

需要输出:

This is for Matra Processing  0 3 0 0 0 0 0 0 0 0 
This is for Matra Processing  0 3 3 0 0 0 0 0 0 0 
This is for Matra Processing  0 3 3 3 0 0 0 0 0 0 
This is for Matra Processing  0 3 3 3 0 0 2 0 0 0 
This is for Matra Processing  0 3 3 3 0 0 2 2 0 0 

产生的输出:

import java.util.Arrays;

public class RaniMsc {

    public static void doPrint(int[] tt, String varnan) {   
        System.out.printf("\n%s ", varnan); 
        for (int q : tt) {
             System.out.printf("%d ", q);   
        } 
    }

    public static void rangeSetValue(int[] foo, int index_1, int index_2) { 
        for(int i = index_1; i < index_2; i++) {
            foo[i]=index_2-index_1;

            doPrint(foo, "This is for Matra Processing ");  
        }  
    } 

    public static void main(String[] args) {
        int[] rani = {0,1,2,3,0,0,1,1,0,0};
        int[] um = {0,0,0,0,0,0,0,0,0,0};

        int i = 0, j = 0, k = 0;
        while (i <rani.length) {
            if (rani[i] != 0) {
                j = i;  
                while (i < rani.length) {
                    if (rani[i] == 0) {
                        k=i;
                        break;
                    } else {
                        i++;
                    } 
                }   
                rangeSetValue(um, j, k);   
            } else {
                i++;
            }  
        } 
    }    
}     

我只需要上面输出的5行中的最后一行。作为编程和java的新手,我需要帮助才能将最后一行作为输出。

完整的代码是:

{{1}}

1 个答案:

答案 0 :(得分:2)

如果您希望仅打印一次输出,请在循环后调用仅输出一次输出的方法:

  for(int i=index_1; i<index_2; i++)  {
      foo[i]=index_2-index_1;
   }
   doPrint(foo, "This is for Matra Processing ");

编辑:

我不能说我理解主方法中循环的目的是什么,但由于你多次调用rangeSetValue,你会得到多个输出行。< / p>

您可以将调用移动到将输出打印到main方法的方法。

即。 :

不要在这里打印任何内容:

public static void rangeSetValue(int[] foo, int index_1, int index_2) { 
    for(int i = index_1; i < index_2; i++) {
        foo[i]=index_2-index_1;
    }  
} 

打印主要末尾的输出:

public static void main(String[] args) {
    int[] rani = {0,1,2,3,0,0,1,1,0,0};
    int[] um = {0,0,0,0,0,0,0,0,0,0};

    int i = 0, j = 0, k = 0;
    while (i <rani.length) {
        if (rani[i] != 0) {
            j = i;  
            while (i < rani.length) {
                if (rani[i] == 0) {
                    k=i;
                    break;
                } else {
                    i++;
                } 
            }   
            rangeSetValue(um, j, k);   
        } else {
            i++;
        }  
    } 
    doPrint(um, "This is for Matra Processing "); // print the output here
}