I wanted to write a short programm, which replaces the Counting of a String. So I would like to start the String with 0 insted of 1. And Because it is a long String i dont want to change it all by my own. So the String (in this example) is: String LINE:
- Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore
- magna aliquyam erat, sed diam voluptua.
- At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum
- dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore
- magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren,
- no sea takimata sanctus est Lorem ipsum dolor sit amet.
And I want the String to start the counting with 0. and go on wit 1.2.3….(0,1,2,3,4…)
public static void main(String[] args) {
for (int counter = 1; counter <= 300; counter++) {
int NormCounter =1;
int ReplaceCounter = 0;
String NormCounterS = (new Integer(NormCounter)).toString() + ".";
String ReplaceCounterS = (new Integer(ReplaceCounter)).toString() + ".";
Line = Line.replace(NormCounterS , ReplaceCounterS);
++ReplaceCounter;
++NormCounter;
}
System.out.println(Line);
}
it just changes the first “1.” into “0.”… So its 0,2,3,4… But i want the counting to go 0,1,2,3,4
Even though you increment your counters, you re-set the counters to 1 and 0 every time the loop iterates. You should probably move this code:
To outside the for-loop:
Also notice how
String NormCounterS = (new Integer(NormCounter)).toString() + ".";can be rewritten more simplyString NormCounterS = NormCounter + ".";. (The end result is the same).See Laky’s comment for an additional bug fix to this method.
Also just a small plug for Java coding conventions: it is standard to name Java variables with a lower case starting letter. E.g. use
normCounterinstead ofNormCounter.