//提示符是:编写一个程序,要求用户输入一个字符串,然后//然后要求用户输入一个字符。程序应计算并显示//指定字符在字符串中出现的次数。
import java.util.Scanner;
public class LetterCounter{
Scanner keyboard = new Scanner (System.in); //Scanner
// Declare Variables
String userString; // String user entered
String userCharacter; // Character user entered
int StringSize;
// Ask the user to enter a string
System.out.println("Please Enter a String.");
userString = keyboard.nextLine();
// Ask the user to enter a charcter
System.out.println("Please Enter a Character.");
userCharacter = keyboard.nextLine();
// Count and display the number of times that character appears in the
// string chosen by the user.
int character;
character = Integer.parseInt(userCharacter);
StringSize = userString.charAt(character);
}
}
出于某种原因,我无法让它工作,我只是不知道从哪里开始。我可能需要一个FOR-LOOP吗?
感谢您的帮助
答案 0 :(得分:1)
嗨看看这个
package gmit;
import java.util.Scanner;
public class LetterCounter{
public static void main(String[] args) {
String keyBoardChar;
Scanner keyboard = new Scanner (System.in); //Scanner
// Declare Variables
String userString; // String user entered
char userCharacter; // Character user entered
int StringSize;
// Ask the user to enter a string
System.out.println("Please enter a string");
userString = keyboard.nextLine();
// Ask the user to enter a charcter
System.out.println("Please Enter a Character.");
char kChar = keyboard.next().charAt(0);
// Count and display the number of times that character appears in the
// string chosen by the user.
int character = 0;
//character = Integer.parseInt(userCharacter);
//StringSize = userString.charAt(character);
char[] StringToChar = userString.toCharArray();
for(int i = 0; i < StringToChar.length - 1; i++){
if ( StringToChar[i] == kChar){
character++;
}
}
System.out.println("character count is " + character);
} }
我选择了这封信 char kChar = keyboard.next()。charAt(0);
并将String转换为Char数组,运行for循环遍历每个字母并检查它是否与所选字符相同。每次检查结果为真,我都会在字符计数器中添加一个。
答案 1 :(得分:0)
是的,你需要使用for循环。
int count = 0;
for (char ch: userString.toCharArray()) {
if(userChar == ch) count++;
}