-2

Alright, so here is my dilemma. Unfortunately my Java teacher does not teach how to start the projects in class, nor does he tell us where to find the information to start the program. This is my first programming course, so I'm still trying to learn a few things.

So, lets get to the point, he wants it to look like this:

This program is written by Ben Barcomb

Enter a String: Alaska

Number of A: 3

//End of program

That is it. I just don't know where to start. Any help would be greatly appreciated! This is what I have right now. The program ends after I enter Alaska.

import java.util.Scanner;

public class P4_BenjaminBarcomb
{
   public static void main(String[] args)
   {
       System.out.println("This program is written by Benjamin Barcomb\n");

       Scanner kb = new Scanner(System.in);

       int counter = 0;
       System.out.print("Enter a String: ");
       String word = kb.next();



       for (int i = 0; i < word.length(); i++) {
         if (word.substring(i, i+1).equalsIgnoreCase("a"))
         counter++;
       }

   }
}
  • Well before you can count the number of characters in a String, you need to know how to capture data that someone types into your program. I suggest you Google around for examples of how to read command-line arguments. – Hunter McMillen Oct 25 '14 at 03:38
  • Right, well I know how to get the user input without a problem, but it's calculating the number of A's in the string. – Benjamin Barcomb Oct 25 '14 at 03:41
  • Can you print the first line `This program is written by Ben Barcomb`? If not, you should focus on smaller problems rather than thinking about the whole program at this point. – takendarkk Oct 25 '14 at 03:41
  • Yes I can, I should have added that in the description, I just need help as to getting the number of A's in the program. – Benjamin Barcomb Oct 25 '14 at 03:42

3 Answers3

1

If you loop through the length of the string, you can check to see whether each letter is an "A".

For example,

for (int i = 0; i < s.length(); i++) {
    if (s.substring(i, i+1).equalsIgnoreCase("a")) counter++;
}
1

you can also do like this:

 int count=0;
 String s ="Alaska";
        for(char ch : s.toCharArray()){
            if(ch=='A' || ch=='a'){
                count++;
            }
        }
 System.out.println("Number of A: "+count);
Rustam
  • 6,485
  • 1
  • 25
  • 25
0

An example is this:

import java.util.Scanner;
public class Junk {
public static void main(String[] args) {
Scanner Keyboard = new Scanner(System.in);
System.out.print("Enter a String: ");
String str = Keyboard.nextLine();
for (int i = 0; i < str.length(); i++){
if (str.substring(i, i+1).equalsIgnoreCase("a")){
count++;
}
}
System.out.println("Number of A: "+count);
Fafore Tunde
  • 319
  • 2
  • 8