Hi everyone,
Today we will solve an algorithm problem with Java language!
The program we need to make will be as follows: We will take a sentence from the console, count how many space characters there are in this sentence and print it to the console.
Let's start!
First of all, we need to define and import the Scanner class since we will receive data from the console.
We will define this above the main class in the program and write our codes in the main method.
We defined the Scanner object.
Now we will ask to enter a sentence into the console with the print command.
We will take this sentence from the console, assign it to a variable and start performing our operations.
We created a string variable named "sentence" and assigned the value received from the console there.
We will get the length of the sentence with length(), one of the string methods!
By making a definition like this, we ensure that the length of the sentence in the sentence variable is assigned to an int variable called sentenceLength.
Now it's time to count the spaces in the sentence.
int counter = 0;
for(int i=0; i<sentenceLength; i++){
if(sentence.charAt(i) == ' '){
counter++;
}
}
This code will first create the counter variable by assigning it the value 0. The loop variable will also start at 0 and will be increased by one at each step until i is one less than the length of the sentence. The reason why we say i < sentenceLength here is that since indexing starts from zero in programming, the last character will correspond to one minus the length of the array.
By defining if in the loop and checking each character in the sentence variable with the charAt() method in the condition block, when it is equal to a space, the counter variable will be incremented by one, and if it is not equal to a space character, the loop will return and the other index will be checked from the beginning. In this way, all the gaps will be calculated.
Finally, the number of space characters in the sentence will be printed to the console.
Yes, this is the logic of the program that finds the number of space characters in the entered sentence. You can also do it in different ways. You can express your opinions or questions in the comments.