I’m pretty new when it comes to coding in java (or coding in general), and I want the code below to print out only the end result (3), but it prints everything beforehand too, then once it reaches the end it gives me a runtime error
JavaScript
x
package programs;
public class practice2
{
public static void main(String [] args)
{
//create a program that counts spaces in a string
String sentence = "test if this works";
int count = 0;
for(int i = 0; i <= sentence.length(); ++i)
{
String space = sentence.substring(i, i+1);
if(space.equals(" "))
{
count = count + 1;
}
System.out.println(count);
}
}
}
Advertisement
Answer
To get the final output, you need to move the print statement outside of the for
loop. As for the runtime error, change the looping condition to i < sentence.length()
instead of i <= sentence.length()
because indexing starts from 0 and end at length-1.