[英]Adding integers of array upto some number (java)
我有一個java問題。
我有兩個int[]
數組: cdn
和cmn
。
cdn
是{1,1,1,1,1,1,2,1,1,1,1,1,1,2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}
cmn
是{8,8,16}
我需要一個程序,它將cdn[]
的連續整數添加到cmn[init]
並返回添加中使用的整數。 然后它繼續從cdn[]
的下一個整數添加到cmn[init+1]
並返回整數。 對於上面的數組,這樣做了3次:第一次返回值是7,第二次是7,第三次是16.可以收集整數的數量和int[]
,即{7,7,16}
。 我的代碼是:
int numofints = 0;
int init = 0;
int plus = 0;
while(init < m2){
for(int j = 0; j < cdn.length; j++){
plus += cdn[j];
numofints++;
if(plus == cmn[init]){
init++;
}
}
}
System.out.print(numofints);
其中m2
是cmn
的大小,在這種情況下是3。 請注意,我的程序開始從cdn
的開頭cdn
遍地循環,因為j = 0
。 我希望它從前一次結束的地方開始! 我希望你有一個解決方案。
比約恩
只需將j
拉出外循環,並使用一段while
不是for
,用於內循環
你還需要在循環中plus = 0
public class T {
public static void main(String[] args) {
int[] cdn = {1,1,1,1,1,1,2,1,1,1,1,1,1,2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1};
int[] cmn = {8,8,16};
int numofints = 0;
int init = 0;
int m2 = 3;
int j = 0;
while(init < m2){
int plus = 0;
while(j < cdn.length){
plus += cdn[j];
j++;
numofints++;
if(plus == cmn[init]){
init++;
System.out.println(j);
break;
}
}
if (j == cdn.length) break;
}
}
}
if(plus == cmn[init]){
是if(plus >= cmn[init])
不要? 如果你完全改變cdn並且“plus”碰巧超過“cmn [init]”,你的代碼就會破壞。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.