java循环、偶数和零
我目前正在开发一个程序,可以计算用户输入数字中的偶数、赔率和零。我在两件事上有困难。一个是我不知道如何让循环继续,直到输入哨兵号,另一个是我如何将零计算为零而不是偶数。下面是我目前的代码,谢谢大家
import java.util.Scanner;
public class CountDigitsWithSentinel
{
public static void main(String[] args)
{
// Declare the identifiers
final int SENTINEL = -99;
int userInput;
int oddNums = 0;
int evenNums = 0;
int numZeros = 0;
// Declare the remaining identifiers ...
Scanner scan = new Scanner(System.in);
// Display the programmer's information
System.out.println("Enter an integer value (-99 to end):");
userInput = scan.nextInt();
System.out.println("The number " + userInput + " contains");
//Your code ...
while (userInput > 0) {
int rem = userInput % 10;
if (rem% 2 == 0) {
evenNums++;
}
else
{
oddNums++;
}
userInput = userInput / 10;
}
//Your code ...
// Display the counts
System.out.println("Zero digits: " + numZeros);
System.out.println("Even digits: " + evenNums);
System.out.println("Odd digits: " + oddNums);
//Your code ...
System.out.println("Have a nice day!");
}
}
# 1 楼答案
我可能会将其转换为字符串,然后在switch语句中使用正则表达式对其求值。如果缓存(预定义)reg EXE,这也会非常有效,因为不需要先将每个字符转换为int
# 2 楼答案
您可以添加
if(rem == 0)
,但我建议您使用字符串,因为如果用户输入的数字以0开头,程序将不会对其计数:带int:
带int的输出:
带字符串:
带字符串的输出: