am a beginner Java programmer so bear with me. I have a question about a project I am working on. I want to receive an
integer (max 30 digits) from the user, then count how many odd, even, and zeros was entered. I have the logic down right:
using modulus to determine if odd or even, and using the ASCII code for zero to determine if it is a zero.
My question is do I need to convert the string to an int or leave it as a string. I am a bit puzzled as how this works.
Any help in the form of example code or relative support would be greatly appreciated.
Thanks
Java
Last Comment
CEHJ
8/22/2022 - Mon
yongsing
Yes, you need to convert the string to an int first:
A 30 digit number is very large. Not sure if it fits into integer or long.
You can do it this way if you want without converting the input into an integer or long.
1. Read in the number from the console. It will be a string.
2. Check the last digit of the number for whether it is even or odd. The last digit determines eveness or oddness.
3. Loop through the string from beginning to end, counting evens, odds, and zeros.
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
If you wish to discover the properties of the individual digits, then it looks like you've got it pretty well taped. No, you don't need to convert it to a numerical value.
NoleBoy
ASKER
I appreciate everyone's help in this matter. I decided to leave it as a string then compare each digit in a for loop.
It is probably more coding than necessary but it worked.
Code below:
public void process(){
String integerString = getIntegerString();
int evenDigits = 0;
int oddDigits = 0;
int zeroDigits = 0;
for (int i = 0; i < integerString.length(); i++){
char c = integerString.charAt(i);
if (c == '0') zeroDigits++;
if (c == '0') evenDigits++;
if (c == '1') oddDigits++;
if (c == '2') evenDigits++;
if (c == '3') oddDigits++;
if (c == '4') evenDigits++;
if (c == '5') oddDigits++;
if (c == '6') evenDigits++;
if (c == '7') oddDigits++;
if (c == '8') evenDigits++;
if (c == '9') oddDigits++;
}
System.out.println(integerString + " contains "
+ evenDigits + " even digits, "
+ oddDigits + " odd digits, and "
+ zeroDigits + " zero digits.");
}
try {
int number = Integer.parseInt(theString
boolean isOdd = (number % 2) != 0;
boolean isEven = (number % 2) == 0;
boolean isZero = (number == 0);
} catch (NumberFormatException e) {
System.out.println("Invali
}