I am trying to write a for loop in Java that will count the occurrences of a letter in a string. The user will enter the letter to count and the string in which to search. This is a very basic code, and we have not gotten to arrays or much else yet. (I realize that I declared letter twice, but my brain is dead at this point) This is what I have tried so far and am having trouble with, any help is appreciated:
Ok I changed my code per suggestions, but now it is only reading the first word of my sentence?
import java.util.Scanner;
public class CountCharacters {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
char letter;
String sentence = "";
System.out.println("Enter a character for which to search");
letter = in.next().charAt(0);
System.out.println("Enter the string to search");
sentence = in.next();
int count = 0;
for (int i = 0; i < sentence.length(); i++) {
char ch = sentence.charAt(i);
if (ch == letter) {
count++;
}
}
System.out.printf("There are %d occurrences of %s in %s", count,
letter, sentence);
}
}
I see a couple of issues. First you have two variables with the same name.
Second your if condition check for the lenght of the sentence to be greater then 0 instead of checking for character equality.
Scanner in = new Scanner(System.in);
char inLetter = "";
String sentence = "";
System.out.println("Enter a character for which to search");
inLetter = in.next().charAt(0);
System.out.println("Enter the string to search");
sentence = in.next();
int letter = 0;
for (int i = 0; i < sentence.length(); i++) {
char ch = sentence.charAt(i);
if (inLetter == ch) {
letter++;
}
}
System.out.print(sentence.charAt(letter));
I would also strongly suggest to validate the input (which is not done in the example above) instead of just assuming you got 1 character from the first input and 1 sentence in the second.
Your if (sentence.length() <= 0) { is not right. Change your condition like:
System.out.println("Enter a character for which to search");
letter = in.next();
System.out.println("Enter the string to search");
sentence = in.next();
char searchLet=letter.charAt(0); // Convert String to char
int letter = 0;
for (int i = 0; i < sentence.length(); i++) {
char ch = sentence.charAt(i);
if (searchLet== ch) { // Check the occurrence of desired letter.
letter++;
}
}
System.out.print(sentence.charAt(letter));
if (sentence.length() <= 0) {
letter++;
}
The above part of code in your program is wrong. This will never be true until otherwise you input an empty string.
And basically this is not the correct logic. You will have to use the direct comparison.
No need to loop:
String sentence = "abcabcabcd";
String letter = "b";
int numOfOccurences = sentence.length() -
sentence.replaceAll(letter, "").length();
System.out.println("numOfOccurences = "+numOfOccurences);
OUTPUT:
numOfOccurences = 3
Try this
forget String letter = "" <-- Delete
forget letter = in.next() <-- Delete
// There's no nextChar() method, so this is a work aroung
char ch = in.findWithinHorizon(".", 0).charAt(0);
int letter = 0;
for (int i = 0; i < sentence.length(); i++) {
if (sentence.charAt(i) == ch) {
letter++;
}
}
System.out.println(letter); // print number of times letter appears
// You don't want this
System.out.print(sentence.charAt(letter)); // Makes no sense
Try this:
Char letter = '';
String sentence = "";
System.out.println("Enter a character for which to search");
letter = in.next().charAt(0);
System.out.println("Enter the string to search");
sentence = in.next();
int count= 0;
for (int i = 0; i < sentence.length(); i++) {
char ch = sentence.charAt(i);
if (ch==letter) {
count++;
}
}
System.out.print(letter+" occurance:"+count);
You need to know the char you wanna search. You can use char charToSearch = letter.toCharArray()[0];
Define a variable, such as count to count the occurrences of a letter in a given string.
Loop the string and compare each char, if the char is equal to the char to search, then count++;
Example--->
int count = 0;
char charToSearch = letter.toCharArray()[0];
for (int i = 0; i < sentence.length(); i++) {
if (sentence.charAt(i) == charToSearch) {
count++;
}
}
System.out.printf("Occurrences of a %s in %s is %d", letter, sentence, count);
Hope this will helpful to you.
import java.util.Scanner;
public class CountCharacters {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter the string to search");
String sentence = in.nextLine();
System.out.println("Enter a character for which to search");
String letter = in.next();
int noOfOccurance = 0;
for (int i = 0; i < sentence.length(); i++) {
char dh=letter.charAt(0);
char ch = sentence.charAt(i);
if (dh==ch) {
noOfOccurance++;
}
}
System.out.print(noOfOccurance);
}
}
Sample Input Output:
Enter the string to search
how are you
Enter a character for which to search
o
No of Occurances : 2
try the indexOf() method.
it should work
your Scanner class has not moved to the next line after reading the character
letter = in.next().charAt(0);
add another in.nextLine() before reading the input string
System.out.println("Enter a character for which to search");
letter = in.next().charAt(0);
in.nextLine();
System.out.println("Enter the string to search");
sentence = in.nextLine();
old thread but hope this helps :)
Related
Suppose you have a String and a CAPITAL letter in that indicates ending of a word. For example, if you have wElovEcakE where E, E and K indicates end of the words wE, lovE and cakE respectively. You need to reverse each word (as you know where it ends). Don’t reverse the String as a whole. To illustrate, if we give wElovEcakE as input output should be EwEvolEkac. See wE became Ew, lovE became Evol and so on....
And the way i tried to approach with ..
import java.util.Scanner;
public class Alternative {
public static void main(String[]args) {
Scanner robo=new Scanner (System.in);
System.out.println("Enter a word ");
String word=robo.nextLine();
char[] array=word.toCharArray();
for(int i =0;i<array.length;i++){
int count =0;
for(int j=0;j<=("EMPTY");j++) // here i am trying to operate a loop where it will work up to the Capital letter.
count ++;
}
//Code incomplete
}
}
}
Above i have mentioned "EMPTY" in the condition part ... i want to operate a loop where my loop will work up to the capital letter , then i will count all the letter that i have counted up to capital letter then last step will be like i will make another loop where i will reverse all the letter where condition for the loop will <=count ;Example:lovE (counted 4 letters i will reverse four times back).
Can you guys help me to write the condition at "EMPTY" part if you think that my approach is correct ..
Can you guys help me to solve the problem in any other way ?
test if this works for you:
Scanner robo = new Scanner (System.in);
System.out.println("Enter a word ");
String word = robo.nextLine();
String textInvert = "";
int indexAnt = 0;
for (int i = 0; i < word.length(); i++) {
if (Character.isUpperCase(word.charAt(i))) {
String wordSplit = word.substring(indexAnt, i + 1);
for (int j = wordSplit.length() - 1; j >= 0; j--)
textInvert += wordSplit.charAt(j);
indexAnt = i + 1;
}
}
System.out.println(textInvert);
Here is my solution with Regex pattern
String[] in = "wElovEcakE".replaceAll("([A-z]+?[A-Z])","$1,").replaceAll(",$","").split(",");
String out = "";
for(String current: in){
StringBuilder temp = new StringBuilder();
temp.append(current);
out+=temp.reverse();
}
System.out.println(out);
Result:
EwEvolEkac
Here is a solution that makes use of the StringBuilder class to hold and reverse each found word.
Scanner robo = new Scanner (System.in);
System.out.println("Enter a word:");
String word = robo.nextLine();
robo.close();
String upperCase = word.toUpperCase(); //used to find uppercase letters
StringBuilder builder = new StringBuilder();
for (int i = 0; i < word.length(); i++) {
char nextChar = word.charAt(i);
builder.append(nextChar);
if (nextChar == upperCase.charAt(i)) {
String subWord = builder.reverse().toString();
System.out.print(subWord); //It's not clear what to do with the found words
builder = new StringBuilder();
}
}
System.out.println();
Example
Enter a word:
makEmorEpiE
EkamEromEip
You can try this solution:
String textInvert = "wElovEcakE";
String revertText = textInvert
.chars().mapToObj(c -> (char) c)
.reduce(new LinkedList<>(Arrays.asList(new StringBuilder())), (a, v) -> {
a.getLast().append(v);
if (Character.isUpperCase(v)) {
a.add(new StringBuilder());
}
return a;
}, (a1, a2) -> a1)
.stream()
.map(s -> s.reverse())
.reduce(StringBuilder::append)
.map(StringBuilder::toString)
.get();
System.out.println(revertText);
public class Alternative {
public static void main(String[] args) {
Scanner robo = new Scanner(System.in);
System.out.println("Enter a word ");
String word = robo.nextLine();
char[] array = word.toCharArray();
int count = -1;
for (int i = 0; i < array.length; i++) {
if (Character.isUpperCase(array[i])) { //find the upper case letters in the word
for (int j = i; j > count; j--) //loop through the letters until the last count variable value is encountered
System.out.print(array[j]); //print the reversed values
count = i; //assign the last encountered uppercase letter's index value to count variable
}
}
}
}
So I'm barely learning Java and I'm having a hard time using loops. I'm supposed to write a program that let the user enter a word and enter a letter they want to remove while printing out the other letters.
here is what I have right now:
System.out.print("Please enter a word: ");
String word = kbreader.nextLine();
System.out.print("Enter the letter you want to remove: ");
for (int k = 0; k <= word.length(); k ++)
{
String remove = kbreader.nextLine();
String word2 = word.charAt(k) + "";
String remove2 = remove.charAt(0) + "";
if (!word2.equals(remove2))
{
System.out.print(word2);
}
}
here is an example:
enter a word: aaabxaaa
enter a letter you want to remove: a
bx
One simple way to handle this would be to just use String#replace here:
System.out.println(word.replace(remove, ""));
This would remove all instances of the string remove, which in your case would just be a single letter.
Another way to do this would be to iterate your input string, and then selectively print only those characters which do not match the character to be removed:
char charRemove = remove.charAt(0);
for (int i=0; i < s.length(); i++){
char c = s.charAt(i);
if (c != charRemove) System.out.print(c);
}
Use public String replace(char oldChar, char newChar) function in java.
Modify to this :
System.out.print("Please enter a word: ");
String word = kbreader.nextLine();
System.out.print("Enter the letter you want to remove: ");
String remove = kbreader.nextLine();
word = word.replace(remove ,"");
System.out.print(word);
This is how you can do it :
System.out.print("Please enter a word: ");
String word = kbreader.nextLine();
System.out.print("Enter the letter you want to remove: ");
//read the char to remove just once before starting the loop
char remove = kbreader.nextLine().charAt(0);
for (int k = 0; k <= word.length(); k ++)
{
char word_char = word.charAt(k);
//check if the current char is equal to char required to be removed
if (word_char != remove)
{
System.out.print(word_char);
}
}
I wrote the following code but I can't seem to convert the string to a char and then search the input entry string. My code is below. Any helpful tips would be greatly appreciated. I'm supposed to use a while loop but felt like for was easier to start with.
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String inputEntry;
String inputCharacter;
int length;
int i;
int counter = 0;
System.out.println("Enter a string: ");
inputEntry = in.next();
System.out.println("Enter a letter: ");
inputCharacter = in.next();
length = inputCharacter.length();
if (length == 1) {
for(i = 0; i <= inputEntry.length(); i++){
char c = inputCharacter.charAt(0);
if (inputEntry.charAt(i) == c){
counter++;
}
}
}
else {
System.out.println("The input letter was not a single letter.");
}
}
}
It looks like the only problem in your code is that you are using <= instead of < within your loop. <= is incorrect because it passes string length as an index, but first character resides at charAt(0), and last character resides at charAt(inputEntry.length() - 1)
Replacing your loop declaration with the following will do the trick:
for(i = 0; i < inputEntry.length(); i++){
Then you also need to System.out.println(counter); after the for loop.
I've replaced a string so that all the letters appear as **'s however when I ask the user for input of a char, I can't seem to get the letters to revert back from *'s into strings. I will show you below what I have done in my code:
System.out.println(randomPirateWord.replaceAll("\\S", "*"));
System.out.println("guess a letter");
char letterGuesed = input.findInLine(".").charAt(0);
System.out.println(randomPirateWord.replaceAll("\\S"+letterGuesed,"*"));
Method replaceAll works in the opposite direction. First is a regular expression, and next the replacement for match, so you replace guessed letters with '*' and that's propably opposite to what you want to achieve.
I would use a String that holds your hiddenWord, and in a different function just display the length of the string in *s, then compare the letterGuessed to hiddenWord and change the *s back to the hiddenWord that way.
Maybe not with replace all, but this seems to work:
import java.util.Scanner;
class hola{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
String randomPirateWord = "HelloWorld";
System.out.println("");
boolean notComplete = true;
char words[] = new char[randomPirateWord.length()];
char words2[] = new char[randomPirateWord.length()];
for(int i = 0; i < randomPirateWord.length(); i++){
words[i] = randomPirateWord.charAt(i);
words2[i] = '*';
}
while(notComplete){
System.out.print("Type a letter: ");
char letter = sc.next().charAt(0);
notComplete = false;
for(int i = 0; i < randomPirateWord.length(); i++){
if(words[i] == letter){
words2[i] = letter;
}
}
for(int i = 0; i < randomPirateWord.length(); i++){
System.out.print(words2[i]);
}
for(int k = 0; k < randomPirateWord.length(); k++){
if(words2[k] == '*'){
notComplete = true;
break;
}
}
System.out.println("");
}
}
}
I am new to java and I have been trying to solve a problem which I feel might have a simpler answer than my code.The problem was to print the initials of a user input name of any length along with the full surname.But this has to be done without any String.split() or arrays.I tried getting the user to input his name one word at a time, but is there any there a possible way to get the whole name at once and do as required.
My code is as follows:
import java.io.*;
public class Initials {
public static void main(String[]args)throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the number of words your name contains");
int n=Integer.parseInt(br.readLine());
String str="";
for(int x=1;x<=n-1;x++){
System.out.println("Enter your name's word number:"+" "+x);
String s=br.readLine();
String st=s.toUpperCase();
char ch=st.charAt(0);
str=str+ch+".";
}
System.out.println("Enter your surname");
String sur=br.readLine();
str=str+" "+sur.toUpperCase();
System.out.println(str);
}
}
Use a regular expression (namely (?<=\w)\w+(?=\s)):
String name = "John Paul Jones"; // read this from the user
System.out.println(name.replaceAll("(?<=\\w)\\w+(?=\\s)", "."));
J. P. Jones
No split(), no arrays :)
A little explanation: We essentially want to replace all letters of each word that is followed by a whitespace character except the first letter, with a . character. To match such words, we use (?<=\w)\w+(?=\s):
(?<=\w) is a positive lookbehind; it checks that a word-character exists at the start of the match but does not include it in the match itself. We have this component because we don't want to match the first character of each name, but rather all but the first (except for the last name, which we'll deal with shortly).
\w+ matches any continuous string of word characters; we use this to match the rest of the name.
(?=\s) is a positive lookahead; it checks that our match is followed by a whitespace character, but does not include it in the match itself. We include this component because we don't want to replace anything on the last name, which should not be followed by a whitespace character and hence should not match the regular expression.
Another way around---
import java.util.Scanner;
//a class that will print your output
class Initial {
public void Initials() {
Scanner sc = new Scanner(System.in);
System.out.print("Enter Full name:");
String name = sc.nextLine();
int l = name.length();
int pos = 0;
for (int i = l - 1; i >= 0; i--) {
char ch = name.charAt(i);
if (ch == ' ') {
pos = i; //getting the last space before Surname
break;
}
}
System.out.print("The initials are: ");
System.out.print(name.charAt(0) + ".");//prints first name initial
// with dot
for (int x = 1; x < pos; x++) //finds midname initial
{
char ch = name.charAt(x);
if (ch == ' ') {
System.out.print(name.charAt(x + 1) + ".");
}
}
for (int i = pos; i < l; i++) { //for printing Surname
System.out.print(name.charAt(i));
}
}
}
public class Str {
public static void main(String[] args) {
Initial i = new Initial();
i.Initials();
}
}
//This code will work for any no. of words in the name
class Surnam {
public static void main(String name) {
name = " " + name;
int l=name.length(), p=0, m=0, r=0;
char y;
String word=" ", words=" ";
for(int i = 0; i = 0; i--) {
y=name.charAt(i);
if(y==' ') {
r=name.lastIndexOf(y); //extracting the last space of the string
word=name.substring(i,l); //extracting the surname
words=name.replace(word," "); //removing the surname break;
}
}
for (int i = 0; i <= r - 1; i++) {
char x=words.charAt(i);
if (x == ' ') {
System.out.print(words.charAt(i + 1) + "."); //Printing all initials before the surname with a dot
}
}
for (int i = l - 1; i >= 0; i--) {
char x=name.charAt(i);
if(x==' ') {
m=i;
name=name.substring(m,l); //extracting the surname
name=name.trim(); //removing all the spaces before the surname
System.out.print(name);
break;
}
}
}
}