2015-07-13 42 views
-5

我在這裏有一個java程序,要求用戶輸入十個整數,並打印出多少個奇數和多少個偶數。JAVA只顯示一個計數器有多少個奇數和偶數?

import java.io.*; 
public class Count { 

    public static void main(String[] args) { 

     int i, , even_ctr=0, odd_ctr = 0; 
     String input = " "; 

     BufferedReader in = new BufferedReader (new InputStreamReader(System.in)); 

     for(i = 1; i <=10; i++){ 
      try{ 
      System.out.print("Input integer number: "); 
       input = in.readLine(); 
       }catch(IOException e){ 
       System.out.println("Error!"); 
       } 

       n = Integer.parseInt(input); 

       if(n % 2 == 0) 
       even_ctr++;  //counter for even 
       if(n % 2 == 0) 
       odd_ctr++;  //counter for odd 
     }System.out.println("EVEN: " + even_ctr + "\nODD: "+ odd_ctr); 
    } 
} 

我想通過只使用一個計數器而不是兩個計數器來更改程序。任何人都知道?

+7

跟蹤奇數,偶數是10多? –

+5

此外,您的代碼只能爲兩個計數器增加偶數整數。 –

回答

0
import java.io.*; 
public class NewClass { 

    public static void main(String[] args) { 

     int i,n, even_ctr=0; 
     String input = " "; 

     BufferedReader in = new BufferedReader (new InputStreamReader(System.in)); 

     for(i = 1; i <=10; i++){ 
      try{ 
      System.out.print("Input integer number: "); 
       input = in.readLine(); 
       }catch(IOException e){ 
       System.out.println("Error!"); 
       } 

       n = Integer.parseInt(input); 

       if(n % 2 == 0) 
       even_ctr++;  

     }System.out.println("EVEN: " + even_ctr + "\nODD: "+ (10-even_ctr)); 
    } 
} 
0

只需保持ODD號碼檢測的第一個計數器遞增(或偶數,但其中任何一個)。在計算結束時,如果ODD計數器= 4,並且輸入的總數爲10,則10 - ODDcounter = 10 - 4 = 6是偶數的數量。

0

爲此,它看起來像使用掃描儀同樣有用,因此您可以避免必須解析字符串的步驟。這也要求您使用import java.util.Scanner,但您可以使用掃描儀接收字符串或整數。

Scanner in = new Scanner(System.in); 
int input; 
int evenCount = 0; 

for(i = 1; i <=10; i++){ 
     try{ 
     System.out.print("Input integer number: "); 
      input = in.nextInt(); 
      }catch(IOException e){ 
      System.out.println("Error!"); 
      } 

      if(input % 2 == 0) 
       evenCount++; 
    } 
System.out.println("EVEN: " + evenCounter + "\nODD: "+ (10 - evenCounter); 

在方法結束時包含in.close();以關閉掃描儀或您使用的閱讀器。

-1
package evenoddten; 

import java.util.Scanner; 

public class EvenOddTen { 

    public static void main(String[] args) { 

     int num1 = 0, num2, even = 0, count = 0; 
     Scanner scr = new Scanner(System.in); 
     System.out.print("Total Nos:"); 
     num2 = scr.nextInt(); 

     while(count<num2) { 
      System.out.println("Enter no:"); 
      num1 = scr.nextInt(); 
      if (num1%2 == 0) { 
       even = even + 1; 
      }   
      count = count+1; 
     } 
     System.out.println("Even nos are:"+even); 
     System.out.println("Odd nos are:"+(count - even)); 
    } 
} 
+1

有一個無用的循環。請檢查。 – sphinks

+1

僅提供代碼解決方案,請幫助用戶解釋您的代碼正在做什麼,並指出他的程序中的缺陷。作爲一個評論,我們的代碼有一個空的for循環,爲什麼你仍然保留它?該問題要求僅使用一個計數器,但您在代碼中也沒有更改 – Icepickle