I am writing a program that counts the number of Evens, Odds, and Zeros in a user-defined whole. Oddly enough, the compiler does not compile at all. It says: "Error: variable number may not be initialized."
Which makes no sense, as far as I can tell, this loop guarantees numberALWAYS is initialized. I know that I can easily shut down the compiler by initializing the declaration. I've always been told that it is usually a bad idea to initialize when declaring to avoid logical errors. However, my biggest scare / confusion is this - I don’t know why I don’t like it. If there is an exception, it will be caught before it happens validInput = true, right? So, when the cycle gets into the check, it will restart, as it validInputwill continue false. This is not even a warning or anything else; This is a tough mistake. What am I missing or not seeing?
I have read other cases regarding if-checks, and this is different from where it is on the check, which may or may not pass. This cycle will ALWAYS go through in the end, if the program does not exit early or not (in any case, it does not reach the for-loop). If this is a duplicate, can someone point me to a direct answer that I could not find? Thanks!
public static void main( String[] args )
{
long number;
boolean validInput = false;
String numStr;
Scanner input = new Scanner(System.in);
do
{
System.out.print("Please enter an integer: ");
numStr = input.next();
try {
number = Long.parseLong(numStr);
validInput = true;
} catch (NumberFormatException e) {
System.out.print("That not an integer. ");
}
} while (!validInput);
int evens = 0, odds = 0, zeros = 0;
for (long temp = number; temp > 0; temp /= 10)
{
int digit = (int)(temp % 10);
if (digit == 0)
{
zeros++;
System.out.println(digit + " is a zero digit.");
}
else if (digit % 2 == 0)
{
evens++;
System.out.println(digit + " is an even digit.");
}
else
{
odds++;
System.out.println(digit + " is an odd digit.");
}
}
String evenStr = " even " + ((evens == 1) ? "digit" : "digits");
String oddStr = " odd " + ((odds == 1) ? "digit" : "digits");
String zeroStr = (zeros == 1) ? " zero" : " zeros";
System.out.println(number + " has " + evens + evenStr + ", " + odds + oddStr + ", and "
+ zeros + zeroStr + ".");
}
source
share