-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++;
       }

   }
}
4

3 回答 3

1

你也可以这样做:

 int count=0;
 String s ="Alaska";
        for(char ch : s.toCharArray()){
            if(ch=='A' || ch=='a'){
                count++;
            }
        }
 System.out.println("Number of A: "+count);
于 2014-10-25T03:54:09.920 回答
1

如果您遍历字符串的长度,您可以检查每个字母是否是“A”。

例如,

for (int i = 0; i < s.length(); i++) {
    if (s.substring(i, i+1).equalsIgnoreCase("a")) counter++;
}
于 2014-10-25T03:40:32.180 回答
0

一个例子是这样的:

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);
于 2014-10-25T03:49:19.993 回答