0

我试图在不使用数组的情况下从输入的字符串中获取一串 charAt 值。这是我到目前为止所拥有的:

public static void main(String [] args){

   Scanner input = new Scanner(System.in);
   String str = "";  
   String encrypt = "";  
   int encry = 0;  
   int i = 0; 
   System.out.printf("Please enter a string: "); 
   str = input.nextLine();
   int length = str.length();
   System.out.println();
   while (length <= length-1)
      encry = str.charAt(++i);
      System.out.println(encry);
4

2 回答 2

0

while-condition 应该类似于(i<liength)

暂时缺少块括号{}

索引从 0 开始,因此它应该str.charAt(i++);代替str.charAt(++i);.

于 2013-10-12T22:05:25.307 回答
0

使用您已经取得的成果,我制作了一种加密方法。我还添加了一个解密方法:

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    System.out.printf("Please enter a string: ");
    String message = input.nextLine();
    String encryptedMessage = encrypt(message);
    System.out.println(encryptedMessage);
    System.out.println(decrypt(encryptedMessage));
    input.close();
}

public static String encrypt(String message) {
    String encrypted = "";
    int i = 0;
    int length = message.length();

    while (i < length) {
        int ascii = message.charAt(i++);
        encrypted += " " + ascii;
    }

    return encrypted.trim();
}

private static String decrypt(String encryptedMessage) {
    Scanner scanner = new Scanner(encryptedMessage);
    String decryptedMessage = "";

    while(scanner.hasNext()) {
        decryptedMessage += (char) scanner.nextInt();
    }

    scanner.close();

    return decryptedMessage;
}

挑战

在上面的代码中,加密的消息在代表一个字符的每组整数之间都有空格。看一眼加密的消息,很容易看出您只是将每个字符转换为对应的 ASCII 字符。

尝试在 ASCII 代码之间插入非数字字符,而不是空格。然后,在解密方法中,使用Scanner#useDelimiter该字符以检索 ASCII 值。

于 2013-10-13T04:08:05.553 回答