0

Выдает ошибку что выхожу за пределы массива, хотя проверяю это в цикле. Тем не менее через раз, выводит ошибку.

package supreme;

import java.util.Scanner;

public class Main {

    public static void main(String args[]) {
            menu();
    }
    public static void menu() {
        Scanner in = new Scanner(System.in);
        int choice;
        System.out.print("1.Crypt\n2.Uncrypt\n3.Exit\nPlease make your choice: ");
        switch(choice = in.nextInt()) {
            case 1:
            {
                System.out.println("Please enter your string which will be crypted: ");
                String line = in.next();
                byte[] crypting = line.getBytes();
                System.out.println("Please enter your password(it can be any number): ");
                String temp = in.next();
                char [] password = temp.toCharArray();
                for ( int i = 0; i <crypting.length; i ++ ) {
                    System.out.println("Element " + i +" is: " +  crypting[i]);
                }
                int counter = 0;
                for (int i = 0; i < crypting.length; i++) {
                    if(counter == crypting.length) counter = 0;

                    if((password[counter] == '1') && (password[counter+1] == '0')) {
                        crypting[i] = (byte)(crypting[i] << 1);
                    }
                    if(password[counter] == '0' && password[counter+1] == '1') {
                        crypting[i] = (byte)(crypting[i] >> 1);
                    }
                    if(password[counter] == '1' && password[counter+1] == '1') {
                        crypting[i] = (byte)(~crypting[i]);
                    }
                    counter+=2;
                    System.out.println(counter);
                }

                System.out.println("After crypt!");
                for( int i = 0; i <crypting.length; i ++ ) {
                    System.out.println("Element " + i +" is: " +  crypting[i]);
                }
                String crypted = new String(crypting);
                System.out.println(crypted);
                byte [] sss = crypted.getBytes();
                for(int i = 0; i < sss.length; i++) {
                    System.out.println(sss[i]);

                }
                break;
            }
            case 2:
            {
                break;
            }
            default:
                System.out.println("Please, choose one of the possible variants:");
                menu();
        }
    }

}

1 ответ 1

5
if (counter >= password.length - 2) counter = 0;

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.