gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 11:29:23 24 4
gpt4 key购买 nike

这是我当前的代码:

    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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com