public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("type the sentence you want to find the letters of");
String sentence = s.nextLine();
getLetters(sentence);
}
public static void getLetters(String sentence) {
int count;
char ch[] = sentence.toCharArray();
for (int i = 0; i < sentence.length(); i++) {
System.out.print(ch[i]);
}
}
I am trying to display the occurrence of each letter (letter only) in a sentence, and I am lost. I have converted the string into a char array, but I am now lost.
For instance, if I typed the sentence: "Hello, how are you?"
The result would be:
Occurrence of h: 1
Occurrence of e: 2
Occurrence of l: 2
Occurrence of o: 3
etc..
I know I need to utilize my int count, but I am not sure how to do that. Our professor is having us use this:
c[26];
c[ch - 'a']++;
And I'm not sure where to use those for this little project.
Edit: Update
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("type the sentence you want to find the letters of");
String sentence = s.nextLine();
getLetters(sentence);
}
public static void getLetters(String sentence) {
sentence = sentence.toLowerCase();
int count[];
char ch[] = sentence.toCharArray();
for (int i = 0; i < sentence.length(); i++) {
System.out.print(ch[i]);
}
char alphabet[] = "abcdefghijklmnopqrstuvwxyz".toCharArray();
System.out.println();
}
}
Use a HashMap<Character, Integer> to keep track. The key is a unique character, and the integer counts the number of times you see it.
import java.util.HashMap;
public class J {
public static void main(String[] args) {
String string = "aaaabbbccd";
HashMap<Character, Integer> map = frequency(string);
System.out.println(map);
}
public static HashMap<Character, Integer> frequency(String string) {
int length = string.length();
char c;
HashMap<Character, Integer> map = new HashMap<Character, Integer>();
// loop thru string
for (int i = 0; i < length; i++) {
c = string.charAt(i);
// If u have already seen that character,
// Increment its count
if (map.containsKey(c)) {
map.put(c, map.get(c) + 1);
// otherwise this is the first time u
// have seen it, so set count to 1
} else {
map.put(c, 1);
}
}
return map;
}
}
Output:
{a=4, b=3, c=2, d=1}
I don't see reason to use HashMap here. HashMaps are used to map some values into places in memory for faster access, using HashFunction. In this case he will have same, or very similar thing with array and this mapping function that is given to him(ch-'a') . Also, for someone who is doing this, it is maybe too soon for HashMap.
Your problem is that you haven't understood idea.
Letters in java have values (You can check ASCII table). You have 26 letters in alphabet, first one is 'a' and last is 'z'. So you want to have array of 26 elements. Every time when you have 'a' into your string, you want to increment element in place 0 in array, when you come into 'b' you want to increment element in place 1.... when you come to 'z' element 25. So, in fact with (ch-'a') you map your letter in place in array where is count of its ocurrence.
You take string, do .toLowerCase() case on it, pass it once to count letters, then print what you found.
Related
This assignment ask to implement printWordRun so that it prints whatever word run it can find starting from the beginning of the input list words. The word run should be printed in reverse order, with each word on a separate line. PrintWordRun is a method which takes a parameter called words which is an ArrayList<String>. The word run is a series of words in the input list, where each word is longer in length than the previous. The word run ends once we either encounter the end of the list, or we encounter a word whose length is equal to or shorter than the previous word.
The array is:
I
am
cat
with
happy
dog
sitting
the result should be:
happy
with
cat
am
I
To get full credit for this assignment, I have to use a stack to print it as I have done, but I cannot get the word "happy" into the stack. My output is:
I
am
cat
with
public class Program {
private void printWordRun(ArrayList<String> words) {
// Here is the code I Wrote.
Stack<String> wordRun = new Stack<>();
for(int i = 1; i < words.size(); i++) {
String str1 = words.get(i-1);
String str2 = words.get(i);
if(str2.length() < str1.length()) {
break;
}
if(str1.length() < str2.length()){
wordRun.push(str1);
}
System.out.println(wordRun);
}
}
public static void main(String[] args) {
Program program = new Program();
program.testPrintWordRun();
}
private void testPrintWordRun() {
ArrayList<String> words = new ArrayList<>();
words.add("I");
words.add("am");
words.add("cat");
words.add("with");
words.add("happy");
words.add("dog");
words.add("sitting");
System.out.println("Testing printWordRun...");
printWordRun(words);
System.out.println();
}
}
Here is one way to construct the printWordRun function:
Stack<String> wordRun = new Stack<>();
int maxLength = 0;
for(String s : words) {
if(s.length() > maxLength ) {
maxLength = s.length();
wordRun.add(s);
} else
break;
}
while(!wordRun.isEmpty())
System.out.println(wordRun.pop());
Just store a value of the current, maximum length and use this to compare your current string.
Output:
Testing printWordRun...
happy
with
cat
am
I
Start by adding the word to the stack with add(int index, E element) to insert the last item as first, and break the loop if the condition doesn't match afterwards.
private void printWordRun(ArrayList<String> words) {
// Here is the code I Wrote.
Stack<String> wordRun = new Stack<>();
for (int i = 1; i < words.size(); i++) {
String str1 = words.get(i);
String str2 = words.get(i - 1);
wordRun.add(0, str2);
if(str2.length() >= str1.length()) {
break;
}
}
System.out.println(wordRun); // [happy, with, cat, am, I]
}
I am trying to hold the position of every character (A-Z) from encoded string. I am unable to find out a way to implement it in Java.
Below is one example from C++ which I am trying to rewrite in Java.
map<Character,Integer> enc = new map<Character,Integer>();
for (int i = 0; i < encoded.length(); i++)
{
enc[encoded.charAt(i)] = i;
}
Example below:
I will have a Keyword which is unique e.g., Keyword is NEW.
String will be formed by concatenating KEYWORD+Alphabets(A-Z which are not in the Keyword) e.g., NEWABCDFGHIJKLMOPQRSTUVXYZ (note that N,E and W are not repeated again in the above in the 26-Character string. Finally, I would like to hold the position of every character i.e., A-Z from the above string in bold.
If I'm understanding what youre saying, you want to map each character in a string to its index. However, Maps need a unique key for each entry, so your code wont work directly for strings which contain duplicate characters. Instead of using an Integer for each character, we'll use a List of Integers to store all the indexes which this character appears.
Here's how you would do that in java:
public static void main(String[] args) {
Map<Character, List<Integer>> charMap = new HashMap<>();
String string = "aaabbcdefg";
for (int i = 0; i < string.length(); i++) {
Character c = string.charAt(i);
if (charMap.containsKey(c)) {
List<Integer> positions = charMap.get(c);
positions.add(i);
} else {
charMap.put(c, new ArrayList<>(Arrays.asList(i)));
}
}
for (Character c : charMap.keySet()) {
System.out.print(c + ": ");
charMap.get(c).forEach(System.out::print);
System.out.println();
}
}
output:
a: 012
b: 34
c: 5
d: 6
e: 7
f: 8
g: 9
If you don't want to handle duplicates letters , you can do as follows, it’ll only keep last occurrence for each letter :
Map<Character, Integer> enc = new HashMap<>();
for (int i = 0; i < encoded.length(); i++) {
enc.put(encoded.charAt(i), i);
}
——————-
To handle duplicates char, you can hold them in a List or concatenate them in a String for example (on the second I add a filter operation to remove spaces)
public static void main (String[] args)
{
String str = "AUBU CUDU";
Map<Character, List<Integer>> mapList =
IntStream.range(0, str.length())
.boxed()
.collect(Collectors.toMap(i->str.charAt(i), i->Arrays.asList(i), (la,lb)->{List<Integer>res =new ArrayList<>(la); res.addAll(lb); return res;}));
System.out.println(mapList);
//{ =[4], A=[0], B=[2], C=[5], D=[7], U=[1, 3, 6, 8]}
Map<Character, String> mapString =
IntStream.range(0, str.length())
.boxed()
.filter(i->(""+str.charAt(i)).matches("[\\S]"))
.collect(Collectors.toMap(i->str.charAt(i), i->Integer.toString(i), (sa,sb)-> sa+sb ));
System.out.println(mapString);
//{A=0, B=2, C=5, D=7, U=1368}
}
Code Demo
I have an array of characters. I should remove any duplicate characters. I did comparison between the string elements with an array of alphabets. There is another array that acts as counter for any duplictae alphabet. If any character has been found for more than once, I should remove the duplicated character and shif the elements to left. Below is the code. I get error at the line with the comment. Java needs the left hand side of the assignment to be variable. Can you help?
import java.util.ArrayList;
import java.util.Scanner;
public class removeduplicate {
public static void main (String args[])
{
Scanner s=new Scanner(System.in);
String str="abbsded";
String myChars="abcdefghijklmnopqrstuvwxyz";
int[] myCounter=new int[26];
for (int i=0; i<str.length(); i++)
{
for(int j=0; j<myChars.length(); j++)
{
if(str.charAt(i)==myChars.charAt(j))
{
myCounter[j]++;
if (myCounter[j]>1)
{
System.out.println("duplication found in "+ str.charAt(i));
for(int h=i; h<str.length();h++)
{
//this line does not work.
str.charAt(h)=str.charAt(h-1);
}
}
}
}
}//end for
}
}
You can use a Hashmap to keep track of the characters you have run into during your implementation. Then just increment every time you see a character in the alphabet. Only adding a letter to the returned string if the character hasn't been seen before.
public static String removeDuplicates(String input)
{
String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
input = input.toUpperCase();
HashMap<Character, Integer> charData = new HashMap<>();
//create the map to store counts of all the chars seen
for(int i = 0; i < alphabet.length(); i++)
charData.put(alphabet.charAt(i), 0);
String cleanedInput = "";
for(int index = 0; index < input.length(); index++)
{
char letter = input.charAt(index);
if(charData.containsKey(letter))
{
charData.put(letter, charData.get(letter) + 1);
//if count is 1 then its the first time we have seen it
if(charData.get(letter) == 1)
{
cleanedInput += letter;
}
}
}
return cleanedInput.toLowerCase();
}
Example Call
public static void main(String[] args) {
System.out.println(removeDuplicates("abbsded"));
System.out.println(removeDuplicates("abbsded!!!"));
System.out.println(removeDuplicates("hahahahahahahahahah"));
}//main method
Output
absde
absde
ha
Note: it only returns the characters once and no characters that aren't in the alphabet are considered in the new trimmed String.
I am trying to write this program so that when the user inputs a line of text they are given a chart showing how many times each letter is used. I broke it up into an array but I kept getting an error for "counts[letters[a] == 'a']++;" saying i can't convert a string to a char or a boolean to a int, depending on the way I put it. I can't figure out why it's not all char.
import java.util.*;
public class AnalysisA { //open class
public static String input;
public static String stringA;
public static void main (String args []) { //open main
System.out.println("Please enter a line of text for analysis:");
Scanner sc = new Scanner(System.in);
input = sc.nextLine();
input = input.toLowerCase();
System.out.println("Analysis A:");//Analysis A
System.out.println(AnalysisA(stringA));
} // close main
public static String AnalysisA (String stringA) { // open analysis A
stringA = input;
char[] letters = stringA.toCharArray();
int[] counts = new int[26];
for (int a = 0; a < letters.length; a++) { //open for
counts[letters[a] == 'a']++;
System.out.print(counts);
} //close for
}
counts[___] expect an Integer index, whereas your expression letters[a] == 'a' return a boolean
Im guessing you're trying to increment your 'Dictionary' value by 1 each time a letter is met.
You can get the index by making letters[a] - 'a'
Because of the order in the ASCII table, letter 'a' which equal 97 if subtracted to another letter, say 'b' which is 98, will produce the index 1, which is the correct position for your base26 'Dictionary'
Extra:
You should use for (int i = ... for indexing (i instead of a, its easy to mixed variables up if you name your index like that)
You must make
sure all the characters are lower-case before you start doing this,
because as you can see in the table above 'B' - 'a' and 'b' - 'a'
are 2 very different things.
The expression letters[a] == 'a' results in a boolean answer (1 or 0), but you have that indexing an array, which must be an int.
What you're basically telling Java is to do counts[true]++ or counts[false]++, which makes no sense.
What you really want is a HashMap that maps each character to the amount of times you saw it in the array. I won't put the answer here, but look up HashMaps in Java and you'll find the clues you need.
If you use a Map you can do this easily without complicating..
Map<Character, Integer> map = new HashMap<Character, Integer>();
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
public class AnalysisA { // open class
public static String input;
public static void main(String args[]) { // open main
System.out.println("Please enter a line of text for analysis:");
Scanner sc = new Scanner(System.in);
input = sc.nextLine();
input = input.toLowerCase();
sc.close();
System.out.println("Analysis A:");// Analysis A
System.out.println(Analysis());
} // close main
public static String Analysis() { // open analysis A
Map<Character, Integer> map = new HashMap<Character, Integer>();
char[] letters = input.toCharArray();
Integer count;
for (char letter : letters) {
count = map.get(letter);
if (count == null || count == 0) {
map.put(letter, 1);
} else {
map.put(letter, ++count);
}
}
Set<Character> set = map.keySet();
for (Character letter : set) {
System.out.println(letter + " " + map.get(letter));
}
return "";
}
}
I would like to ask you a question, I want to count how many times a specified number is in a given numer (long) from the user and print it as an int.
Could you please help me with this code?
Apologize for my english.
Example:
< number specified = 4; number given = 34434544; result = 5. >
Check whether the least-significant digit is equal to the digit you are searching for; then divide by ten and check again; keep going until you reach zero.
int cnt = 0;
while (value != 0) {
if (value % 10 == digit) ++cnt;
value /= 10;
}
Where you are trying to count the occurrences of digit in the big number value.
If you're using Java 8:
long count = String.valueOf(givenNumber).chars()
.filter(c -> c == (specifiedNumber + '0'))
.count();
Make a Scanner to get input from System.in. Then, iterate through the String returned by turning it into a char[]. Then analyse each char and count original characters. Probably use a Map<Character, Integer> for this. For each element in the Map, iterate by one if it is in the Map. Query the Map for your desired character and print the result when finished.
public static void main(String[] args) {
CharacterFinder cf = new CharacterFinder();
Scanner scan = new Scanner(System.in);
String input = scan.nextLine();
Map<Character, Integer> resultsMap = cf.countChar(input);
System.out.println(resultsMap.get('g'));
}
// Note that 'null' means that it does not appear and if it is null, you ought print 0 instead.
// Also note that this method is case sensitive.
private Map<Character, Integer> countChar(String input) {
Map<Character, Integer> resultsMap = new HashMap<Character, Integer>();
for (int i = 0; i < input.length(); i++) {
Character element = input.charAt(i);
if (resultsMap.containsKey(element)) {
Integer cCount = resultsMap.get(element);
resultsMap.put(element, cCount + 1);
} else {
resultsMap.put(element, 1);
}
}
return resultsMap;
}
Well, unless you already know the char you want. In that case, analyse for that exact char.
public static void main(String[] args) {
CharacterFinder cf = new CharacterFinder();
Scanner scan = new Scanner(System.in);
String input = scan.nextLine();
// Call counting method and print
System.out.println(cf.countChar(input, '5'));
}
// Counting method
private int countChar(String input, char c) {
int x = 0;
for (int i = 0; i < input.length(); i++) {
if (input.charAt(i) == c) {
x++;
}
}
return x;
}