Letter Counter Code [duplicate] - java

This question already has answers here:
How do I count the number of occurrences of a char in a String?
(48 answers)
Closed 7 years ago.
//The Prompt is: Write a program that asks the user to enter a string, and //then ask the user to enter a character. The program should count and display //the number of times that the specified character appears in the string.
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 some reason I can't get it to work, I just don't know where to go from here. Do I possibly need a FOR-LOOP?
Thanks for your help

Hi have a look at this
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);
}
}
I selected the letter using
char kChar = keyboard.next().charAt(0);
and converted the String to a Char array, ran a for loop going through each letter and checking if it was the same as the selected character. Each time the check was true I added one to the character counter.

Yes, you'll need to use a for loop.
int count = 0;
for (char ch: userString.toCharArray()) {
if(userChar == ch) count++;
}

Related

How do I print a letter based on the index of the string?

I want to print a letter instead of the index position using the indexOf(); method.
The requirement is that: Inputs a second string from the user. Outputs the character after the first instance of the string in the phrase. If the string is not in the phrase, outputs a statement to that effect. For example, the input is 3, upside down, d. The output should be "e", I got part of it working where it inputs an integer rather than a string of that particular position. How would I output a string?
else if (option == 3){
int first = 0;
String letter = keyboard.next();
first = phrase.indexOf(letter,1);
if (first == -1){
System.out.print("'"+letter+"' is not in '"+phrase+"'");
}
else {
System.out.print(first + 1);
}
}
String.charAt(index)
You can access a single character, or a letter, by caling método charAt() from String class
Example
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String phrase = keyboard.nextLine();
char firstLetter = phrase.charAt(0);
System.out.println("First Letter : " + firstLetter);
}
So, running this code, assuming the input is StackOverFlow, the output will be S
In your code I think doing the follow will work:
Your Code
String letter = keyboard.next();
first = letter.charAt(0);
That might help!
Based on those comments
So, what you want is print the first letter based on a letter the user
has input? For example, for the word Keyboard, and user inputs letter
'a' the first letter might be 'R'. Is that it? – Guerino Rodella
Yes, I have to combine both the indexOf(): method and the charAt():
method – Hussain123
The idea is get next letter based on user input letter.
I'm not sure I wunderstood it, but this is my shot
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String phrase = "keyboard";
String userInput = keyboard.nextLine();
boolean notContainsInputValue = !phrase.contains(userInput);
if (notContainsInputValue) {
System.out.println("The input value doesn't exists");
return;
}
char firstLetter = userInput.charAt(0);
int desiredIndex = 0;
for (int i = 0; i < phrase.length(); i++) {
if (phrase.charAt(i) == firstLetter) {
desiredIndex = i;
break;
}
}
System.out.println("The index for your input letter is: " + desiredIndex);
System.out.println("Next letter based on input value is: " + phrase.charAt(desiredIndex + 1));
}
The Output
The index for your input letter is: 5
Next letter based on input value is: r
Hope that helps you.

Not a Statement Error - Where did I go wrong?

So, I am very new at coding but have a college assignment to create a Word Manipulator. I am supposed to get a string and an INT from the user and invert every Nth word, according to the int input.
I am following steps and am stuck with this error at line 38 (the start of my last FOR LOOP). The compiler is giving me an Not an Statement Error in this line but I cant see where I went wrong.
Could someone gimme a light, please?
ps: I am not allowed to use Token or inverse().
import java.util.Scanner;
public class assignment3 {
public static void main(String[] args) {
// BOTH INPUTS WERE TAKEN
Scanner input = new Scanner (System.in);
String stringInput;
int intInput;
System.out.println("Please enter a sentence");
stringInput = input.nextLine();
System.out.println("Please enter an integer from 1 to 10. \n We will invert every word in that position for you!");
intInput = input.nextInt();
int counter = 1;
// ALL CHARS NOW ARE LOWERCASE
String lowerCaseVersion = stringInput.toLowerCase();
// SPLIT THE STRING INTO ARRAY OF WORDS
String [] arrayOfWords = null;
String delimiter = " ";
arrayOfWords = lowerCaseVersion.split(delimiter);
for(int i=0; i< arrayOfWords.length; i++){
System.out.println(arrayOfWords[i]);
// THIS RETURNS AN ARRAY WITH ALL THE WORDS FROM THE INPUT
}
// IF THE INTEGER INPUT IS BIGGER THAN THE STRING.LENGTH, OUTPUT A MESSAGE
// THIS PART IS WORKING BUT I MIGHT WANT TO PUT IT IN A LOOP AND ASK FOR INPUT AGAIN
if (intInput > arrayOfWords.length){
System.out.println("There are not enough words in your sentence!");
}
// NOW I NEED TO REVERSE EVERY NTH WORD BASED ON THE USER INPUT
//THIS IS WHERE THE ERROR OCCURS
for(int i=(intInput-1); i<arrayOfWords.length; (i+intInput)){
char invertedWord[] = new char[arrayOfWords.length()];
for(int i=0; i < arrayOfWords.length();i++){
ch[i]=arrayOfWords.charAt(i);
}
for(int i=s.length()-1;i>=0;i--){
System.out.print(invertedWord[i]);
}
}
}
}
(i+intInput) isn't a statement. That's like saying 12. Perhaps you mean i=i+intInput or i+=intInput which assigns a value to a variable
well, for one thing, i dont see "s" (from s.length()) initiated anywhere in your code.

