This week's book giveaway is in the Java in General forum. We're giving away four copies of Beginning Java 17 Fundamentals: Object-Oriented Programming in Java 17 and have ishori Sharan & Adam L Davis on-line! See this thread for details.
I'm currently enrolled in a Computer Science class in high school, and we were recently assigned a program which is a modified version of a program in David J. Eck's online text. The original program is available here: http://math.hws.edu/javanotes/c4/ex1-ans.html
The assignment the class was given was to modify the program so that it asks the user to enter a string, code word, and whether to encode or decode the phrase. The program uses the simple encoding technique of matching up the numerical value of a character and adding it to the original string. Following is the code I have worked and attempted to debug over the past couple days:
There are two main problems I am experiencing. Our specifications say to test the program using the message "Taxi Cab" and the code word "cafe". When adding the numerical value 6 (from the 'f' in cafe) to the string, my program does not wrap around to the beginning of the alphabet, and simply keeps going through the unicode character set. The second problem is that although I use a counter variable to determine which part of the code word I am adding to the string, the counter doesn't seem to reset itself properly.
Any input or advice that anyone is willing to contribute to my program would be greatly appreciated. Also, please excuse my amateur style
For your first problem, there are a couple of solutions, but you're going to have to be intelligent about your use of capitals.
The first option is to check to see if the character code is larger than 'z'. If it is, subtract 26 from it. BUT notice that Z + B doesn't give you a letter, but it also isn't greater than 'z'.
The second option is to use the modulo operation. Subtract 'A' from both the input and the keyword, so that all of the characters are between 0 and 25. Then, when you get your result, do this: result = result % 26. Then, add 'A' back into the picture. This will give you the wrap around that you want. You need to be careful about capitals, again, here, though. If you have a capital letter you want to subtract and re-add 'A', if you have a lowercase letter, you want to subtract and re-add 'a'.
With regard to your second question, I would wait to see if the fix to your first problem gets things working for you. I'm not entirely sure that your counter doesn't reset itself. It may have to do with forgetting to deal with capitals.