I'm stuck on this Java exercise problem and don't know how to organize my code with proper formatting and it's not helping that I'm pretty terrible at logic. I can't figure out how to return the number of spaces to be displayed in the main method.

Im stuck on this Java exercise problem and dont know how to organize my code with proper formatting and its not helping that Im pretty terrible at logic I cant class=

Respuesta :

In your "count spaces method" before the for loop, you want to declare an int variable (let's call it spc)

then, each time you find that charat, spc++.


also, the string must be declared in the main method, not the spaces count method.


The actual code:


public class CountSpaces{

public static void main(String[] args){

String instring = "(your quote here)";

int spaces = calculateSpaces(instring);

System.out.println("The number of spaces is " + spaces);

}

public static int calculateSpaces(String in){

int spc = 0;

for(int i= 0; i<in.length; i++){

if(in.charAt(i)== ' '){

spc++;

}

}

return spc;

}

}


that should be it.  If you have any questions, feel free to reach out.