3 回答

TA貢獻(xiàn)1824條經(jīng)驗(yàn) 獲得超6個(gè)贊
您的第一個(gè) for 循環(huán)是將數(shù)組中的每個(gè)索引分配給最新的輸入。您不需要嵌套 for 循環(huán)來(lái)完成此作業(yè)。這是一個(gè)帶有注釋的示例,解釋了代碼的不同方面。
Scanner in = new Scanner(System.in);
int[] numbersList = new int[10];
int amount = 0;
int total = 0;
do { //stop at negative
int number = in.nextInt();
if (number < 0) {
// if a negative number is entered then stop looping
break;
}
amount += 1;
// use modulo arithmetic to assign numbers, the accessed index will
// range from 0 to 9
numbersList[amount % 10] = number;
// iterate over numbersList and sum entries
for(int i = 0; i < numbersList.length; i++){
total += numbersList[i];
}
// output total
System.out.println(total);
// reset total to 0
total = 0;
} while(number >= 0); // this is redundant since we check earlier
System.out.println(total);

TA貢獻(xiàn)1852條經(jīng)驗(yàn) 獲得超7個(gè)贊
只需聲明
number
為int number;
,它就會(huì)自動(dòng)取值 0。無(wú)需詢(xún)問(wèn) Scanner。第一個(gè) int 永遠(yuǎn)不會(huì)被使用,因?yàn)槟阍?while 循環(huán)中請(qǐng)求另一個(gè) int。在第 n 輪中,您將用當(dāng)前輪數(shù)替換前 n+1 個(gè)整數(shù)(0 <= i <= n -> n+1 輪;改為使用
i < amount
)。如果您“玩”超過(guò) 9 輪,這將導(dǎo)致異常。每次替換單個(gè)整數(shù)后,您都會(huì)遍歷整個(gè)數(shù)組。請(qǐng)注意,該總數(shù)永遠(yuǎn)不會(huì)重置。
您并不是在輸入負(fù)數(shù)后立即停止,而是也用這個(gè)負(fù)數(shù)運(yùn)行一輪然后終止。
break;
因此,如果您發(fā)現(xiàn)結(jié)果是否定的,請(qǐng)使用 anumber
(因此,請(qǐng)?jiān)趶膾呙鑳x獲取結(jié)果后進(jìn)行測(cè)試)。
因此,您可以對(duì)以下數(shù)組求總和(省略尾隨 0):
[2] //2
[2,2] //2 + 2 + 2 = 6
[3,2] //6 + 3 + 2 = 11
[3,3] // 11 + 3 + 3 = 17
[3,3,3] // 17 + 3 + 3 + 3 = 26
[4,3,3] // 26 + 4 + 3 + 3 = 36
[4,4,3] // 36 + 4 + 4 + 3 = 47
[4,4,4] // 47 + 4 + 4 + 4 = 59
[4,4,4,4] // 59 + 4 + 4 + 4 + 4 = 75
[-1,4,4,4] // 75 - 1 + 4 + 4 + 4 = 86
[-1,-1,4,4] // 86 - 1 - 1 + 4 + 4 = 92
[-1,-1,-1,4] // 92 - 1 - 1 - 1 + 4 = 93
[-1,-1,-1,-1] // 91 - 1 - 1 - 1 - 1 = 89
[-1,-1,-1,-1,-1] // 89 - 1 - 1 - 1 - 1 - 1 = 84

TA貢獻(xiàn)1858條經(jīng)驗(yàn) 獲得超8個(gè)贊
下面的代碼也有效。
ArrayList<Integer> numbersList = new ArrayList<>();
Scanner in = new Scanner(System.in);
int number = in.nextInt();
int total = 0;
while (number>=0) { //stop at negative
//store all numbers in ArrayList
numbersList.add(number);
//for the first 10 numbers we can just add them as follows
if(numbersList.size()<=10) {
total += number;
System.out.println(total);
}
//if user imputs more than 10 numbers we need to count the total of the last 10 numbers so:
else
{
//Restore total to 0 for recount
total =0;
//iterate Arraylist backwards for the last 10 values inputed in it
for(int j = 10; j >=1 ; j--) {
total += numbersList.get(numbersList.size()-j);
}
System.out.println(total);
}
//get next number
in = new Scanner(System.in);
number = in.nextInt();
}
System.out.println(total);
添加回答
舉報(bào)