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