Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Java integer increases unintended

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

"@@@@@@@@@@—"

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?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading