There was the following problem.
I'm trying to implement text encryption.
There are no problems with reading and encryption itself, I use a simple substitution method. However, the trouble is at the time of inserting the error.
There should be a 5 percent probability of copying, replacing or disappearing the left / right bit. When the random () method is called, an exception sometimes occurs.
As far as I understand.
Actually, I cannot understand, when and for what reason an exception occurs.
I will be very grateful!
Indicated part of the code:

public class MainForm extends javax.swing.JFrame { /** * Creates new form MainForm */ private char[] text; private char[] alphabet = {'А', 'Б', 'В', 'Г', 'Д', 'Е', 'Ё', 'Ж', 'З', 'И', 'Й', 'К', 'Л', 'М', 'Н', 'О', 'П', 'Р', 'С', 'Т', 'У', 'Ф', 'Х', 'Ц', 'Ч', 'Ш', 'Щ', 'Ъ', 'Ы', 'Ь', 'Э', 'Ю', 'Я', 'а', 'б', 'в', 'г', 'д', 'е', 'ё', 'ж', 'з', 'и', 'й', 'к', 'л', 'м', 'н', 'о', 'п', 'р', 'с', 'т', 'у', 'ф', 'х', 'ц', 'ч', 'ш', 'щ', 'ъ', 'ы', 'ь', 'э', 'ю', 'я', '.', ',', '!', 63, 34, 32, '-', 133, '/', 10}; private int[] keyalphabet = {50, 51, 52, 53, 54, 55, 56, 57, 58, 60, 61, 62, 63, 64, 65, 66, 67, 68, 70, 71, 72, 73, 74, 75, 76, 77, 78, 80, 81, 82, 83, 84, 85, 1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 12, 13, 14, 15, 16, 17, 18, 20, 21, 22, 23, 24, 25, 26, 27, 28, 30, 31, 32, 33, 34, 35, 36, 40, 41, 42, 43, 44, 0, 45, 46, 86, 87}; private int[] key = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; List<Integer> encryptarr = new ArrayList<Integer>(); public MainForm() { initComponents(); int WIDTH = 150; int AreaHeight = 230; int HEIGHT = 50; Read.setSize(WIDTH, HEIGHT); Encryption.setSize(WIDTH, HEIGHT); Send.setSize(WIDTH, HEIGHT); Decryption.setSize(WIDTH, HEIGHT); jTextArea1.setSize(WIDTH, AreaHeight); jTextArea2.setSize(WIDTH, AreaHeight); jTextArea3.setSize(WIDTH, AreaHeight); jTextArea4.setSize(WIDTH, AreaHeight); } private void getTxt(String getext) { text = getext.toCharArray();//в данную переменную массив типа char записывается наш текст конвертированный из String System.out.println("We are get this text:\n" + Arrays.toString(text));//вывод нашего текста на консоль, конвертируем массив символов в String } private void StartEncryption() { /*тут проверяется на совпадение каждый символ текста с каждым элементом массива,где содержатся азбука*/ for (int index = 0; index < text.length; index++) { for (int jndex = 0; jndex < alphabet.length; jndex++) { if (text[index] == alphabet[jndex]) {/*в случаи совпадения символ отправляется в список-коллекцию*/ encryptarr.add(keyalphabet[jndex]); creatError(encryptarr, jndex); } } } getMatrix(encryptarr); } private void creatError(List<Integer> encryptarr, int jndex) { int index = jndex; double rand = random(); if (rand > 0.01 && rand <= 0.05) { System.out.println("Error on bite with " + rand + " persent"); rand = random(); if (rand <= 0.33) { System.out.println("Copy bite"); //CopyBite(encryptarr, index); } else if (rand > 0.33 && rand < 0.66) { System.out.println("Delete bite on value " + encryptarr.get(index) + " with index:" + index); encryptarr.set(index, DeleteBite(encryptarr, index)); } else { System.out.println("Changed bite on value " + encryptarr.get(index) + " with index:" + index); //encryptarr.set(index, ChangedBite(encryptarr, index)); } } } private int DeleteBite(List<Integer> encryptarr, int index) { double rand = random(); if (rand <= 0.5) { System.out.println("Delete left bite"); int buffer = encryptarr.get(index) % 10; System.out.println("We set this value:" + buffer); return buffer; } else { System.out.println("Delete right bite"); int buffer = encryptarr.get(index) / 10; System.out.println("We set this value:" + buffer); return buffer; } } private double random() { double rand = new Random().nextDouble(); System.out.println("rand:" + rand); return rand; } private void getMatrix(List<Integer> encryptarr) { jTextArea2.setText(encryptarr.toString()); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code"> private void initComponents() { jPanel1 = new javax.swing.JPanel(); jScrollPane1 = new javax.swing.JScrollPane(); jTextArea1 = new javax.swing.JTextArea(); Read = new javax.swing.JButton(); Encryption = new javax.swing.JButton(); Send = new javax.swing.JButton(); Decryption = new javax.swing.JButton(); jScrollPane2 = new javax.swing.JScrollPane(); jTextArea2 = new javax.swing.JTextArea(); jScrollPane3 = new javax.swing.JScrollPane(); jTextArea3 = new javax.swing.JTextArea(); jScrollPane4 = new javax.swing.JScrollPane(); jTextArea4 = new javax.swing.JTextArea(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jTextArea1.setColumns(20); jTextArea1.setRows(5); jScrollPane1.setViewportView(jTextArea1); Read.setText("Считывание"); Read.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ReadActionPerformed(evt); } }); Encryption.setText("Шифрование"); Encryption.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { EncryptionActionPerformed(evt); } }); Send.setText("Передача"); Decryption.setText("Дешифрование"); jTextArea2.setColumns(20); jTextArea2.setRows(5); jScrollPane2.setViewportView(jTextArea2); jTextArea3.setColumns(20); jTextArea3.setRows(5); jScrollPane3.setViewportView(jTextArea3); jTextArea4.setColumns(20); jTextArea4.setRows(5); jScrollPane4.setViewportView(jTextArea4); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(Read, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 150, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(Encryption, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 151, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(Send, javax.swing.GroupLayout.PREFERRED_SIZE, 151, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(Decryption, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 151, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)))) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 233, Short.MAX_VALUE) .addComponent(jScrollPane3) .addComponent(jScrollPane4) .addComponent(jScrollPane1)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(Read, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(Encryption, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(Send, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(Decryption, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(23, Short.MAX_VALUE)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); pack(); }// </editor-fold> private void ReadActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: getTxt(jTextArea1.getText());//получаем наш текст и сохраняем его в переменной } private void EncryptionActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: StartEncryption();//далее запускаем метод шифрования... } /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(MainForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(MainForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(MainForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(MainForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new MainForm().setVisible(true); } }); } // Variables declaration - do not modify private javax.swing.JButton Decryption; private javax.swing.JButton Encryption; private javax.swing.JButton Read; private javax.swing.JButton Send; private javax.swing.JPanel jPanel1; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JScrollPane jScrollPane3; private javax.swing.JScrollPane jScrollPane4; private javax.swing.JTextArea jTextArea1; private javax.swing.JTextArea jTextArea2; private javax.swing.JTextArea jTextArea3; private javax.swing.JTextArea jTextArea4; // End of variables declaration } 

Actually, the list of errors

 [LEFT]Exception in thread "AWT-EventQueue-0" java.lang.IndexOutOfBoundsException: Index: 71, Size: 11 at java.util.ArrayList.rangeCheck(ArrayList.java:657) at java.util.ArrayList.get(ArrayList.java:433) at maininterface.MainForm.creatError(MainForm.java:88) at maininterface.MainForm.StartEncryption(MainForm.java:71) at maininterface.MainForm.EncryptionActionPerformed(MainForm.java:297) at maininterface.MainForm.access$100(MainForm.java:19) at maininterface.MainForm$2.actionPerformed(MainForm.java:214) at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022) at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2348) at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402) at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259) at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252) at java.awt.Component.processMouseEvent(Component.java:6533) at javax.swing.JComponent.processMouseEvent(JComponent.java:3324) at java.awt.Component.processEvent(Component.java:6298) at java.awt.Container.processEvent(Container.java:2237) at java.awt.Component.dispatchEventImpl(Component.java:4889) at java.awt.Container.dispatchEventImpl(Container.java:2295) at java.awt.Component.dispatchEvent(Component.java:4711) at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4889) at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4526) at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4467) at java.awt.Container.dispatchEventImpl(Container.java:2281) at java.awt.Window.dispatchEventImpl(Window.java:2746) at java.awt.Component.dispatchEvent(Component.java:4711) at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758) at java.awt.EventQueue.access$500(EventQueue.java:97) at java.awt.EventQueue$3.run(EventQueue.java:709) at java.awt.EventQueue$3.run(EventQueue.java:703) at java.security.AccessController.doPrivileged(Native Method) at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80) at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:90) at java.awt.EventQueue$4.run(EventQueue.java:731) at java.awt.EventQueue$4.run(EventQueue.java:729) at java.security.AccessController.doPrivileged(Native Method) at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80) at java.awt.EventQueue.dispatchEvent(EventQueue.java:728) at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201) at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116) at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105) at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101) at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93) at java.awt.EventDispatchThread.run(EventDispatchThread.java:82) 

    1 answer 1

    Code:

     private void StartEncryption() { for (int index = 0; index < text.length; index++) { for (int jndex = 0; jndex < alphabet.length; jndex++) { if (text[index] == alphabet[jndex]) { encryptarr.add(keyalphabet[jndex]); creatError(encryptarr, jndex); } } } getMatrix(encryptarr); } 

    You pass the jndex index to the function, and then you try to get an element from the encryptarr at that index. But where does he come from? For example, let the input string be "abc". Suppose that no errors were generated for the first two letters. When processing the last letter, an error is generated and we pass jndex as an index, which is 35 for the letter 'c'.

     System.out.println("Delete bite on value " + encryptarr.get(index) + " with index:" + index); encryptarr.set(index, DeleteBite(encryptarr, index)); 

    You are trying to get the contents of the container at this index. In the container at this point you have two elements, respectively, an exception is generated.

    I don’t know what exactly you wanted to do - but most likely you didn’t want jndex , you wanted to transfer something else to it :)

    • Everything, I understood the error, I needed to pass not jndex, but simply index, then in the function I can refer to the necessary element of the collection. - A_Light
    • @A_Light, great! I'm glad if I could be useful to you. - isnullxbh