0

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.

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
dirtydan
  • 36
  • 1
  • 5

2 Answers2

1

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);
}  
uoyilmaz
  • 3,035
  • 14
  • 25
1

As far as I understand your goal, you want to read in a String and then shift it's chars in the ascii table?

A char is a 16 bit unsigned number, a kinda int derivate, that's why it is interpreted as an int.

but you're trying to assign an int back to your inp String:

inp = ((inp.charAt(x)) - 12);

This fails of course.

Because Strings are immutable in java you have to create a new String every time.

You can use Character.toString(char c) to get the actual char from an int value in the ascii table. This will set an offset of 12 to your input string

   int offset = 12;
   Scanner scan = new Scanner(System.in);
   inp = scan.nextLine(); 
   String shifted ="";
   for (int i = 0; i < inp.length(); i++) {
        char c = (char)((inp.charAt(i)) - offset);
        shifted+= Character.toString(c);
    }  
    System.out.println(shifted);
    scan.close();
Mad Matts
  • 1,118
  • 10
  • 14