在程序接近尾声时,我已将用户输入转换为名为 letter 的字符数组。我想遍历字母,并且对于数组中的每个“字母”,我想添加或减去 shiftCode 的值。 shiftCode 可以是正数或负数。我有一小部分功能,它只是将 1 添加到“letter”的第一个字母。
有人可以告诉我如何使用 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]);
}
}
最佳答案
这是迭代数组的一种方法。
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
block 内。
关于java - 使用 CharToArray 和 foreach 以便根据用户选择增加或减少字母,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12328176/