java - 如何在java中将多个对象分配给分割字符串的一部分?

标签 java

这是我当前的代码:

    public static void main(String[ ] args)
{
    CodeBreaker thisProgram = new CodeBreaker();

    String uncodedMessage = " 83 101 110 100 32 121 111 117 114 32 116 101 97 99 104 101 114 32 97 110 32 101 109 97 105 108 32 116 111 100 97 121";

    thisProgram.decoder(uncodedMessage);
}

public void decoder(String codedMessage){
    String[] parts = codedMessage.split(" ");
    int numberOfCharactersRemaining = parts.length;
    int count = 0;

    while (count <= numberOfCharactersRemaining) {
        String[] partsOf = codedMessage.split(" ");
        int n = 0; 
        System.out.print(partsOf[1 + n] + " ");
        n = n + 1;
        count = count + 1;

    }

}

这会输出字符串中的第一个字符,而我想创建变量(第 1 部分、第 2 部分等)并为其分配字符串的相应部分,我该如何执行此操作?

最佳答案

您引用的部分已经存在于代码中,它们存储在 parts 变量中,可以通过 parts[0]、parts[1]、...、parts[x] 访问,其中 x 是数组的长度。

我对您的代码进行了一些更改以输出正确的结果。

public static void main(String[ ] args)
{
    CodeBreaker thisProgram = new CodeBreaker();
    String uncodedMessage = " 83 101 110 100 32 121 111 117 114 32 116 101 97 99 104 101 114 32 97 110 32 101 109 97 105 108 32 116 111 100 97 121";
    thisProgram.decoder(uncodedMessage);
}

public void decoder(String codedMessage)
{
    String[] parts = codedMessage.split(" ");
    int numberOfCharactersRemaining = parts.length;
    int count = 0;
    int n = 0; //This needs to be outside of the while loop so it doesn't reset to 0 every time.

    while (count < numberOfCharactersRemaining) //Removed equal comparison.
    {
        //Removed this since you have already split the code and stored it in the parts variable.
        //String[] partsOf = codedMessage.split(" "); 
        System.out.print(parts[n] + " "); //Removed the '+1' so it will not go out of bounds, changed also to parts[n] instead of partsOf[n].
        n = n + 1;
        count = count + 1;
    }
}

关于java - 如何在java中将多个对象分配给分割字符串的一部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43970789/

相关文章:

c# - 通过 COM4J 从 .NET 方法返回接口(interface)数组

java - 基本颠覆问题

Java 泛型 : actual argument T cannot be converted to int by method invocation conversion

java - Maven 如何为 create-schema 命令指定 sql 文件的目录

java - 如何在不创建新类也不修改类的情况下将 "append"新字段/数据放入对象中?

java - 安卓工作室/JAVA : How to trace error at android studio using "log"

java - AWS XRay - 请求期间无法开始名为 'AWSSecurityTokenService' : segment cannot be found, 的子分段

java - 如何避免Spring批量将元数据持久化到DB中

java - 在我的 R 类中出现奇怪的 Android 错误

java - 从 JTable 获取选定 JCheckBox 的数据