0
import javax.swing.*;
public class TestProject {

    public static void main(String[] args) {

        String test = "Hel lo !";

        String[] array = new String[test.length()];

        for (int a=0; a<test.length(); a++) {
            array[a] = test.substring(a, (a+1));
        }
        NoSpaces(array);

        for (int g=0; g<test.length(); g++) {
            System.out.print(array[g]);
        }

    }
    public static String[] NoSpaces(String[] theArray) {
        int count=0;

        for (int c=0; c<theArray.length; c++) {
            if (theArray[c] == " ") {
                count++;
            }
        }
        String[] d = new String[theArray.length-count];

        for (int f=0; f<(theArray.length-count); f++) {
            if (theArray[f] != " ") {
                d[f]=theArray[f];
            }
        }
        return d;
    }


}

I'm trying to create a program that takes a phrase constructed from user input and stores them into an array, and then to make a static method to return an array with the output being the input, except with no spaces. Here I declared a test String and stored them into an array. Then I print out the array modified by my static method. My static method includes making a new array with a length of the original String minus the spaces and only included the non-space characters. However, when I run my code, it prints the exact same thing as my input. What error did I make in my code?

asp211
  • 11
  • 5
  • Ok, thanks, I fixed that. But it still doesn't print the desired output; it doesn't change. – asp211 Dec 05 '17 at 00:05
  • for (int g=0; g – RAZ_Muh_Taz Dec 05 '17 at 00:06
  • you need to print the array by each index, you are just trying to print the array object. An array is not a string so you need to go through each element and print it seperately – RAZ_Muh_Taz Dec 05 '17 at 00:06
  • How did my code not change anything? I input a String and it returned the same String. I fixed the printing array problem. – asp211 Dec 05 '17 at 00:08
  • you need to do the following assigment, array = NoSpaces(array); you never are assigning the newly created array returned by your method – RAZ_Muh_Taz Dec 05 '17 at 00:10
  • `if (theArray[c] == " ") {` - This doesn't work in Java. You need to use `.equals()`. – D M Dec 05 '17 at 00:25
  • I did that. It still didn't change anything.Oh wait I'll try that. – asp211 Dec 05 '17 at 00:25
  • Still didn't work. – asp211 Dec 05 '17 at 00:28
  • There's a problem with what you're doing in that last `for` loop, beyond the `==` and `!=` problem. You're transferring from one array to the other, using the same location in both arrays. But if there are spaces, you don't want to be in the same location in both arrays. If it's "Hi World" then, after you remove the spaces, the W needs to move up a spot. – D M Dec 05 '17 at 00:38
  • Then what changes should I make to my code? – asp211 Dec 05 '17 at 00:52

0 Answers0