Search code examples
javaindexingcaesar-cipher

I'm having trouble trying to get the character at an index


This is my code:

package ch3;

import java.util.Scanner;

public class caesarCypher {

    static String inp;

    public static void main(String[] args) {
        int input;
        int x = 0;
        Scanner scan = new Scanner(System.in);
        inp = scan.nextLine();

        input = inp.length();
        System.out.println(input + inp);
        while (x < input) {
            x += 1;
            inp =  ((inp.charAt(x)) - 12);
        }   
    }
}

how would I go about setting the index of inp to x? So to rephrase, I'm trying to subtract the character, for example, a - 12 on the ASCII table.


Solution

  • Try using a char array:

    public class caesarCypher {
    
        static String inp;
    
        public static void main(String[] args) {
            int input;
            Scanner scan = new Scanner(System.in);
            inp = scan.nextLine();
            char[] inpArr = inp.toCharArray();
    
            input = inp.length();
            System.out.println(input + inp);
            for( int i = 0; i < input; i++)
            {
                inpArr[i] -= 12;
            }
    
            inp = new String( inpArr);
        }
    }
    

    As a side note, you will get an IndexOutOfBoundsException from the below code. Use x, then increment it.

    while (x < input) {
        x += 1;
        inp =  ((inp.charAt(x)) - 12);
    }