Ask your own question, for FREE!
Computer Science 20 Online
OpenStudy (anonymous):

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?

OpenStudy (ankit042):

can you share the code?

OpenStudy (anonymous):

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); } }

OpenStudy (anonymous):

it says that the variable firstDigit might not have been initialized

OpenStudy (ankit042):

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

OpenStudy (anonymous):

Oh yes, you're right. I'll try to solve it. Thanks. I'm still open for suggestions.

OpenStudy (ankit042):

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

OpenStudy (anonymous):

like this? x = number; if (x / 10 > 0) { firstDigit = x / 10; x = x/10; }

OpenStudy (ankit042):

yes! actually there is no need to have firstDigit varibale after the loop value of x will give you firstDigit

Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!
Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!