gpt4 book ai didi

java - 将长文本拆分为多行代码,最好的方法是什么?

转载 作者:行者123 更新时间:2023-11-30 03:37:06 31 4
gpt4 key购买 nike

假设您想要显示游戏的欢迎消息,但需要将源代码中的行的最大长度保持为 80 个字符宽度。在游戏中,线条的长度并不重要。欢迎消息的示例如下:

private void welcomeMessage() {
System.out.println("Welcome to the game. This message should learn me how to create a long messages like this in a read-able fashion. Imagine there is a limit of 80 characters per line for a programmer to see. How to fix this efficiently? This is one large line in my IDEA. ");
}

这一行太长了,每行代码不能有 80 个字符,正如您通过滚动条看到的那样。我以前学会了简单地做这样的事情:

private void welcomeMessage() {
System.out.println("Welcome to the game. This message should learn me" +
" how to create a long messages like this in a read-able " +
"fashion. Imagine there is a limit of 80 characters per line for" +
" a programmer to see. How to fix this efficiently? This is one " +
"large line in my IDEA. ");
}

但是我发现这个解决方案很丑陋,这会产生一个非常烦人的依赖关系。如果我添加 “欢迎来到游戏。这条消息应该了解我” 只是一个词,我必须更改所有其他行,因此一行之后的所有行都取决于它。

我还可以想象仅仅以这种方式使其可读就会受到惩罚。这让我想知道:

  1. 编译器是否直接附加所有行,因为它们本身不依赖于其他变量,还是在运行时发生? (恐怕它会调用连接运算符函数('+')4次)
  2. 在此示例中,使用 .append() 的 StringBuffer 是否会更高效,因为它不会创建 5 个字符串,而是将其附加到 StringBuilder 对象?

想象一下这是一个真正的游戏,然后您会创建一个 txt 文本文件并使用 StringBuffer 等导入它以将其显示在屏幕上吗?或者您还可以如何显示更长的短信?

最佳答案

Does the compiler append all lines directly since they themselves do not depend on other variables or does it happen at runtime? (I am afraid that it would call the concatenation operator function ('+') 4 times)

编译器将连接字符串。无运行时开销。

Would a StringBuffer with .append() be more efficient in this example because it does not create 5 strings but instead appends it to the StringBuilder object?

没有。

<小时/>

演示:

class Test {
public static String test = "a" + "b" + "c";
}

命令

javac Test.java && javap -c -v Test

产生以下输出

[...]
Constant pool:
#1 = Methodref #5.#15 // java/lang/Object."<init>":()V
#2 = String #16 // abc
#3 = Fieldref #4.#17 // Test.test:Ljava/lang/String;
[...]

Code:
stack=1, locals=0, args_size=0
0: ldc #2 // String abc
2: putstatic #3 // Field test:Ljava/lang/String;
5: return

[...]

关于java - 将长文本拆分为多行代码,最好的方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27603425/

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