Home > front end >  Java integer increases unintended
Java integer increases unintended

Time:09-22

I have a function that takes String and a char[] type variables as parameter.

public String compressLine(String line, char[] fileChars){
  String outputLine = new String();
  int count = 0;
  char lastChar = fileChars[0];
  for(char c : line.toCharArray()){
    if(c!=lastChar){
      outputLine  = String.format("%o,", count);
      lastChar = c;
      count = 1;
    }else{
      count  = 1;
    }
  }
  outputLine  = count;
      return outputLine;
}

String line is a line of ascii art and the char[] fileChars consists of the characters that are used in the string mentioned beforehand.

Example of line:

"@@@@@@@@@@---"

Example of fileChars:

[-, @]

Algorithm works in the following manner: given a row of data, the algorithm replaces each row with numbers that say how many consecutive pixels are the same character, always starting with the number of occurrences of the character that is encountered first in the fileChars.

When I ran a test using the examples given above, It should return;

[0, 10, 3]

But the output I get is;

[0, 12, 3]

When I tried to solve the bug, I saw the integer count somehow hops from 7 to 10.

What is causing this?

CodePudding user response:

Your problem is with this line:

outputLine  = String.format("%o,", count);

The "%o" output format specifier specifies that the value of count should be output in Octal. When the decimal value of count is 10, the Octal equivalent is 12.

I expect that you want this instead:

outputLine  = String.format("%d,", count);

PS: When it appears that the number "jumps" from 7 to 10, that's because '10' immediately follows '7' in octal.

CodePudding user response:

%o means octal. I'm not sure how you ended up on using %o, but, you don't want octal. Octal is how you would count if you have 8 fingers. 0, 1, 2, 3, 4, 5, 6, 7.., oh last finger, so.. 10!

In octal, '12' is how you write the tenth number. Just like you'd use '10' to do that in decimal, and '1010' in binary.

You want %d for decimal.

  • Related