我一直试图弄清楚为什么我的代码无法正常工作。如果我不是通过一种方法来完成它并将此代码放在main方法中,那么它会不断重复。我想每次都要求用户提供一个新号码。然后看看数字是奇数还是偶数。如果是奇数然后增加奇数,则添加用户输入的所有数字。应该要求用户输入值,直到输入数字0.
public void listAllfiles()
{
for(String filename : files) {
System.out.println(filename);
}
}
答案 0 :(得分:0)
你应该读一个数字" i = sc.nextInt();
"在循环内部,变量count
在外面,如下所示:
package Week1;
import java.util.Scanner;
public class Task12 {
public void numbers() {
Scanner sc = new Scanner(System.in);
int oddnumbers = 0;
int count = 0;
int i=0;
do {
System.out.println("Enter number");
i = sc.nextInt();
count = count + i;
System.out.println("The total is:" + count);
if (i % 2 == 0) {
System.out.println("The number is Even");
} else if (i != 9) {
oddnumbers += i;
System.out.println("The number is odd");
System.out.println("the count of odd numbers is :" + oddnumbers);
} else
System.out.println("The number is odd");
System.out.println("the count of odd numbers is :" + oddnumbers);
} while (i != 0);
}
public static void main(String[] args) {
Task12 n = new Task12();
n.numbers();
}
}
答案 1 :(得分:0)
此代码给出了游览规范/问题的答案
不工作的原因:你应该在do while循环中输入,然后检查奇数。
public int numbers() {
Scanner sc = new Scanner(System.in);
int num = 0;
int oddSum = 0;
do {
System.out.println("Enter number");
num = sc.nextInt();
if(num == 0) {
break;
} else if (num % 2 != 0) {
oddSum += num;
}
} while (num != 0);
sc.close();
return oddSum;
}
public static void main(String[] args) {
Test n = new Test();
System.out.println(n.numbers());
}