I need help on writing a program about counting how many times a letter in a given word is repeated in alphabetical order. Lower and upper case letters are equals and it has to work for numbers as well. For example:
we have to use array and loops. also, it must not count the space if there is more than 1 word /number given and it should also prompt the user if they want to continue or not. If not then they should enter a dot '.' or when there's a dot '.' after the word, it should close the program after counting the letters.
University
e:1 i:2 n:1 r:1 s:1 t:1 u:1 y:1
import java.util.Scanner;
import java.lang.Character;
public class Array {
public static void main(String[] args) {
Scanner input=new Scanner (System.in);
int[] letters =new int [26];
String str= input.nextLine();
str=str.toLowerCase();
for (int i=0; i<str.length(); i++)
{
letters[i]=0;
}
System.out.println(str.length());
System.out.println(char2int('a'));
System.out.println(char2int ('D'));
}
public static int char2int (char c) {
return Character.toLowerCase(c)-(int)'a';
}
}
This comes out to, for example
me
2
0
3
I'm going to give you a big hint, what you need to do is call a method (say countLetters) that takes a word and a letter - so that would be,
// Count the "letter"(s) in the word.
public static int countLetters(String word, char letter) {
int count = 0;
if (word != null) {
char lc = Character.toLowerCase(letter);
for (char c : word.toCharArray()) {
if (lc == Character.toLowerCase(c)) {
count++;
}
}
}
System.out.printf("%s: %d\n",
String.valueOf(letter), count);
return count;
}
public static void main(String[] args) {
String test = "Universe";
countLetters(test, 'e');
countLetters(test, 'u');
}
Output is
e: 2
u: 1
Related
Being fairly new to Java, I have an exercise where the user will be asked to enter a word. Next, they will be asked to enter a number. Then the program will modify the word by taking the number and implementing it to change the string. For example, if the word "Hello" was entered, and the integer entered was the number "3", it will take each character in the string (Hello) and move them each 3 letters down in the alphabet, which would then make the output word "Khoor". I recently learned about method replacing (.replace) in the same chapter as this question but it seems like having to clarify every single letter with a replace would be too lengthy. This is what I have so far.
public class Lab03Exercise7 {
public static void main(String [] args)
{
// Prompt user to enter a string
System.out.print("Enter a word");
// Import Java scanner
Scanner input = new Scanner( System.in );
int numberinput;
String wordinput = input.nextLine();
// Prompt user to enter an integer
System.out.print( "Enter a number");
numberinput = input.nextInt();
}
}
You can do it as follows:
import java.io.IOException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws IOException {
Scanner input = new Scanner(System.in);
System.out.print("Enter a word: ");
String wordInput = input.nextLine();
System.out.print("Enter a number: ");
int numberInput = input.nextInt();
StringBuilder updatedStr = new StringBuilder();
for (char c : wordInput.toCharArray()) {
updatedStr.append((char) (c + numberInput));
}
System.out.println("Updated string: " + updatedStr);
}
}
Explanation: Break the word into an array of characters and iterate through the array. During iteration, add the number to the character and append the updated character to a StringBuilder object. Note that you can add an integer to a char value but you need to cast it before appending to the StringBuilder object.
You can use something like this:
final StringBuilder sb = new StringBuilder();
for(int i = 0 ; i < wordinput.length(); i++) {
final char currentChar = wordinput.charAt(i);
sb.append((char)(currentChar + numberinput));
}
System.out.println(sb.toString());
So basically, we're going character by character and adding the shift that you've got from the user. here I don't handle the edge cases - where we need to rotate after z / Z
In general, this algorithm called Caesar Cipher and you can get some more info about it here: https://www.geeksforgeeks.org/caesar-cipher-in-cryptography/
As highlighted by #maio290' comment you have to use the ascii table to solve your problem, differentiating between lowercase characters and uppercase characters. Starting from the assumption we have a 26 chars alphabet (a-z and A-Z) in the example we are translating the chars of three positions so we will have for example:
"Hello" will be translated to "Khoor"
"zed" will be translated to "chg"
In the case of z char it will be translated to c, I'm posting an example explaining the situation:
public class Caesar {
public static String encode(String original, int k) {
char[] arr = original.toCharArray();
StringBuilder encoded = new StringBuilder();
for (char ch : arr) {
char initialCharacter = Character.isLowerCase(ch) ? 'a' : 'A';
int dec = ((int)(ch - initialCharacter) + k) % 26;
encoded.append((char)(dec + initialCharacter));
}
return encoded.toString();
}
public static void main(String[] args) {
System.out.println(encode("Hello", 3)); //<-- will print Khoor
System.out.println(encode("zed", 3)); //<-- will print chg
}
}
You have to transform your char to int and after retransform it to char , differentiating between lowercase chars and uppercase chars and assuming an alphabet of 26 chars , for further details see the ascii table.
I believe this is gonna help to solve your problem. Just do not forget to handle it after 122(letter z). You can check the ASCII table here (https://theasciicode.com.ar/)
public static void main(String[] args) throws Exception {
String word = "word";
char[] arr = word.toCharArray();
int count=0;
for (char c : arr) {
//!!Handle if the sum is bigger than 122 (letter z), you need to do some easy math.
arr[count] = (char) (((int)c) + 3);
count++;
}
String newWord = new String(arr);
}
I am currently stuck on the first loop of the code. I'm having a difficult time comparing the character at an index within the string to the first vowel a (Keeps saying that char cannot be dereferenced...).
I would just like to know how to properly compare any letter within the string to any vowels (a, e, i, o, u). I would also like to know if I can compare a certain letter within the string to the entire array, or would I just have to compare to every individual vowel??
import java.util.*;
class StringCount {
public static void main(String [] args) {
Scanner input = new Scanner(System.in);
String user;
int charCount;
char[] vowel = {'a', 'e', 'i', 'o', 'u'};
System.out.println("Please enter any string!");
user = input.nextLine();
charCount = user.length();
for (int i = 0; i < charCount; i++) {
if(user.charAt(i).equals('a') {
}
}
}
}
You are missing a couple of things here:
a. Character can be in uppercase or lowercase.
b. Word seperators, they may be comma , space, etc.
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class WaitTest {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String user;
int charCount;
List<Character> vowels = new ArrayList();
//add all vowels to list inclusing uppercase
a,e,i,o,u,A,E,I,O,U
vowels.add('a');
vowels.add('e');
List<Character> wordSeperators = new ArrayList();
//add your word seperators here
wordSeperators.add(' ');
wordSeperators.add(',');
System.out.println("Please enter any string!");
user = input.nextLine();
charCount = user.length();
int vowelCount=0,wordCount=0;
for (int i = 0; i < charCount; i++) {
char c= user.charAt(i);
if(vowels.contains(c)) {
vowelCount++;
}else if (wordSeperators.contains(c)){
wordCount++;
}
}
}
}
If you just want to check your user enter a word with a char in your list you could use Java.lang.String.contains() Method with your char list in the loop
If u want to check your user enter is exctely a char in your list, you could use Java.lang.String.equal() Method with in a loop
Another possible solution:
if (Arrays.binarySearch(vowel, user.charAt(i)) >= 0) {
}
Update:
equals() is used for Objects (String, Integer, etc...)
For primitives like int, boolean, char etc, you have to use ==
Try with this.
public static void main(String[] args) {
int count =0;
String user;
Scanner input = new Scanner(System.in);
System.out.println("Please enter any string!");
user = input.nextLine();
System.out.println(user);
int inputLength = user.length();
try{
for (int i = 0; i < inputLength; i++) {
char letter = user.charAt(i);
if(letter=='a'||letter=='e'||letter=='i'||letter=='o'||letter=='u') {
count +=1;
}
}
}catch (Exception e) {
// TODO: handle exception
}
System.out.println("FINAL COUNT "+count);
}
You will need to modify your code to compare every input char with your vowel array.
for (int i = 0; i < charCount; i++) {
for (char v : vowel) {
if(user.charAt(i) == v {
//here is what you do if a vowel <v> is found
}
}
}
Hope this helps.
My instructor isn't too strict on the manner in which we complete this as we are fairly new to programming. I tampered with my code and found a solution. I understand it may not be the best solution, but for the most part, as long as proper punctuation is used within the String, then the word count as well as the vowel count do go up as desired.
Most of the answers I received were a little advanced for me. We haven't covered a lot of these concepts, but thank you guys so much. Someone pointed out that I was using ".equals" to compare a single character instead of using the "==". This solution helped me the most!!
If anyone can add on to my solution to allow ANY user input be converted into the correct word count and vowel count then thank you!!
ex. 1 (States the correct word count and vowel count):
String: "Let us go over there!"
vowels: 7
words: 5
ex. 2 (States the incorrect word count and vowel count):
These are the values when no punctuation is used
String: "Let us go over there"
vowels: 7
words: 4
import java.util.*;
class StringCount {
public static void main(String [] args) {
Scanner input = new Scanner(System.in);
String user;
int s, charCount, wordCount, vowelCount;
char[] vowel = {'a', 'e', 'i', 'o', 'u',};
char[] punct = {' ', '.', ';','?', '!', '-'};
s = 0;
wordCount = 0;
vowelCount = 0;
System.out.println("Please enter any string!");
user = input.nextLine();
user = user.toLowerCase();
charCount = user.length();
for (int i = 0; i < charCount; i++) {
if(user.charAt(i) == vowel[0] ||
user.charAt(i) == vowel[1] ||
user.charAt(i) == vowel[2] ||
user.charAt(i) == vowel[3] ||
user.charAt(i) == vowel[4])
vowelCount++;
if(user.charAt(i) == punct[0] ||
user.charAt(i) == punct[1] ||
user.charAt(i) == punct[2] ||
user.charAt(i) == punct[3] ||
user.charAt(i) == punct[4] ||
user.charAt(i) == punct[5])
wordCount++;
}
System.out.println("Vowels: " + vowelCount);
System.out.println("Words: " + wordCount);
}
}
import java.util.Scanner;
public class KBstrings1
{
public static void main (String []args)
{
Scanner scan=new Scanner(System.in);
String s1= scan.nextLine();
int num=0;
for(int i=0; i<s1.length();i++)
{
if(s1.charAt(i)=='a'){
num++;}
i++;
}
if(num>3)
{
System.out.println(s1.replace('a','#'));
}
else
{
System.out.println(s1.replace('a','#'));
}
}
}
I want to create a program that accepts user input of a sentence and replaces all the 'a' characters with '#' if there are 3 or less instances of 'a', and replace 'a' with '#' if there are more than 3 instances. I tried using the sentence "Computer science is no more about computers than astronomy is about telescopes." but my output replaced the 'a' with '#' when it should've replaced it with '#'. I do all my code in JCreator.
You are incrementing i twice.
for(int i=0; i<s1.length();i++)
and
i++;
What this programme does is;
Prompts for number of testcases,
User then inputs lines of strings which are the test case.
Program is to count the number of vowels in each test case.
then print out the each test case.
btw for this particular program "y" is also a vowel
For instance;
Number of test:
4
githsajklu
bsa uiqsacva
o h qi samsauq sajahhsa
skajayyosak
answer:
5 4 13 2
The problem is that the program doesnt read the last line/input. it just brings the count for the first 3 inputs but not the last. I hope I am clear enough
import java.util.Scanner;
/*
* Counts number of Vowels in each line
*/
public class VowelCount {
/*
*
*/
public static void main(String[] args){
Scanner input = new Scanner(System.in);
Scanner input2 = new Scanner(System.in);
//prompt user for number of test case
System.out.println("Type in number of Test Cases");
int testcases = input.nextInt();
String[] line = new String[testcases];
String newline;
for(int i=0; i<testcases; i++)
{
//initialize input to line 1,2,3 e.t.c
line[i] = input2.nextLine();
//remove all white spaces
newline =line[i].replaceAll(" ", "");
display(testcases, newline);
}
}
/*
* counts how many vowels are in eace line of input
*/
public static int Counter(String input)
{
//start count from 0;
int counter = 0;
for(int i = 0; i<input.length(); i++)
{
//set character at position i to Dstr
char dStr = input.charAt(i);
//compare if dstr is a vowel
if(dStr == 'i' || dStr == 'u' || dStr == 'o' || dStr == 'a' || dStr == 'e' || dStr == 'y')
{
//increase when characte is a vowel
counter++;
}
}
//return the last count
return counter;
}
/*
* diplay the total count;
*/
public static void display(int testcases, String input)
{
System.out.print(" "+Counter(input));
}
}
Do a scan.nextLine() after you read the amount of test cases. Don't know why it works like that, someone feel free to explain, but if you're reading a an int, then a string, you can either do
int n = Integer.parseInt(scan.nextLine());
or
int n = scan.nextInt();
scan.nextLine();
Also, I know you didn't ask, but here's a much simpler way to count the amount of vowels.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
scan.nextLine();
for(int i = 0; i < n; i++){
String str = scan.nextLine();
System.out.println(str.replaceAll("[^AEIOUaeiouYy]", "").length());
}
}
What that does is erase everything that is not a vowel (and y), and prints the length of it. Really not sure if it's faster, but it's a lot simpler.
Actually, here I'm testing and it is working just fine, it is getting exactly how many inputs I asked for.
My console:
Type in number of Test Cases
4
werty
2
sdfghj
0
xdcfvgh
0
xsdfgh
0
Sometimes, having less code can make things clearer:
void printVowelCount(String text) {
System.out.println(text.replaceAll("[^aeiouAEIOU]", "").length());
}
I have this instruction:
Define and test a method called checkString that will take in the word as a parameter and checks whether the String begins and ends with the same letter. If both letters are the same the method returns true otherwise false (returns a boolean). The program treats lower and uppercase letters as equivalent.
Also I need to use the printf statement
Sample output would be:
Type a string: abba
abba begins and ends with the same letter
Here's what I have so far:
import java.util.Scanner;
public class Excercise5 {
public static void main(String[] arg) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Type a string: ");
String word = keyboard.nextLine();
System.out.printf ("%s begins and ends with the same letter." , checkString(word));
}
public static boolean checkString (String word) {
int length = word.length();
word = word.toUpperCase(); //since you are testing them as upper case
char firstLetter = word.charAt(0);
char lastLetter = word.charAt(length - 1);
return firstLetter == lastLetter;
}
}
It appears you've basically figured it out already, but here's a slightly updated version.
import java.util.Scanner;
public class Excercise5{
public static void main(String[] arg) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Type a string: ");
String word = keyboard.nextLine();
if(checkString(word)) {
System.out.printf("%s begins and ends with the same letter.\r\n" , word);
} else {
System.out.printf("%s does not begin and end with the same letter.\r\n", word);
}
}
public static boolean checkString (String word) {
int length = word.length();
word = word.toUpperCase(); //since you are testing them as upper case
char firstLetter = word.charAt(0);
char lastLetter = word.charAt(length - 1);
return firstLetter == lastLetter;
}
}
The method will return true if the first letter and the last letter of the received String is the same. Otherwise it will return false. In the main: do the required definitions and ask the user to enter a String.