在我的程序结束时,我已将用户输入转换为名为letter的字符。我想迭代字母和数组中的每个“字母”,我想添加或减去shiftCode的值。 shiftCode可以是正面的也可以是负面的。我有一小部分功能,它只是在“字母”的第一个字母上加1。
有人可以告诉我如何使用i ++来迭代字母中的每个字母并使用shiftCode值加减:
我认为它看起来像
for(shiftCode; shiftCode === 26; shiftCode++) {
letter[EVERY LETTER IN THIS THING?] += shiftCode;
}
我似乎无法弄清楚如何通过每个字母迭代shiftCode的值。如果有人能指出我正确的方向,我将非常感激。
谢谢你, 亚伦
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]);
}
}
答案 0 :(得分:2)
这是一种可以迭代数组的方法。
for(int i = 0; i < letter.length; i++) {
// using i, you can manipulate and access all elements of the array.
letter[i] -= shiftCode; // may want more logic in this case.
}
我也注意到你没有很好地处理错误状态;你应该在reader
块中包含所有处理try...catch
的代码。