-2

I have working code that encrypts a phrase using a caesar cipher but this is with predetermined inputs (HELLOWORLD and 4 as the sift).

What I would like to do is enable a user to choose their own input and shift.

More specifically in the format:

e.g. $java Caesar 3 HELLOWORLD

and so "HELLOWORLD" is shifted 3 times

2 Answers2

0
Scanner scanner = new Scanner(System.in);
String string = scanner.nextLine();
int i = scanner.nextInt();

Ask your question then the user types the result in console.

0

To use commandline arguments, just use args[0] args[1] etc.. So in your example "3 HELLOWORLD" - 3 is args[0] and HELLOWORLD is args[1].

As shift is an integer you must parse it which converts it from a String to an Integer. To improve the code, you should catch any errors incase the String entered cannot be converted.

    public static StringBuffer rotate(int shift, String plainText){
    StringBuffer result= new StringBuffer();

    for (int i=0; i<plainText.length(); i++){
        if (Character.isUpperCase(plainText.charAt(i))){
            char ch = (char)(((int)plainText.charAt(i) + shift - 65) % 26 + 65);
            result.append(ch);
        }
        else{
            char ch = (char)(((int)plainText.charAt(i) + shift - 97) % 26 + 97);
            result.append(ch);
        }
    }
    return result;
}


public static void main(String[] args){
    String plainText = args[1];
    int shift = Integer.parseInt(args[0]);
    System.out.println("Text  : " + plainText);
    System.out.println("Shift : " + shift);
    System.out.println("Cipher: " + rotate(shift, plainText));
}

This is the output after using the arguments you mentioned

Tom
  • 215
  • 1
  • 10