+ Start a Discussion

Need help with simple class



Iam trying to execute a simple code . Its supposed to show the output as 3 but its throwing error at the for loop. Not sure whats wrong.  Here is the below code


Integer ifactor= 2;
Integer iResult;
Integer iSum = 0;
Integer i;
String OCR_Line = '0000000401000000000000000000000000002800';
Integer OCR_Check_Digit;

for(i=0; i<=40 ; i++){
iResult = Integer.valueOf(OCR_Line.SubString(i,1))* iFactor;

iResult = Integer.valueOf(String.valueOf(iResult).SubString(1,1)) + Integer.valueOf(String.valueOf(iResult).SubString(2,1));
iSum = iSum+iResult;

if(iFactor == 1)
iFactor = 2;
iFactor = 1;

iResult = math.mod(iSum,10);

if(iResult == 0)
OCR_Check_Digit = 0;
OCR_Check_Digit = 10-iResult;


The OCR_Check_Digit should show the output as 3.


You are getting a Type exception on line 9 (it would be kind to us if you had posted the exception and line#) - Invalid Integer


iResult = Integer.valueOf(OCR_Line.SubString(i,1))* iFactor;

 The substring() method arg 1 is the startIndex and arg2 is the endIndex -- arg 2 is not the number of chars to substring.


This problem is very amenable to system.debug(...) to understand what your code is doing


Thanks Eric. I still cant figure out the issue. I changed the line to 


iResult = Integer.valueOf(OCR_Line.Substring(i,i)) * iFactor . 


It still gives the exception of invalid integer





Substring(i,i) will start at index i and end at index i-1.  From the doc:


Returns a new String that begins with the character at the specified zero-based startIndex and extends to the character at endIndex - 1. For example:
'hamburger'.substring(4, 8); 
// Returns "urge"

'smiles'.substring(1, 5);
// Returns "mile"

If you just want the character at index i, substring(i,i+1).


Use Anonymous Apex in either the Developer Console or Eclipse IDE to experiment with apex code to see how it functions