簡體   English   中英

為什么我的 Java 數字輸入代碼不起作用?

[英]Why isn't my Java number input code working?

我一直在試圖弄清楚為什么我的代碼不起作用。 如果我不通過一個方法來做,而是把這段代碼放在 main 方法中,那么它就會不斷重復。 我想每次都向用戶詢問一個新號碼。 然后看看這個數字是奇數還是偶數。 如果為奇數,則增加奇數計數加上用戶輸入的所有數字。 應要求用戶輸入值,直到輸入數字 0。

package Week1;

import java.util.Scanner;

public class Task12 {

    public void numbers() {
        Scanner sc = new Scanner(System.in);
        int i = sc.nextInt();
        System.out.println("Enter number");
        int oddnumbers = 0;
        do {

            int count = 0;
            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();
    }
}

您可能應該在循環內部讀取數字“ 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();
}

}

此代碼給出了旅游規范/問題的答案

不工作的原因:你應該在 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());
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM