CSC 1106 Lab 072 ailings Review View Normal No SpacingHeadin
Solution
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


