Java Lab: Count Characters

preview_player
Показать описание
----------------------------------------------------------------------------------------
Social media:
----------------------------------------------------------------------------------------

Code in comments
Рекомендации по теме
Комментарии
Автор

Bit of a problem here, it doesn't append an "'s" onto the character in the case of plurals, which it needs to do in order to satisfy the requirements of the lab. I rewrote it using a bit of a simpler process in case anybody is struggling:

import java.util.Scanner;

public class LabProgram {
public static void main(String[] args) {
Scanner scnr = new Scanner (System.in);
char userLetter;
String userWord;

userLetter = scnr.next().charAt(0);
userWord = scnr.nextLine();

int wordCount = 0;

for (int i = 0; i < userWord.length(); i++) {
if (userWord.charAt(i) == userLetter){
wordCount++;
}}

if (wordCount ==1) {
System.out.println(wordCount + " " + userLetter);
}
else {
System.out.println(wordCount + " " + userLetter + "'s");
}
}
}

キュウリジョー
Автор

im about to type this word for word just to discover errors. thanks

Iphone-jgpo
Автор

import java.util.Scanner;

public class LabProgram {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);

char character = scnr.next().charAt(0);

String string = scnr.nextLine();
System.out.println(countChar(character, string));

}

public static int countChar(char c, String s){

int counter = 0;

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

if(c == s.charAt(i))
counter++;
}

return counter;

}
}

collegehelper