0

在我的程序快结束时,我将用户输入变成了一个名为 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]);
    }
}
4

1 回答 1

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.
    }

我还注意到您没有很好地处理错误情况;您应该将处理块内部的所有代码包装起来。readertry...catch

于 2012-09-08T05:13:08.523 回答