gpt4 book ai didi

java - 为什么我遇到以下代码 :Exception in thread "main" java. lang.OutOfMemoryError: Java 堆空间错误

转载 作者:行者123 更新时间:2023-12-02 06:15:42 24 4
gpt4 key购买 nike

创建一个程序,要求用户输入单词,直到用户输入空字符串。然后程序打印用户给出的单词。

输入一个词:

李斯特

我编写了以下代码,但出现上述错误:

public static void main(String[] args) {

   Scanner input = new Scanner(System.in);
String word = input.nextLine();
ArrayList<String> words = new ArrayList<String>();

System.out.println("Type a word: "+ word);

while(word.isEmpty() == false)
{
words.add(word);
}

for (String wd : words){
System.out.println("You typed the following words:");
System.out.println( wd);
}

最佳答案

问题出在这部分代码:

   while(word.isEmpty() == false)
{
words.add(word);
}

您不断地将word添加到words列表中,而不更改word的内容。因此,您的应用程序会消耗所有可用内存,然后因 OOM 异常而崩溃。

从代码的上下文来看,我假设这就是您想要做的:

import java.util.*;

public class Test {
public static void main(String[] args) {

Scanner input = new Scanner(System.in);
ArrayList<String> words = new ArrayList<String>();

while (input.hasNextLine()) {
String word = input.nextLine();
words.add(word);
}

for (String wd: words) {
System.out.println("You typed the following words:");
System.out.println(wd);
}
}
}

关于java - 为什么我遇到以下代码 :Exception in thread "main" java. lang.OutOfMemoryError: Java 堆空间错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55872958/

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