Since it's homework, I'll just give you the next step; hopefully you can figure it out from there :)
In your for loop:
String num = nums[i];
x = Integer.parseInt(num);
سؤال
I am working on a homework assignment which encodes and decodes letters to int's and vice versa. The first encoding loop I have works great!
public static String Encode(String msg){
String result="";
String m = msg.toUpperCase();
char c;
int x;
for (int i = 0; i<m.length(); i++){
c = m.charAt(i);
x = c;
if (x == 32){
x = 0;
} else{
x -= 64;
if (x < 1 || x > 26){
x = 99;
}
}
result += String.valueOf(x) + " ";
}
return result;
}
It takes the string msg and runs a for loop to convert it into integer equivalent. My issue is the decoding. Essentially, the numbers you input would be entered in with a comma in between each number. I would then take the message into an array and split it to remove the commas. Then I would take it and read each value in a for loop and display the letter equivalent. This is where I am stuck. I understand the logic. It's basically reverse of the first loop, but I cannot seem to effectively code it. Here is what I have:
public static String Decode(String msg){
String result = "";
String m = msg;
char c;
int x;
String[] nums = msg.split(",");
for (int i = 0; i<nums.length; i++){
String num = nums[i];
x = Integer.parseInt(num);
if(x <= 0 || x > 26){
x=-1;
}
result += String.valueOf((char)(x + 64)) + " ";
}
return result;
}
I am having issues with reading the length of the nums array. I haven't had much luck with the rest of it. I understand that you have to parse the integers as well. Any insight into completing this would be greatly appreciated!
المحلول
Since it's homework, I'll just give you the next step; hopefully you can figure it out from there :)
In your for loop:
String num = nums[i];
x = Integer.parseInt(num);