I want to make a program that takes a string and encrypts it.
During execution of program it is supposed to convert a string to char array. Then, a switch statement runs through the array to replace a with b and vice versa.
However, the programm just returns the same as at the start! here is the code
import java.lang.*;
import java.util.Scanner;
public class Program
{
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
String pw = input.next();
char pwa[] = pw.toCharArray();
for(char c : pwa ){
switch(c){
case 'a':
c = 'b';
break;
case 'b':
c ='a';
break;
}
}
String convpw = new String(pwa);
System.out.println(convpw);
}
}
You’re just changing the variable
c, notpwa, andcis local to your loop.You can do this :