Question: How can I get this code to run properly? On line 18 I changed it to while (loopCount >= 1 || 1
How can I get this code to run properly? On line 18 I changed it to " while (loopCount >= 1 || 1 <= digitsLoop) { " which got rid of one error but I still get no result after I enter an integer. Thanks import java.util.*; public class AddDigits{ public static int sumDigits(long lg) { // method parses and sums the digits of any given lg int input = (int)lg; // convert to int type in order to use %
// find the length of the number by using String.length()
String inputCheck = "" + input;
int digitsLoop = inputCheck.length();
int loopCount = 0, digitsTotal = 0;
while (loopCount += 1 <= digitsLoop) { // loop for every digit digitsTotal += input % 10; // use % to collect the ones position
input = input / 10; // divide the input by 10 to trim off the ones
} // end while
return digitsTotal;
} // end sumDigits
public static void main(String [] args){ // Initialize the input object
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer:"); int userInteger = input.nextInt();
// display the sum of the integers digits
System.out.println("The sum of the digits in " + userInteger + " = " + sumDigits(userInteger)); }
}
Step by Step Solution
There are 3 Steps involved in it
1 Expert Approved Answer
Step: 1 Unlock
Question Has Been Solved by an Expert!
Get step-by-step solutions from verified subject matter experts
Step: 2 Unlock
Step: 3 Unlock
