I need help with Java Basics question. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

I need help with Java Basics question.

So, I want to write a program that reads an integer between 0 and 1000 and adds all digits in the integer. For example, say the user inputs 222 then the program would add 2+2+2. How would I go about doing this? Here is what I got so far... import java.util.Scanner; public class Program { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print(" Name a whole number between 1 and 1000 :"); double wholeNumber = input.nextDouble(); double extract = wholeNumber % wholeNumber.length; } }

11th Jun 2019, 5:12 PM
Markie Alicia
Markie Alicia - avatar
5 Answers
+ 1
First store the integer in a string, let the user input be a string, then split the string, parseInt or parseDouble and then add them all.
11th Jun 2019, 5:29 PM
Isaac
Isaac - avatar
+ 1
String wholeNumberString = input.next();
11th Jun 2019, 8:54 PM
zemiak
+ 1
Here is what I have ... How do I split the user's answer so that I can add each integer... say they put 22... I want the program to do 2 + 2 = 4 Thank You so much!! (: import java.util.Scanner; public class Program { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print(" Name a whole number between 1 and 1000 :"); String wholeNumberString = input.next(); int wholeNumber = Integer.parseInt(wholeNumberString); System.out.println( "You typed :" + wholeNumber); int wholeNumber } }
12th Jun 2019, 5:29 PM
Markie Alicia
Markie Alicia - avatar
0
What am I doing wrong here? import java.util.Scanner; public class Program { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print(" Name a whole number between 1 and 1000 :"); String wholeNumberString = input.nextString();
11th Jun 2019, 7:22 PM
Markie Alicia
Markie Alicia - avatar
0
- instead of long code you can post here link from sololearn code editor with your saved code, up right there is icon for shared and there for copy to clipboard - you need loop for() with wholeNumberString.length() as condition . in loop get digits from number like 1 from number 123456 . you can use wholeNumberString.substring() and then parseInt() or wholeNumberString.charAt() - 48 . for check you can print this temporary result, in this time end of loop
13th Jun 2019, 12:42 AM
zemiak