-1

So I just started taking my first classing in programming with Java, so don't hurt me for being a new guy. I understand this may be a simple thing to do, but I'm stuck on where to even begin. I want to make a program that simply counts the number of characters in a string using the Scanner utility. So far I have...

import java.util.scanner
class Counter
{
   public static void main(String[] args)
   {
      Scanner input = new Scanner(System.in);
      System.out.println("Type a sentence, and I will tell you how many 
        characters are in it.");
      String sentence = input.nextString();

And this is as far as I have gotten. What I want to do is the previous plus...

Char character;

and do something with that, maybe a for-loop, but I'm simply stumped. And even if I did want to do this I wouldn't know how to go about it. Any ideas?

Thanks! ~Andrew

EDIT:

import java.util.Scanner;  
class Counter
{
   public static void main(String[] args)
   {
      Scanner input = new Scanner(System.in);
      System.out.println("Type a sentence, and I will tell you how many 
        characters are in it.");
      String sentence = input.nextLine();
      sentence = sentence.trim();
      System.out.print("This sentence has " + sentence.length() + "    
         characters in it.");
   }
}

Did not seem to work.

Andrew M
  • 93
  • 8

2 Answers2

1
  1. You have to use input.nextLine() instead of input.nextString() to capture the sentence given by the user.

  2. You also have to use the trim() method on that sentence to delete the spaces given by the user in the front and back side of the sentence. Ex: sentence.trim()

  3. You can get the length of the sentence by the length() method. Ex: sentence.length()

Now, I am giving you the full code to count letters of a given sentence:

import java.util.Scanner;

public class LetterCount 
{
    public static void main(String[] args) 
    {
        Scanner input = new Scanner(System.in);
        System.out.println("Type a sentence, and I will tell you how many characters are in it.");
        String sentence = input.nextLine();
        System.out.print("This sentence has " + sentence.trim().length() + " characters in it.");       
    }
}
Avijit Karmakar
  • 6,843
  • 5
  • 30
  • 53
-1

First of all, to read by Scanner you have to use input.nextLine(); instead of input.nextString();.

After, you can use .length() function to know how much positions have your String (how much chars have your String) so you won't have to convert it to any char or whatever.

System.out.println(sentence.length());

I expect it will be helpful for you!

Francisco Romero
  • 11,900
  • 18
  • 71
  • 151