Nevada - 1 year ago 104

Java Question

I'm new in Java and I try to find the sum of first three digits in

`int`

I have a number

`123456`

`123`

`456`

`public static void main(String[] args) {`

Scanner scanner = new Scanner(System.in);

System.out.println("Enter the number:");

int number = scanner.nextInt();

int length = (int) Math.ceil(Math.log10(number));

for (int i = 1; i <= 3; i++) {

System.out.println(i);

}

System.out.println(length);

System.out.println(number);

}

I think that I shoud to use for loop, but I'm not sure. I know how to count the length of a number. But how to how to find the sum of the first three numbers and last three?

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

Here's a straightforward way of doing it, making the assumption that your integer has an even number of digits...

```
public class Test {
public static void main(String[] args) {
// Makes the assumption that the input integer contains an even number of digits.
int x = 123456;
String s = Integer.toString(x);
int[] count = new int[2];
for (int i = 0; i < s.length(); i++) {
int digit = Integer.parseInt(s.substring(i, i + 1));
int countIndex = (int)Math.floor(i * 2 / s.length());
count[countIndex] += digit;
}
int half = s.length() / 2;
System.out.println("First Sum of " + s.substring(0, half) + ": " + count[0]);
System.out.println("Second Sum of " + s.substring(half) + ": " + count[1]);
}
}
```

**Alternate Method**

Here's another way of doing it without using the arrays above, and actually simplified the logic by abstracting the sum to a method.

```
public class Test {
public static void main(String[] args) {
// Makes the assumption that the input integer contains an even number of digits.
int x = 123456;
String s = Integer.toString(x);
int half = s.length() / 2;
String firstHalf = s.substring(0, half);
String secondHalf = s.substring(half);
System.out.println(firstHalf);
System.out.println(secondHalf);
int sum1 = sumString(firstHalf);
int sum2 = sumString(secondHalf);
System.out.println("Sum 1: " + sum1);
System.out.println("Sum 2: " + sum2);
}
private static int sumString(String s) {
int sum = 0;
for (int i = 0; i < s.length(); i++) {
sum += Integer.parseInt(s.substring(i, i + 1));
}
return sum;
}
}
```

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**