0

First of all Sorry for foolish question As i am new to java. actually i have a string which contains a number in between i want to increment its value up to some specific number. i am very confused how to explain . below is the example what i need to do.

I have a string i.e :-
"03000001da00000001666666"
and i want to increase its value like below

"03000001da00000002666666"
"03000001da00000003666666"
"03000001da00000004666666" etc.

I wrote a simple java code below:

but its print wrongly i.e:-
"03000001da2666666"
"03000001da3666666"
"03000001da4666666" etc.

public class Demo {

public static void main(String[] args) {
        String content = "03000001da00000001666666";

        String firstIndex = content.substring(0, 10);
        String requireIndex = content.substring(10,18);
        String lastIndex  = content.substring(18, content.length());
       for(int i = 0; i <= 10;i++){
           System.out.println(firstIndex + (Integer.parseInt(requireIndex)+i) + lastIndex);
       }
    } 
}

need some help please help me.

TTK
  • 47
  • 1
  • 7
  • 2
    Possible duplicate of [How can I pad an integers with zeros on the left?](http://stackoverflow.com/questions/473282/how-can-i-pad-an-integers-with-zeros-on-the-left) – flakes Apr 04 '16 at 17:37

2 Answers2

1

You can use printf and a format String (like %08d) to pad your int at 8 characters with leading zeros. You can also parse your int once before you loop and String.substring(int) (with only one parameter) reads the rest of the String by default. That might look something like,

String content = "03000001da00000001666666";
String firstIndex = content.substring(0, 10);
String lastIndex = content.substring(18);
int middle = Integer.parseInt(content.substring(10, 18));
for (int i = 0; i <= 10; i++) {
    System.out.printf("%s%08d%s%n", firstIndex, middle + i, lastIndex);
}
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
  • I think internally `Arrays.fill()` also use a loop. I am not able to figure out the issue with my answer below. Would you help me point it out? – user2004685 Apr 04 '16 at 17:48
1

Try this:

public static void main(String[] args) {
    String content = "03000001da00000001666666";

    String firstIndex = content.substring(0, 10);
    String requireIndex = content.substring(10,18);
    String lastIndex  = content.substring(18);
    for(int i = 0; i <= 10;i++){
        System.out.printf("%s%08d%s%n",firstIndex, Integer.parseInt(requireIndex)+i, lastIndex);
    }
}
Nicolas Filotto
  • 43,537
  • 11
  • 94
  • 122