I'm having a problem with my java program, error says that a certain variable might not have been initialized. But that variable have been initialized inside a loop. What should I do?
can you share the code?
here: //gets the sum of the first and last digit of a number... import javax.swing.JOptionPane; public class FirstAndLastDigits { public static void main(String[] args) { String numberStr; int number; int firstDigit; int lastDigit; int sum; int x = 1; numberStr = JOptionPane.showInputDialog(null,"Enter a number not less than 4 digits","Number",JOptionPane.INFORMATION_MESSAGE); number = Integer.parseInt(numberStr); while (x > 0) { firstDigit = number / 10; x++; } lastDigit = number % 10; sum = firstDigit + lastDigit; JOptionPane.showMessageDialog(null,"Number: " + number + "\nFirst Digit: " + firstDigit + "\nLast Digit: " + lastDigit + "\nSum: " + sum); } }
it says that the variable firstDigit might not have been initialized
I am not sure about the error but I can see some problem in the logic. For the first digit logic doesn't look correct to me. This will be an infinite loop
Oh yes, you're right. I'll try to solve it. Thanks. I'm still open for suggestions.
save ur number to a temp variable x . Then check if x/10 >0. if yes then first digit = x/10 and x =x/10
like this? x = number; if (x / 10 > 0) { firstDigit = x / 10; x = x/10; }
yes! actually there is no need to have firstDigit varibale after the loop value of x will give you firstDigit
Join our real-time social learning platform and learn together with your friends!