Reputation: 161
I am trying to print each digit of an integer and then sum of each digit like this. There is something wrong with the loops but I cant seem to figure it out. I want it to be like this:
Please enter a number: 194
1 * 100 = 100
9 * 10 = 90
4 * 1 = 4
import java.util.Scanner;
public class PrintEachDigits {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter the number: ");
int num = scan.nextInt();
String s = ""+num;
double d = 0;
for(int i = 0; i < s.length(); i++) {
for(int j = s.length()-1; j >= 0; j--) {
d = Math.pow(10,j);
System.out.println(s.charAt(i) + " * " + d
+ " = " + (s.charAt(i)*d));
}
}
}
}
This is the output of my code:
Enter the number: 194
1 * 100.0 = 4900.0
1 * 10.0 = 490.0
1 * 1.0 = 49.0
9 * 100.0 = 5700.0
9 * 10.0 = 570.0
9 * 1.0 = 57.0
4 * 100.0 = 5200.0
4 * 10.0 = 520.0
4 * 1.0 = 52.0
Upvotes: 2
Views: 103
Reputation: 31
import java.util.Scanner;
public class PrintEachDigits {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter the number: ");
int num = scan.nextInt();
String s = "" + num;
int len = s.length() - 1;
long d = 0;
if (len < 2) {
d = 1;//For single digit
} else {
d = (long)Math.pow(10, len);
}
for (int i = 0; i < s.length(); i++) {
System.out.println(s.charAt(i) + " * " + d + " = "
+ ((s.charAt(i) - '0') * d));
d = d / 10;
}
}
}
Upvotes: 0
Reputation: 10613
There's a couple problems with your code.
The first problem is that you don't need two loops, you just need one.
The second problem is confusing char
s and int
s. '0'
is not the same as 0
; instead, '0'
is a numeric value representing the encoding of that character (which turns out to be 48). So to get the correct value that you want, you should subtract '0'
from the char
before doing your math.
for(int i = 0; i < s.length(); i++) {
d = Math.pow(10, s.length() - i - 1);
int value = s.charAt(i) - '0';
System.out.println(value + " * " + d
+ " = " + (value*d));
}
This will get it close to the output you wanted. It's still showing the .0
at the end though, because d
is a double
. Make it an int
to fix that.
//This can be scoped to inside the loop, so you don't need to declare it beforehand
int d = (int)Math.pow(10,j);
Upvotes: 7