How to solve this Range Error in my code?
142
There is an error when you start from the highest index:
for(int i = alfa.length-1
Your index has to go down and you are using ++.
Use this:
for(int i = alfa.length-1; i > -1; i--)
Author by
JotaCanutto
Updated on December 07, 2022Comments
-
JotaCanutto over 1 year
I'm trying to create an cipher app on android studio using flutter. Right now I'm working on a simple Atbash Cipher, but I get a range error when trying to test it. These are the encrypt and decrypt codes:
@override String encrypt(String plaintext, {String key}) { String alfa = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; String alfaReverso = ""; for(int i = alfa.length-1; i > -1; i++){ alfaReverso += alfa[i]; } String encryText = ""; for (int i = 0; i < plaintext.length; i++){ if(plaintext.codeUnitAt(i) == 32){ encryText += " "; } else{ int count = 0; for(int j = 0; j < alfa.length; j++){ if(plaintext[i] == alfa[j]){ encryText += alfaReverso[j]; break; } } } } return "ENCRYPT Plain = " + encryText; } } @override String decrypt(String cyphertext, {String key}) { String alfa = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; String alfaReverso = ""; for(int i = alfa.length-1; i > -1; i++){ alfaReverso += alfa[i]; } String dencryText = ""; for (int i = 0; i < cyphertext.length; i++){ if(cyphertext.codeUnitAt(i) == 32){ dencryText += " "; } else{ int count = 0; for(int j = 0; j < alfaReverso.length; j++){ if(cyphertext[i] == alfaReverso[j]){ dencryText += alfa[j]; break; } } } } return "ENCRYPT Plain = " + dencryText; }
When trying to run it this is the range exception I get:
I/flutter ( 6004): RangeError (index): Invalid value: Not in range 0..25, inclusive: 26
I know it has something to do with the alphabetI'm using, but I don't know how to solve it.
-
diegoveloper over 5 yearsDon't worry. I'm glad to help you. Don't forget the accept the answer :)