Count letter in a word from scanner, java - java

My code is looking like this right now, it's counting the letters in the word but I would like my code to count every letter in the word so if I write banana or nine, the code will ask which letter to count, and if I choose "N", it will print 2 "N". Please help me out.
System.out.println("Ange ordet du vill leta i: ");
String str1 = sc.nextLine();
System.out.println("Ange bokstaven du vill leta efter: ");
String str2 = sc.nextLine();
int count = 0;
for(int i = 0; i < str2.length(); i++) {
if(str2.charAt(i) != ' ')
count++;
}
System.out.println("Antal bokstäver i ditt ord: " + count);

You don't need to count every letter at first. You should count after getting the letter to count. But depending on the scenario. I assume that you need to get the count of the letter in a particular string.
You can wrap counting logic inside a while() to do this over and over again.
import java.util.Scanner;
public class MyClass {
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
System.out.println("enter word");
String s = scanner.next();
System.out.println("enter letter");
char a = scanner.next().charAt(0);
int count = 0;
for(int i = 0; i < s.length(); i++){
if(s.charAt(i) == a){
count++;
}
}
System.out.println(count);
}
}

Related

what to revise so that the final word can be print

I'm still learning Java and me and my classmate are working on this assignment code game hangman. We have a problem in the part printing the original word, because we want the word to be hidden, but we need the word to be printed, not hidden on the final output. What can we revise in our code to make it print properly??
import java.util.Scanner;
public class GameHangman {
public static void main(String[] args) {
System.out.println("Welcome! To the HANGMAN game.");
System.out.println("Guess the word by guessing each letter.");
System.out.println("LET'S START!");
String[] words = {"superman","batman","spiderman"};
int t = words.length;
int x, y, miss;
String w;
char l, c='y';
Scanner input = new Scanner(System.in);
while (c=='y')
{
x = (int)(Math.random()*(t));
w = words[x];
char[]chars = w.toCharArray();
var hidden = new char[w.length()];
for(int i = 0; i < hidden.length; i++)
{
hidden[i] = '*';
}
boolean z = false;
int count = 0;
miss = 0;
while(!z)
{
System.out.print("\n(guess) Enter a letter ("+new String(hidden)+"): ");
l = input.next().charAt(0);
y = 0;
for(int i = 0; i < hidden.length; i++)
{
if(chars[i]==l)
{
y++;
if(hidden[i]=='*')
{
hidden[i]=l;
count++;
y++;
}
}
}
if(y==1)System.out.println("\nOOPS!("+l+") already present, try other letters.");
else if (y==0)
{
miss++;
System.out.println("\nYIKES!("+l+") is not in the word, guess again.");
}
if(count==hidden.length) z = true;
}
System.out.println("\nGreat!! You guessed the word("+hidden+")!!!");
System.out.println("You were wrong "+miss+" tries.");
System.out.print("\nDo you want to continue with another game word? "
+ "\nEnter yes or no: ");
c = input.next().charAt(0);
}
}
}
in this part, we print our final word
System.out.println("\nGreat!! You guessed the word("+hidden+")!!!");
and this is what we are getting output. we need to print with not being hidden.
Here are two methods to convert your char array hidden into a String for printing out.
// First option: Create a String object
String str1 = new String(hidden);
System.out.println("\nGreat!! You guessed the word("+str1+")!!!");
// Second option: Using valueOf method
String str2 = String.valueOf(hidden);
System.out.println("\nGreat!! You guessed the word("+str2+")!!!");
Alternatively, you can also print your String variable w and avoid calling these methods.

Read in a sentence and print out only words that have the same letter repeated 3 or more times in a row

I wanted to make a program in which only repeats words that has 3 of the same letters back to back. eg the mooonkey raaan through the mounnntains. the program should only repeat mooonkey, raaan
public class Triplets2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("write a sentence");
String in = input.nextLine();
String [] sentence = in.split(" ");
for (int i = 0; i < sentence.length; i++) {
char [] word = sentence[i].toCharArray();
int counter =0;
for (int s = 0; s < word.length; s++) {
char letter = word[s];
for (int x = 0; x<word.length; x++) {
if (letter == word[x]) {
counter++;
}
else {
counter = 0;
}
}
}
if (counter >=3) {
System.out.print(sentence[i] + ", ");
}
}
}
the program instead just repeats nothing.
Your code is almost correct, the only logical error you made is inside your inner loop you keep resetting your counter variable as soon as you find a letter that is different:
if (letter == word[x]) {
counter++;
} else {
counter = 0;
}
So when you iterate over a word like "raaan" your counter will reset when it reaches the very end of the String, because "n" only exists once.
What this means is that you will only be able to detect words that have 3 consecutive letters at the very end (like "Hooo").
The solution is simple:
Once you found 3 consecutive letters in a word you can just stop iterating and checking the rest of your word. At that point you already know that it fits your criteria:
if (letter == word[x]) {
counter++;
if(counter >= 3) break; // stop inner loop checking once we found 3 letters
} else {
counter = 0;
}
Since you are looking for consecutive letters you want to start at char i and then compare the char at i to char at i+1 and at i+2. If they are all equal then we have a match and can continue.
You can simplify the whole function such as:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("write a sentence");
String in = input.nextLine();
List<String> tripleLetter = new ArrayList<>();
for (String s : in.split(" ")) {
char[] word = s.toCharArray();
for (int i = 0; i < word.length - 2; i++) {
if ((word[i] == word[i+1]) && (word[i] == word[i+2])) {
tripleLetter.add(s);
break;
}
}
}
System.out.println(tripleLetter.stream().collect(Collectors.joining(", ")));
}
Allow me to suggest a solution that differs slightly from yours and doesn't use a counter.
Scanner input = new Scanner(System.in);
System.out.println("write a sentence");
String in = input.nextLine();
String[] sentence = in.split(" ");
for (int i = 0; i < sentence.length; i++) {
char[] word = sentence[i].toCharArray();
for (int s = 0; s < word.length - 2; s++) {
if (word[s] == word[s + 1] && word[s] == word[s + 2]) {
System.out.print(sentence[i] + ", ");
break;
}
}
}
Check whether the current letter, in the current word, is the same as the next letter and the same as the letter after the next letter. If the condition holds, then print the current word and proceed to the next word in the sentence.
Well, if you're just looking for a shorter version of doing this then try this.
first, split the sentence on one or more white space characters (you should be doing that regardless).
stream the array and filter on a single character, followed by the same two characters via a back reference to the capture group (see regular expressions for that).
And print them.
String str =
"Thiiis is aaaa tesssst of finding worrrrds with more than threeeeee letteeeeers";
Arrays.stream(str.split("\\s+"))
.filter(s -> s.matches(".*(.)\\1\\1.*"))
.forEach(System.out::println);
Prints
Thiiis
aaaa
tesssst
worrrrds
threeeeee
letteeeeers

Counting Upper and Lower characters in a string using an array

