Near the end of my program I have turned my user input into a chararray called letter. I want to iterate through letter and for each “letter” in the array, I would like to add or subtract the value of shiftCode. shiftCode can be a positive or a negative. I have a small part that functions where it simply adds 1 to the first letter of “letter”.
Can someone please tell me how to use i++ in order to iterate through each letter in letter and add or subtract using shiftCode value?
I THINK it will look something like
for(shiftCode; shiftCode === 26; shiftCode++) {
letter[EVERY LETTER IN THIS THING?] += shiftCode;
}
I can’t seem to figure out how to iterate for the value of shiftCode through each letter. If someone could point me in the right direction I would greatly appreciate it.
Thank you,
Aaron
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/*
* This program is designed to -
* Work as a Ceasar Cipher
*/
/**
*
*
*/
public class Prog3 {
static String codeWord;
static int shiftCode;
static int i;
static char[] letter;
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws IOException {
// Instantiating that Buffer Class
// We are going to use this to read data from the user; in buffer
// For performance related reasons
BufferedReader reader;
// Building the reader variable here
// Just a basic input buffer (Holds things for us)
reader = new BufferedReader(new InputStreamReader(System.in));
// Java speaks to us here / We get it to query our user
System.out.print("Please enter text to encrypt: ");
// Try to get their input here
try {
// Get their codeword using the reader
codeWord = reader.readLine();
// What ever they give us is probably wrong anyways.
// Make that input lowercase
codeWord = codeWord.toUpperCase();
letter = codeWord.toCharArray();
}
// If they messed up the input we let them know here and end the prog.
catch(Throwable t) {
System.out.println(t.toString());
System.out.println("You broke it. But you impressed me because"
+ "I don't know how you did it!");
}
// Java Speaks / Lets get their desired shift value
System.out.print("Please enter the shift value: ");
// Try for their input
try {
// We get their number here
shiftCode = Integer.parseInt(reader.readLine());
}
// Again; if the user broke it. We let them know.
catch(java.lang.NumberFormatException ioe) {
System.out.println(ioe.toString());
System.out.println("How did you break this? Use a number next time!");
}
letter[1] += 1;
System.out.println(letter[1]);
}
}
Here’s one way that you can iterate over an array.
I also notice that you don’t handle the error condition well; you should wrap all of the code that deals with
readerinside of thetry...catchblock.