gpt4 book ai didi

java - 我正在尝试制作一个简单的程序,用 'a' 符号替换 'e' 、 'i' 、 "*"但我收到此错误代码

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:54:17 26 4
gpt4 key购买 nike

所以我正在努力为即将到来的 final 练习,我只是为了好玩和学习而随机编码。今晚我偶然发现了这个我以前从未见过的错误代码。我的代码似乎没有进入 for 循环,然后弹出错误消息。有任何想法吗?谢谢你!

Please enter a sentence
Testing the program
You entered :
testing the program

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at java.util.Arrays.copyOf(Arrays.java:3332)
at java.lang.AbstractStringBuilder.expandCapacity(AbstractStringBuilder.java:137)
at java.lang.AbstractStringBuilder.ensureCapacityInternal(AbstractStringBuilder.java:121)
at java.lang.AbstractStringBuilder.append(AbstractStringBuilder.java:421)
at java.lang.StringBuilder.append(StringBuilder.java:136)
at FinalStudy.main(FinalStudy.java:22)


public static void main(String[] args) 
{
Scanner input=new Scanner(System.in);
System.out.println("Please enter a sentence");

String sentence=input.nextLine();
sentence=sentence.toLowerCase();

System.out.println("You entered : \n" + sentence);
//Doesn't seem to make it to this loop because it only prints the initial sentence
for (int i=0; i<sentence.length(); i++)
{
if (sentence.charAt(i)=='a' || sentence.charAt(i)=='e' || sentence.charAt(i)=='i')
{
sentence=sentence.substring(0,i) + "*" + sentence.substring(0,(i+1));
}
}

System.out.println("This is your new sentence: \n" + sentence);
}

最佳答案

TLDR:这里是一个无限循环,它会扩展字符串“句子”,直到内存不足。但我不会确切地告诉您如何解决您的问题。

此外,您还需要学习如何在程序中使用断点和打印语句进行调试。一个简单的谷歌搜索就足够了。

为什么它不起作用的解释:

Imagine that I input the sentence "abc" and let's go through the for loop.
First, i = 0, and the length of 'sentence' = 3.
sentence.charAt(0) == 'a' is true
thus 'sentence' is now set to be the substring from 0 up to 0 (nothing),
plus '*', plus the substring from 0, up to 1 ("a").
Now the String 'sentence' is set to "*a".
i = 1, length = 2,
sentence.charAt(1) == 'a' is true
'sentence' is now set to be the substring from 0 up to 1 ("*"),
plus '*', plus the substring from 0 up to 2 ("*a");
Now the String 'sentence' is set to ***a
The for loop continues in this manner, doubling the length of the string
'sentence' whenever the variable i reaches sentence.length()-1. Eventually the
computer runs out of memory because it cannot store an infinite length string
and the program crashes.

一些提示:当您单击 IDE 中的行号时,这会导致出现“断点”。这意味着如果你在“ Debug模式”下运行程序,解释器会在那一行暂停,让你看到一些信息,比如某些变量的值。调试时的另一个技巧是使用打印语句来显示有关代码中发生的事情的信息,通常以这种方式显示变量。

PS 大家都曾经这样问过问题,所以不要因为找不到问题而气馁。以后使用上面的建议先尝试调试,再尝试其他来源的解决方案。通常,像这样的简单错误是问题的原因,可以通过调试找到它们。

关于java - 我正在尝试制作一个简单的程序,用 'a' 符号替换 'e' 、 'i' 、 "*"但我收到此错误代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34279894/

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