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; } }
5 Respostas
+ 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.
+ 1
String wholeNumberString = input.next();
+ 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
}
}
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();
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