Java Creating a array and strings from user input

Im writing a program that first takes input from the user as an int then constructs an array that the user then types in individual characters that builds a string from that. i've written some code but I've come up with a form of writer's block and i don't know where to go from here. any help is greatly appreciated.
EDIT: im stuck on getting the string from the input into the array im getting an error where a method is not applicable. ill make in the code where the error is happening.
Example:
How many strings? 2
Enter string #1:
Enter an alphabetic string followed by enter: t
Enter an alphabetic string followed by enter: e
Enter an alphabetic string followed by enter: s
Enter an alphabetic string followed by enter: t
Enter an alphabetic string followed by enter: %
Enter string #2:
Enter an alphabetic string followed by enter: one
Enter an alphabetic string followed by enter: two
The strings you entered are:
test onetwo
code is below:
package workfiles;
//George Flamburis
import java.util.*;
public class Hw3 {
private static Scanner numScan;
public static void main(String[] args) {
int numstring=0;
numScan = new Scanner(System.in);
while (numstring <= 0 ){
System.out.print("How many strings? ");
numstring = numScan.nextInt();
if (numstring<1){
System.out.print("Please enter a positive (> 0) number.");
}
}
String[] stringarray = new String[numstring];
for (int i = 0; i < numstring; i++) {
//ERROR HAPPENING IN THIS CODE BELOW!!!
stringarray[i] = inputAlphaString();
}
numScan.close();
}
public static String inputAlphaString(Scanner aScan) {
Scanner strScan = new Scanner(System.in);
String t = "a";
String hold = "";
while(t.matches("[a-zA-Z]+")){
System.out.println("Enter an alphabetic string followed by enter: ");
t = strScan.nextLine();
hold = hold + t;
}
strScan.close();
return hold;
}
//added [] into the method name and int to i
public static void printSArray(String[] sArray) {
for (int i = 0; i <= sArray.length; i++)
System.out.print(sArray[i] + " ");
System.out.println();
}
}

Java string inside string

Write a program that asks the user to enter two Strings, and prints the number of times that the second String appears within the first String. For example, if the first String is "banana" and the second is "an", the program prints 2.
Below is my code so far
public class Assignment4 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Scanner answer = new Scanner(System.in);
//Prompt the user to enter a string
System.out.println("Enter a word:");
String input = answer.nextLine();
//Ask the user to enter a second String
//look at index method of string
System.out.println("Enter another word:");
String input2nd = answer.nextLine();
int counter = 0;
for(int i=0; i<input.length(); i++) {
if(input.charAt(i) == input2nd.charAt(0)) {
counter++;
}
}
System.out.println(input2nd + " appears " + counter + " times.");
When I type banana into first string, and second string is "an", the only thing come up is number 3, and it is for character a which appear 3 time, but not two as it suppose to only be 2 "an"
Consider this trick I learned years ago:
replace the searched word in the original word by emptychars...
get the diff between the length of both... searched chars and the original with replaced
divide that by the len of the searched word...
private static void searchString() {
Scanner answer = new Scanner(System.in);
// Prompt the user to enter a string
System.out.println("Enter a word:");
String input = answer.nextLine();
// Ask the user to enter a second String
// look at index method of string
System.out.println("Enter another word:");
String input2nd = answer.nextLine();
String a = input.replace(input2nd, "");
int counter = (input.length() - a.length()) / input2nd.length();
System.out.println(input2nd + " appears " + counter + " times.");
}
with the input banana and an will print 2

How to count instances of an specified char in a string in Java?

I've looked through everything relevant I can find on here, but for some reason nothing is helping. Whenever I run this I always end up with a result of 0. And no, I can not use other libraries for this (I saw some awesome solutions that have it down to one line, but I can't do that)
public void process()
{
Scanner input = new Scanner(System.in);
System.out.println("Enter your String:");
String in_string = input.nextLine();
Scanner input2 = new Scanner(System.in);
System.out.println("Press 1 to count the occurrence of a particular letter.");
System.out.println("Press 2 to count the total words in your input sentance.");
System.out.println("Press 3 to change your input sentance.");
System.out.println("Press 4 to exit.");
int option = input2.nextInt();
if (option==1)
{
System.out.println("Choose your letter: ");
String in_occurence = input.nextLine();
for(int i = 0 ; i < in_string.length(); i++)
{
if(in_occurence.equals(in_string.charAt(i)))
{
charCount++;
}
}
System.out.println(charCount);
}
You are comparing a String with a char using String#equals(). That will always give you false.
For example:
System.out.println("a".equals('a')); // false
You should convert the String to char by getting character at index 0 before comparison:
if(in_occurence.charAt(0) == in_string.charAt(i))
or, just declare in_occurrence as char type:
char in_occurence = input.nextLine().charAt(0);
You are comparing a String to a char which is never equal even if the String contains that char.
What you want is
if (in_occurance.charAt(0) == in_string.charAt(i)) // compare char

Categories