我正在针对Java进行MOOC练习36。我必须创建一个偶数和奇数计数器,但是我的偶数和非计数器显示错误的值。一切正常,期望这个计数器,我不确定为什么。
另一方面,它表示变量sum2和平均值的初始化程序'0'是多余的。我的代码仍在运行,但是为什么只对sum2和average而不是在开始时初始化为0的所有其他变量说呢?
谢谢!
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
//Variables
System.out.println("Type numbers: ");
int numbers = Integer.parseInt(reader.nextLine());
int counter = 0;
int sum = numbers;
int minus = -1;
int even = 0;
int odd = 0;
int sum2 = 0;
double average = 0;
while (numbers >= 0) {
numbers = Integer.parseInt(reader.nextLine());
sum+= numbers;
counter = counter + 1;
if (numbers % 2 == 0 ) {
even++;
}else {
odd++;
}
}
if (numbers == minus) {
int sum2 = sum + 1;
double average = (double) sum2 / counter;
System.out.println("Thank you and see you later!");
System.out.println("The sum is " + sum2);
System.out.println("How many numbers: " + counter);
System.out.println("Average: " + average);
System.out.println("Even numbers " + even);
System.out.println("Odd numbers " + odd);
}
}
答案 0 :(得分:0)
您不应该初始化numbers
来读取第一行。当您这样做时,其他计数器未正确初始化。解决一个,
int numbers = 0;
对于sum2
是冗余的,它是冗余的 1 ,因为int sum2 = sum + 1;
应该是sum2 = sum + 1;
(或删除{{ 1}})。您有两个变量,名为int sum2 = 0;
。与sum2
和double average = (double) sum2 / counter;
相同的问题是,有两个名为double average = 0;
的变量。
1 此处冗余是有意的。
答案 1 :(得分:0)
这是解决方案,谢谢大家!
导入java.util.Scanner;
公共课程草案{ 公共静态void main(String [] args){
Scanner reader = new Scanner(System.in);
int numbers = 0;
int counter = 0;
int sum = 0;
int even = 0;
int odd = 0;
System.out.println("Type number: ");
while (numbers >= 0) {
numbers = Integer.parseInt(reader.nextLine());
sum = sum + numbers;
counter = counter + 1;
if (numbers >= 0 && numbers % 2 == 0 ) {
even++;
}
if (numbers >= 0 && numbers % 2 != 0) {
odd++;
}
}
if (numbers == -1) {
int sum2 = sum + 1;
int counter2 = counter - 1;
double average = (double) sum2 / counter2;
System.out.println("Thank you and see you later!");
System.out.println("The sum is " + sum2);
System.out.println("How many numbers: " + counter2);
System.out.println("Average: " + average);
System.out.println("Even numbers " + even);
System.out.println("Odd numbers " + odd);
}
}
}