I have been working on this problem for two days now and have no idea where I'm going wrong.
Essentially I need to ask a user for a string of words.
I need to set up an int array of 26 elements that holds the count of lower case letters and one for upper case letters.
I can't get the program to compare with the array elements properly. This is my code so far:
public class Lab17Array {
public static void main(String[] args)
{
Scanner kb = new Scanner (System.in);
int lLetter = 0;
int uLetter = 0;
// int[] alph = new int [26];
int alph [] = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
int Alph [] = {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
System.out.println("Enter a phrase");
String user = kb.nextLine();
// to print out length of word
System.out.println("Total number of letters is " + user.length());
for(int i = 0; i < user.length(); i++)
{
}
System.out.println("Upper case letters are:" + uLetter);
System.out.println("Lower case letters are:" + lLetter);
int otherL = user.length() - (uLetter + lLetter);
// to print out other chars that aren't letters
System.out.println("Number of all other letters is " + otherL );
}
}
Inside my for loop is where I've been trying different if conditions. I have no idea what I'm missing?
Using an Array
You could use String.toCharArray() and a for-each loop to iterate your userInput (you seem to have changed the variable name between your post, and your comment). Regardless, something like
for (char ch : user.toCharArray()) {
if (Character.isLowerCase(ch)) {
lLetter++;
} else if (Character.isUpperCase(ch)) {
uLetter++;
}
}
Using Regular Expression(s)
You could reduce your code by using a regular expression to remove all non-lowercase characters from the input and another to remove all non-uppercase characters from the input like
int lLetter = user.replaceAll("[^a-z]", "").length(); // <-- removes everything not a-z
int uLetter = user.replaceAll("[^A-Z]", "").length(); // <-- removes everything not A-Z
Try this
int upperCount = 0;
int lowerCount = 0;
Scanner sc = new Scanner(System.in);
String w = sc.nextLine();
for(int i = 0; i < w.length(); i++){
if(Character.isUpperCase(w.charAt(i))){
upperCount++;
}else{
lowerCount++;
}
}
System.out.println("Upper Counts are "+upperCount+" lower counts are "+lowerCount);
Try this.
for(int i = 0; i < user.length(); i++)
{
int ch = user.charAt(i);
if (Arrays.binarySearch(alph, ch) >= 0)
++lLetter;
if (Arrays.binarySearch(Alph, ch) >= 0)
++uLetter;
}

java program to count the number of words that starts with capital letters

I want to write a program that count the number of words that starts with capital letters. It only count no. Of capital letter not word try this line
"Hi hOw are yOu"
According to my code output will be 3
But their is only 1 word that starts with capital letter that is 'Hi'...so how can I solve these problem..Please help me with this.
import java.util.*;
class Cap
{
public static void main(String m[])
{
Scanner in=new Scanner(System.in);
String s=new String();
System.out.println("Enter a line:");
s=in.nextLine();
char c;
int ct=0;
for(int i=0;i<s.length();i++)
{
c=s.charAt(i);
if(c>=65 && c<=90)
{
ct++;
}
}
System.out.println("total number of words start with capital letters are :"+ct);
}
}
You should better use scanner.next();, which returns the token up to white space in other way a word.Now, you can check the first character of String returned by next() is in uppercase or not.
For statement This is StackOverflow you will have three tokens, This, is and StackOverflow and you can use String.charAt(0) on this String.
Moreover, you can simply use Character.isUpperCase method to check whether character is in upper case or not.
import java.util.*;
public class program_6
{
public static void main(String[] args)
{
String s1;
Scanner scan = new Scanner(System.in);
System.out.println("Enter the string... ");
s1 = scan.nextLine();
int count=0,i=0,n;
n = s1.length();
System.out.println("Size of the string is... " + n );
if ( null == s1 || s1.isEmpty())
{
System.out.println("Text empty");
}
else
{
if( Character.isUpperCase(s1.charAt(0) ))
{
count++;
}
for (i=1 ; i<n ; i++)
{
if ( Character.isWhitespace(s1.charAt(i-1)) && Character.isUpperCase(s1.charAt(i) ) )
{
count++;
}
}
}
System.out.println("Number of the word wich starts with capital latter... " + count );
}
}
Currently you are counting all the capital letters that are entered.
What you want to do is split the line on space and check only for the first letter if it is capital.
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
String s;
System.out.println("Enter a line:");
s=in.nextLine();
int ct=0;
for(String str: s.split(" ")) {
if(str.charAt(0)>=65 && str.charAt(0)<=90)
{
ct++;
}
}
System.out.println("total number of words start with capital letters are :"+ct);
}
You are comparing each character.Instead you can add a space at the begining of the string and check each character after space if it is in uppercase.
Scanner in = new Scanner(System. in );
String s = new String();
System.out.println("Enter a line:");
s = " " + in .nextLine().trim();
char c;
int ct = 0;
for (int i = 1; i < s.length(); i++) {
c = s.charAt(i);
if (c >= 65 && c <= 90 && s.charAt(i - 1) == 32) {
ct++;
}
}
System.out.println("total number of words start with capital letters are :" + ct);
DEMO
or better use scanner.next() as said by TAsk
Try this:
Scanner in = new Scanner(System.in);
String s = new String();
System.out.println("Enter a line:");
s = in.nextLine();
char c;
int ct = 0;
for (int i = 0; i < s.length(); i++) {
c = s.charAt(i);
if (Character.isUpperCase(c)
&& (i == 0 || Character.isWhitespace(s.charAt(i - 1)))) {
ct++;
}
}
System.out
.println("total number of words start with capital letters are :"
+ ct);
First of all we check on the first position whether it is starts with capital letter or not and it is only for the string which starts with capital letter... If yes then the count will be incremented. Next condition( Which is used for string which start with blank space or any other string) will check that left position must have blank space to start new word and the character must be capital to increment the count variable...
import java.util.*;
public class program_6
{
public static void main(String[] args)
{
String s1;
Scanner scan = new Scanner(System.in);
System.out.println("Enter the string... ");
s1 = scan.nextLine();
int count=0,i=0,n;
n = s1.length();
System.out.println("Size of the string is... " + n );
if ( null == s1 || s1.isEmpty())
{
System.out.println("Text empty");
}
else
{
if( Character.isUpperCase(s1.charAt(0) ))
{
count++;
}
for (i=1 ; i<n ; i++)
{
if ( Character.isWhitespace(s1.charAt(i-1)) && Character.isUpperCase(s1.charAt(i) ) )
{
count++;
}
}
}
System.out.println("Number of the word wich starts with capital letter... " + count );
}
}

how many letter occur in a text?

I got it working but it is also counting the spaces between the words that are being typed.
All i care is for the letters to be count and not the spaces.
How or what can i do to change this? where am i messing up or missed something
import java.util.Scanner;
public class LetterCount
{
public static void main (String[] args)
{
System.out.println("Type something ");
Scanner n = new Scanner (System.in);
String s = "";
s = n.nextLine();
char []c = s.toCharArray();
int sz = c.length;
int i =0, j=0, counter=0;
for (i=0; i<sz; i++){
counter =0;
for(j=0; j<sz; j++)
{
if (j< i&& c[i] == c[j])
{
break;
}
if (c[j] == c[i])
{
counter++;
}
if (j==sz-1)
{
System.out.println("the character "+c[i]+" is present "+counter+" times");
}
}
}
}
}
What you'd want to do is remove the whitespace from the string before you count the letters;
Removing whitespace from strings in Java

Categories

Resources