CSC 1106 Lab 07.2 ailings Review View Normal No SpacingHeading 1Heading 2 3) Wri
ID: 3930815 • Letter: C
Question
CSC 1106 Lab 07.2 ailings Review View Normal No SpacingHeading 1Heading 2 3) Write a program to count the number of blank characters in a given string. Ask the user to input a sentence, and display the number of blank characters in the sentence. Assume there is no space before the first word, and no space after the last word of a given sentence. Note the verb usage is different depending upon the number of blank characters. The output message should be adjusted accordingly. Please enter a sentehce: Make America great again. There are 3 blank characters. Please enter a sentence: Stronger together. There is 1 blank character. I Please enter a sentence: Vote2016 There is no blank character.Explanation / Answer
Changes in existing code:: Accept input as keyboard.nextLine().You are using next() function due to that it is not accepting whole sentence ,it just accepts single word.And I have added if condition to check whether char at each positon is blank or not.I have given changed code with comments And also added at which position blank character found.
Code::
import java.util.Scanner;
public class Blanks
{
public static void main(String[] args)
{
int position=0;
int count=0;
String input;
Scanner keyboard;
keyboard = new Scanner(System.in);
//Accept Input from User
System.out.println("Input a sentence");
input=keyboard.nextLine();
//Traverse through string
while(position < input.length())
{
char ch=input.charAt(position);
//check for each character whether it is blank or not
if(ch==' ')
{
//if it is blank character then increment count by 1
count++;
//Print at which position blank charcter found
System.out.println(count+"st Blank Space found at Position::"+position);
}
position++;
}
//condition for no blank character
if(count==0)
{
System.out.println("There is no blank character");
}
//print total count of blank spaces
System.out.println("The number of blank spaces::"+count);
keyboard.close();
}
}
/*......Input&output......*/
1)
Input a sentence
Make America Great Again
1st Blank Space found at Position::4
2st Blank Space found at Position::12
3st Blank Space found at Position::18
The number of blank spaces::3
2)
Input a sentence
Stronger Together
1st Blank Space found at Position::8
The number of blank spaces::1
3)
Input a sentence
Vote2016
There is no blank character
The number of blank spaces::0
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.