+ Start a Discussion
eduardofernandeseduardofernandes 

Why does not work?

Integer[] pesoCnpj = {1,2,3};

Best Answer chosen by Admin (Salesforce Developers) 
Starz26Starz26

Because you declared the var but did not create the object:

 

Integer[] pesoCnpj = New Integer[]{1,2,3};

All Answers

Starz26Starz26

Because you declared the var but did not create the object:

 

Integer[] pesoCnpj = New Integer[]{1,2,3};
This was selected as the best answer
eduardofernandeseduardofernandes

Thanks!

eduardofernandeseduardofernandes

But, look this error.


System.StringException: Ending position out of bounds: 12: Class.Validacao.validaCnpj: line 31, column 1
And this is the code of my class
public class Validacao {
	
	Integer[] pesoCnpj = new Integer[]{6,5,4,3,2,9,8,7,6,5,4,3,2};
	
	
	//Validando o digito do CNPJ
	public Integer calculaDigito(String str, Integer[] peso){
		Integer soma = 0;
		
		for(Integer i = str.length() - 1, digito; i >= 0; i--){
			digito = Integer.valueOf(str.substring(i,i+1));
			soma += digito*peso[peso.size() - (str.length() + i)];
		}
		
		soma = 11 - Math.mod(soma,11);
		return soma > 9 ? 0 : soma;
	}
	
	//Fazendo a validação do CNPJ
	public Boolean validaCnpj(String cnpj){
		Integer digitoV_1 = calculaDigito(cnpj.substring(0,12), pesoCnpj);
		Integer digitoV_2 = calculaDigito(cnpj.substring(0,12) + digitoV_1, pesoCnpj);
		
		return cnpj.equals(cnpj.substring(0,12) + digitoV_1.format() + digitoV_2.format());
	}
}
Starz26Starz26

It means the string cnpj is not 12 characters long.