请注意:在仔细检查之前,请勿将此问题点击为否定。
输入:
int[] rani = {0,1,2,3,0,0,1,1,0,0};
int[] um = {0,0,0,0,0,0,0,0,0,0};
所需输出:
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
我只需要上述输出的 5 行中的最后一行。作为编程和 java 新手,我需要帮助才能仅获取最后一行作为输出。
完整代码为:
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++;
}
}
}
}
最佳答案
如果您希望输出仅打印一次,请在循环之后调用仅打印输出一次的方法:
for(int i=index_1; i<index_2; i++) {
foo[i]=index_2-index_1;
}
doPrint(foo, "This is for Matra Processing ");
编辑:
我不能说我理解 main 方法中循环的目的,但由于您多次调用 rangeSetValue
,因此您会得到多个输出行。
您可以将对打印输出的方法的调用移至主方法。
即:
不要在这里打印任何内容:
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;
}
}
在 main 末尾打印输出:
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
}
关于java - 如何避免此 java 代码的额外输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31722935/