0

Help me with the code!

/*the code below is supposed to add digits of an input number until it returns a single digit number, like if I input 66 , it returns 6+6=12, then 1+2 = 3, so the final answer is 3. But it ain't working. got no clue why*/ //The code import java.util.Arrays; import java.util.Scanner; public class Main{ public static void main(String []args) { Scanner inp = new Scanner(System.in); int num = inp.nextInt(); inp.close(); int sum = 0; while(num<9) { String[]myArray= String.valueOf(num).split(""); for (String el : myArray) { sum += Integer.parseInt(el); num = sum; myArray = new String[0]; } System.out.println(num); } } }

23rd Apr 2021, 6:42 AM
Mons Joseph
Mons Joseph - avatar
2 Answers
+ 3
/* while(num<9) - would execute forever because adding the digits would eventually end up to single digit and therefore this while loop would execute infinitely the variable "sum" needs to be set again to 0 after every steps [CODE] */ import java.util.Arrays; import java.util.Scanner; public class Main{ public static void main(String []args) { Scanner inp = new Scanner(System.in); int num = inp.nextInt(); inp.close(); int sum = 0; while(num>9) { sum = 0; String[] myArray= String.valueOf(num).split(""); for (String el : myArray) { sum += Integer.parseInt(el); num = sum; } System.out.println(num); } } }
23rd Apr 2021, 7:02 AM
minirkk
minirkk - avatar
+ 1
1. While condition has to be num>9 2. Reset sum in each while loop iteration Fixed code: import java.util.Arrays; import java.util.Scanner; public class Main{ public static void main(String []args) { Scanner inp = new Scanner(System.in); int num = inp.nextInt(); while(num>9) { String[]myArray= String.valueOf(num).split(""); int sum = 0; for (String el: myArray) { sum += Integer.parseInt(el); num = sum; myArray = new String[0]; } System.out.println(num); } } }
23rd Apr 2021, 7:04 AM
Benjamin JĂŒrgens
Benjamin JĂŒrgens - avatar