Java - separate number in 3 parts

Say I have the following number:

36702514

I want to separate the indicated number into 3 parts, which is 36, 702, 514.
The following is the code I tried:

int num = 36702514;
int num1 = num.substring(0, 2);
int num2 = num.substring(2, 3);
int num3 = num.substring(5, 3);

Am I writing correctly?

+4
source share
4 answers
List<String>  myNumbers = Arrays.asList(
    NumberFormat.getNumberInstance(Locale.US).format(36702514).split(","));

My solution is building a comma separated Stringinput in the US locale:

36,702,514

This one is Stringthen split into a comma to give the desired three parts in the original problem.

List<Integer> numbers = new ArrayList<>();
Integer n = null;
for (String numb : myNumbers)
{
    try
    {
        n = new Integer(numb);
    }
    catch (NumberFormatException e)
    {
        System.out.println("Wrong number " + numb);
        continue;
    }
    numbers.add(n);
}
System.out.println(numbers);
+7
source

You need to use it substring()in Java String, not in the primitive int. Convert your number in Stringwith String.valueOf():

int num = 36702514;
String numString = String.valueOf(num);

int num1 = Integer.parseInt(numString.substring(0, 2));
int num2 = Integer.parseInt(numString.substring(2, 5));
int num3 = Integer.parseInt(numString.substring(5, 8));
+5
source

.

int num1 = num % 10;
int num2 = num / 10 % 10;
int num3 = num /100 % 10;

System.out.print(num1);
System.out.print("\n" + num2);
System.out.print("\n" + num3);

: .

0

?

No, you will not do this, you will get a compile-time error like

error: int cannot be dereferenced

num here is a primitive, you cannot call a method on a primitive.

The right way:

int no = 36702514;
String num=String.valueOf(num);
int num1 = Integer.parseInt(num.substring(0, 2));
int num2 = Integer.parseInt(num.substring(2, 3));
int num3 = Integer.parseInt(num.substring(5, 3));
-3
source

Source: https://habr.com/ru/post/1598154/


All Articles