sách gpt4 ai đã đi

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

In lại 作者:行者123 更新时间:2023-12-02 06:15:42 hai mươi bốn 4
mua khóa gpt4 Nike

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

输入一个词:

李斯特

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

public static void main(String[] args) {

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

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);
}

1 Câu trả lời

问题出在这部分代码:

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

您不断地将wordThêm vàowords列表中,而不更改word的内容。因此,您的应用程序会消耗所有可用内存,然后因 OOM 异常而崩溃。

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

import java.util.*;

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

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

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/

hai mươi bốn 4 0
行者123
Hồ sơ cá nhân

Tôi là một lập trình viên xuất sắc, rất giỏi!

Nhận phiếu giảm giá Didi Taxi miễn phí
Mã giảm giá Didi Taxi
Giấy chứng nhận ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com