2016-10-21 21 views
0

設計並實現一個應用程序,該應用程序確定並打印從鍵盤讀取的int值中的偶數位,奇數位和零位數 。需要使用while循環的幫助來使打印語句有效

例子:

Enter a number: 100504575 
The number: 100504575 has 3 zeros, 1 evens, and 5 odds. 

所以代碼是說進入一個數字,然後它會算多少找齊賠率和零,然後再重新打印數量,並說有多少勝算脣上和零有。計數部分的工作,我只是無法得到數字部分工作在這個打印聲明。如果我輸入數字1384932,它應該打印出來:數字:有0個零,3個evens和4個賠率。 當前它打印出來:數量:有0個零,3個evens和4個賠率。

是System.out.print( 「總數:」 + NUM + 「具有」 +零+ 「0」, +甚至+ 「找齊,」 + 「和」 +奇+ 「賠率」) ;

import java.util.Scanner; 

public class CountDigits { 

    public static void main(String[] args) { 
     //Scanner scan = new Scanner(System.in); 

     Scanner Scan = new Scanner(System.in); 
     int even =0, odd = 0, zero = 0; 
     System.out.print ("Enter a number: "); 
     int num = Scan.nextInt(); 
     while(num > 0) { 
      int digit = num % 10; 
      num /= 10; 
      if(digit == 0) { 
      zero++; 
      } else if(digit % 2 == 0) { 
       even++; 
      } else { 
       odd++; 
      } 
     } 
     System.out.print("The number: " + num + " has " + zero + " zeros, " 
       + even + " evens, " + "and " + odd + " odds."); 
     Scan.close(); 
    } 
} 
+0

請將語言作爲標籤 – Pikamander2

+0

您的循環從不退出,因爲除非您輸入了「0」,否則'num'總是'> 0'。用@ChiefTwoPencils答案去改變這一點。但我增加了一種不同的思考方式。 –

+0

是@ChiefTwoPencils – codingisntmyfavorite

回答

1

num0因爲那是你的警戒值停止循環。沒問題,只需將輸入複製到將在while循環中使用的另一個變量中。

int num = Scan.nextInt(); 
int looper = num; 
while (looper > 0) { ... } 

這樣num保留與Scanner採取的值,而另一個是一個循環過程中改變。當然,您還需要將num的所有實例重構爲while循環內的looper。你可以很容易地用Replace All來做到這一點。

+0

這就是我想念的,謝謝你的幫助!它現在是有道理的 – codingisntmyfavorite

0

我編輯你的代碼,以使String使用,所以,當你想,你可以在進入儘可能多的字符,而不必擔心int限制。

我用了一個int[]與大小3計數爲零,nums[0],賠率,nums[1]和找齊。 nums[2]

它會輸入數字,刪除任何空格,並使用charAt()解析digit。然後它檢查。

讓我們知道,這假設只有整數將被輸入,沒有空格或字母或特殊字符。

public static void main(String[] args) { 
    Scanner Scan = new Scanner(System.in); 
    int[] nums = new int[3]; 
    System.out.print ("Enter a number: "); 
    String num = Scan.nextLine(); 
    num = num.trim(); 
    for(int i = 0; i < num.length(); i++){ 
     int digit = Integer.parseInt("" + num.charAt(i)); 
     if(digit == 0){ 
      nums[0]++; 
     }else if(digit % 2 == 0){ 
      nums[2]++; 
     }else{ 
      nums[1]++; 
     } 
    } 
    System.out.print("The number: " + num + " has " + nums[0] + " zeros, " 

      + nums[2] + " evens, " + "and " + nums[1] + " odds."); 
    Scan.close(); 
} 
+0

你如何在幾分鐘內寫出我永遠不會明白的......謝謝你的幫助 – codingisntmyfavorite

+0

我以前做過。如果你想保持自己的行事方式,使用@ChiefTwoPencils答案。它解決了你的核心問題,我的答案只是一種不同的思考方式。 –