因此,我正在處理一個項目,這一步要求我編寫一個要求輸入數字的程序,當輸入「-1」時,它將計算除-1之外的所有輸入數字的總和。我只是通過在循環後添加+1來解決這個問題,但我確定有另一種「正確」的方式來做這件事,我想學習如何。如何正確計算總和而不使用sum ++;?
任何幫助表示讚賞。 (注意:我一直在學習Java大約一週,所以請使用ELI5)
public static void main(String[] args) {
// program in this project exercises 36.1-36.5
// actually this is just one program that is split in many parts
Scanner reader = new Scanner(System.in);
int numbertyped = 0;
int sum = 0;
System.out.println("Type numbers: ");
while (numbertyped != -1) {
numbertyped = Integer.parseInt(reader.nextLine());
sum = sum + numbertyped;
}
sum++;
System.out.println("Thank you and see you later!");
System.out.println("The sum is " + sum);
編輯:我的程序現在已經完成。我使用了在while循環中添加中斷的解決方案,並添加了我想要的其他功能之後,這是最終產品:(如果有人有關於如何改進我的代碼或使其更高效的提示,請發表評論!)
import java.util.Scanner;
public class LoopsEndingRemembering {
public static void main(String[] args) {
// program in this project exercises 36.1-3
// actually this is just one program that is split in many parts
Scanner reader = new Scanner(System.in);
int numbertyped = 0;
int sum = 0;
int howmany = 0;
int evencounter = 0;
int oddcounter = 0;
System.out.println("Type numbers: ");
while (true) {
numbertyped = Integer.parseInt(reader.nextLine());
if (numbertyped == -1)
{
break;
}
if (numbertyped % 2 == 0)
{
evencounter++;
}
else
{
oddcounter++;
}
sum = sum + numbertyped;
howmany++;
}
double average = (double) sum/howmany;
System.out.println("Thank you and see you later!");
System.out.println("The sum is " + sum);
System.out.println("How many numbers: " + howmany);
System.out.println("Average: " + average);
System.out.println("Even numbers: " + evencounter);
System.out.println("Odd numbers: " + oddcounter);
}
}
快速,但稍微糟糕的解決方案是...'int sum = 1'在開始。您可以在增加總和之前添加if語句。 – byxor
我最終在添加總和之前使用了帶有中斷的if語句。 –