196k views
4 votes
. Write a short program that asks the user to input a string, and then outputs the

number of characters in the string.

User LRLucena
by
5.5k points

1 Answer

2 votes

Answer:

// program in java.

// package

import java.util.*;

// class definition

class Main

{

// main method of the class

public static void main (String[] args) throws java.lang.Exception

{

try{

// object to read input from user

Scanner scr=new Scanner(System.in);

System.out.print("Enter a string:");

// read input

String myString=scr.nextLine();

// variable to store characters count

int char_count=0;

// count the characters

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

if(myString.charAt(i) != ' ')

char_count++;

}

// print the number of character

System.out.println("total characters in the String: "+char_count);

}catch(Exception ex){

return;}

}

}

Step-by-step explanation:

Read a string from user with the help of Scanner object and assign it to variable "myString".Iterate over the string and if character is not space (' ') then char_count++. After the loop print the number of characters in the string.

Output:

Enter a string:hello world

total characters in the String: 10

User Pramesh
by
5.2k points