Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I have this code that encrypts or decrypts text. Is there a simpler way to code

ID: 3902796 • Letter: I

Question

I have this code that encrypts or decrypts text. Is there a simpler way to code it without using stringbuilder and append? I do not want to use anything complicated, just looking to use simpler strings and methods.

import java.util.Scanner;

public class Program4 {

public static void main(String[] args) {
  Scanner sc = new Scanner(System.in);
  System.out.println("Enter your choice e for encrypt d for decrypt");
  String choice = sc.nextLine();
  String text = "";

  int n = 23;
  StringBuilder conversion = new StringBuilder();
  if ("e".equals(choice)) {
   System.out.println("Enter string to be encrypted");
   text = sc.nextLine();
  } else if ("d".equals(choice)) {
   System.out.println("Enter string to be decrypted");
   text = sc.nextLine();
   char[] textChar = text.toCharArray();
   
   n = 3;
  }

  char[] textChar = text.toCharArray();
  for (char c : textChar) {
   if (Character.isUpperCase(c)) {
    
    char ch = (char) (((int) c + n - 65) % 26 + 65);
    conversion.append(ch);
   } else if (Character.isLowerCase(c)) {
   
    char ch = (char) (((int) c + n - 97) % 26 + 97);
    conversion.append(ch);
   } else {
    conversion.append(c);
   }
  }
  if ("e".equals(choice)) {
   System.out.println("Encrypt: " + text);
   System.out.println("Encrypted result: " + conversion);
  } else if ("d".equals(choice)) {
   System.out.println("Decrypted: " + text);
   System.out.println("Decrypted result: " + conversion);
  }
}
}

Explanation / Answer

import java.util.Scanner;

public class Program4 {

public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter your choice e for encrypt d for decrypt");
String choice = sc.nextLine();
String text = "";

int n = 23;
String conversion="";
if ("e".equals(choice)) {
System.out.println("Enter string to be encrypted");
text = sc.nextLine();
} else if ("d".equals(choice)) {
System.out.println("Enter string to be decrypted");
text = sc.nextLine();
char[] textChar = text.toCharArray();

n = 3;
}

char[] textChar = text.toCharArray();
for (char c : textChar) {
char ch=c;
if (Character.isUpperCase(c)) {
  
ch = (char) (((int) c + n - 65) % 26 + 65);
} else if (Character.isLowerCase(c)) {
ch = (char) (((int) c + n - 97) % 26 + 97);
}
conversion+=ch;
}
if ("e".equals(choice)) {
System.out.println("Encrypt: " + text);
System.out.println("Encrypted result: " + conversion);
} else if ("d".equals(choice)) {
System.out.println("Decrypted: " + text);
System.out.println("Decrypted result: " + conversion);
}
}
}

Do give a thumbs up