2013-10-12 32 views
0

我想从输入的字符串中获取charAt值的字符串而不使用数组。 这是我到目前为止有:如何使用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); 
+2

'length'决不会小于或等于'长度1' ;-) – janos

+0

有道理。那么除此之外的其他条件是否所有其他条件都看起来不错? – user2874910

回答

0

而条件应该像(i<liength)

块支架{}失踪了一段时间。

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

+0

谢谢你的帮助。现在将加密转换回字符串,它会是一个类似的方法? – user2874910

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值。

相关问题