简体   繁体   中英

I am trying make a simple program that replaces 'a', 'e', 'i' with the “*” symbol but i'm getting this error code

So i'm trying to practice for an upcoming final and i'm just doing random coding for fun and to learn. Tonight I have stumbled upon this error code that i've never seen before. My code does not seem to make it to the for loop and then the error message pops up. Any ideas? Thank you!

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: What you have here is an infinite loop that expands the String 'sentence' until you run out of memory. But I won't tell you exactly how to solve your problem.

Also, you need to learn how to use breakpoints and prints statements within your program to debug. A simple google search should suffice.

Explanation of why it doesn't work:

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.

A few tips: When you click the line numbers in your IDE this causes there to be a "breakpoint". What this means is that if you run the program in "debug mode", the interpreter will pause at that line and allow you to see some information, like the value of certain variables. Another trick when debugging is to use print statements to display information about what is happening in the code, often displaying variables in this manner.

PS Everyone was once like this asking questions, so don't feel discouraged that you couldn't figure out the problem. In the future use the suggestions above to try to debug first, then try other sources of a solution. Often times simple mistakes like that are the cause of the problem and they can be found by debugging.

use replace method

    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++)
// {

    sentence = sentence.replace('a', '*');
    sentence = sentence.replace('e', '*');
    sentence = sentence.replace('i', '*');

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

Very simple:

String str = "abciabehgitye";
str = str.replaceAll("[aei]", "*");
System.out.println("str = " + str); // str = *bc**b*hg*ty*

The modification of sentence inside your for loop is wrong and it changes (increases) the length of the string causing an infinite loop .

Change it as follows :

if (sentence.charAt(i)=='a' || sentence.charAt(i)=='e' || sentence.charAt(i)=='i') {     

     sentence = sentence.substring(0,i) + "*" + sentence.substring(i+1,sentence.length());

     }

This will output the correct result.

You can also simply use string replace / replaceAll methods to achieve your result.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM