Printing out frequency of letters instead of how many times? - java

I'm trying to change my code so that it prints how the frequency of the letters and not how many there is e.g. "I am a man I am a man" should give the same answer as "I am a man" since the relative proportions of each letter to the whole sequence is the same.
So the desired output would be:
Letter A: Count: 0.43
Letter I: Count: 0.14
Letter M: Count: 0.29
Letter N: Count: 0.14
So the count will always add up to 1.0.
At the moment, my code just counts and displays how many times the letter appears, is this simple to change?
//

You could try something like this to get the percent of total characters:
int total = 0;
for(int i = 0; i < lettersArray.length; i ++)
{
total += letterArray[i];
}
for (char characters = 'a'; characters <= 'z'; characters++) {
int index = characters - 'a';
//print out the analysis
System.out.println("'" + characters + "' entered " + (((double)letterArray[index] / (double)total))
+ " times");
}}}

System.out.println("'" + characters + "' entered " + letterArray[index] /
(double)line.length() + " times");

Related

i don't understand how length() works in this code

Can someone please explain this code for me, especially this part.
int lastpos = message.length() - 1;
Why did he add - 1 ?
==
System.out.print("What is your message? ");
String message = kb.nextLine();
System.out.println("\nYour message is " + message.length() + " characters long.");
System.out.println("The first character is at position 0 and is '" + message.charAt(0) + "'.");
int lastpos = message.length() - 1;
System.out.println("The last character is at position " + lastpos + " and is '" + message.charAt(lastpos) + "'.");
System.out.println("\nHere are all the characters, one at a time:\n");
for ( int i=0; i < message.length(); i++ )
{
System.out.println("\t" + i + " - '" + message.charAt(i) + "'");
}
int a_count = 0;
for ( int i=0; i<message.length(); i++ )
{
char letter = message.charAt(i);
if ( letter == 'a' || letter == 'A' )
{
a_count++;
}
}
System.out.println("\nYour message contains the letter 'a' " + a_count + " times. Isn't that interesting?");
}
}
Because indices start at 0 . If you have a list of {0, 1, 2}, note that it has a length of 3, but the last index is only 2. - 1 is used to correct for that.
If you iterated to the element at index 3 (the length of the list), you would go off the end of the list, causing an IndexOutOfBoundsException.
Note, I used lists as an example for ease of understanding, but it's exactly the same when it comes to Strings. All iterables start at an index of 0.
Suppose you have a String "Abdullah" and you want to print last character of that string then
int lastpos = message.length() - 1
Iine gives you last character of that String.
So in given code that line print the last character of the input String.

Duplicating prime numbers of even numbers

This part of an assignment requires to check every even number in an array for 2 prime numbers that add up to that even number. I already managed to find all the primes between 2 and each even number and put those primes in a separate array list. I've already found how to find 2 prime numbers that add up to each even number; however when I check the output, it gives me multiple answers like this:
How many numbers would you like to compute:
12
Your two prime factors that add up to 4 are:
2 & 2
Your two prime factors that add up to 6 are:
3 & 3
Your two prime factors that add up to 8 are:
3 & 5
Your two prime factors that add up to 8 are:
5 & 3
Your two prime factors that add up to 10 are:
3 & 7
Your two prime factors that add up to 10 are:
5 & 5
Your two prime factors that add up to 12 are:
5 & 7
Your two prime factors that add up to 12 are:
7 & 5
All I want is ONE pair of primes that sum up to each even number in a loop. My code looks like this:
//For Loop looks at every even number in the arrayList
//for(int c = 0; c < len; c++) {
//Code for Numbers that come before every even number
//Code for Finding primes
//Finding prime numbers that add up to even number
int len3 = primeNumbers.size();
for(int f = 0; f < len3; f++) {
if(primeNumbers.get(f) + primeNumbers.get(f) == index) {
System.out.println("Your two prime factors that add up to " + index + " are: ");
System.out.println(primeNumbers.get(f) + " & " + primeNumbers.get(f));
break;
}
for(int g = 1; g < len3; g++) {
if(primeNumbers.get(f) + primeNumbers.get(g) == index) {
System.out.println("Your two prime factors that add up to " + index + " are: ");
System.out.println(primeNumbers.get(f) + " & " + primeNumbers.get(g));
break;
}
}
}
}
Try this. Your second loop should start from f. So if you do that u can remove the first if you have and then have this. I havent tested it. But try and let me know if it works.
for(int f = 0; f < len3; f++) {
for(int g = f; g < len3; g++) {
if(primeNumbers.get(f) + primeNumbers.get(g) == index) {
System.out.println("Your two prime factors that add up to " + index + " are: ");
System.out.println(primeNumbers.get(f) + " & " + primeNumbers.get(g));
}
}
}
When you call break statement it simply break current loop if your method only handle this logic simply change break statement to return. Hope this is you expect :
int len3 = primeNumbers.size();
for (int f = 0; f < len3; f++) {
if (primeNumbers.get(f) + primeNumbers.get(f) == index) {
System.out.println("Your two prime factors that add up to " + index + " are: ");
System.out.println(primeNumbers.get(f) + " & " + primeNumbers.get(f));
return;
}
for (int g = 1; g < len3; g++) {
if (primeNumbers.get(f) + primeNumbers.get(g) == index) {
System.out.println("Your two prime factors that add up to " + index + " are: ");
System.out.println(primeNumbers.get(f) + " & " + primeNumbers.get(g));
return;
}
}
}

Converting a string of numbers from Scanner to integers using loop?

Have an assignment that requires me to take an input from the user of a series of numbers. ex.(1 12 -34 9) I am then asked to determine the number of positive and negative numbers. The class has not gotten into any of the "easy" solutions to this problem such as arrays, string.split(), buffers etc... The most advanced methods taught are the use of loops. My question is how can I take the string line of numbers and separate them individually without the aforementioned methods? I can take it the rest of the way I am certain without complications but this one step has me at a loss. Any input will help. Thanks
Presumably you start with a string containing all the numbers - I'll call it numString.
Then:
ArrayList<String> numbers = new ArrayList<String>();
String aNumber = "";
for (int i = 0; i < numString.length(); i++){
String letter = numString.substring(i, i+1);
if (letter.equals(" ")){
numbers.add(aNumber);
aNumber = "";
}
else{
aNumber += letter;
}
}
ArrayList<String> negatives = new ArrayList<String>();
ArrayList<String> positives = new ArrayList<String>();
for (String s : numbers){
if(s.contains("-")){
negatives.add(s);
}else{
positives.add(s);
}
System.out.println("There were " + positives.size() + "positive numbers.");
System.out.println("There were " + negatives.size() + "negative numbers.");
System.out.println("Making a total of " + numbers.size() + "numbers.");
Of course, I'd only recommend this solution in the context of what you've learned. This wouldn't be the best way to do this otherwise.
Good luck!
edit - Alternatively - quicker but more logically complex option:
There should be as many "-" as negative numbers, and one less space than total numbers - and as many positive numbers as totalCount minus negativeCount.
So in pseudocode:
NegativesCount = count("-");
PositivesCount = count(" ") + 1 - NegativesCount;
and in code:
int dashCount = 0;
int spaceCount = 0;
for (int i = 0; i < numString.length(); i++){
String letter = numString.substring(i, i + 1);
if (letter.equals(" ")){
spaceCount++;
}
else if(letter.equals("-")){
dashCount++;
}
}
int negCount = dashCount;
int posCount = spaceCount - 1 + dashCount;
System.out.println("There were " + posCount + "positive numbers.");
System.out.println("There were " + negCount + "negative numbers.");
System.out.println("Making a total of " + spaceCount + "numbers.");
It has come to my attention that the confusing way in which the assignment is worded combined with the misleading example of the running program led me to believe the numbers were entered all at once when in reality the numbers are to be prompted for one at a time. I can easily write the program that handles THIS method. Thanks to all of the responses and I apologize for a question that leads to nowhere. Just so you don't think I am crazy here is the "example" of the program running as it should provided in the assignment:
Enter an integer, the input ends if it is 0: 1 2 -1 3 0
The number of positives is 3
The number of negatives is 1
Notice how the input looks as though it is a one line entry -_-
The best way to do this is by using regex.
You can count the instance of followed by -ve sign to count number of negative integers. and count instance of followed by numerical value to count number of positive integers.

how to report all tied positions for the last element in the list in JAVA

I have a task to print n frequently used words based on their count values across multiple files.
Now the issue is after printing n words, I have to print all the ties at the last position
for instance if I printed 10 frequently used words based on the highest count
and the output comes like this when I use a for loop.
CODE
int listSize = newList.size() >= 10 ? 10 : newList.size();
for (int k = 0; k < listSize; k++) {
Words w = newList.get(k);
System.out.println("Word : " + ++j + " " + w.getWord() + " "
+ w.getCount());
// System.out.println(w.getWord());
}
OUTPUT :
word 1 : liked 104
word 2 : hello 98
....
....
....
word 10 : picnic 15
now If I encounter words further with the same count that is 15 I have to print them also
if I have five words with the same word count 15
I have to print all of them that is all ties for the last position must be reported like this
**OUTPUT :**
word 11 : camera 15
word 12 : monkey 15
word 13 : carrot 15
word 14 : penguin 15
word 15 : bottle 15
how to implement this case guide me thanks in advance
If newList is sorted by getCount then the simpliest way to print words with same count as last printed word is:
int k; // init k before the cycle
for (k = 0; k < listSize; k++) {
Words w = newList.get(k);
System.out.println("Word : " + ++j + " " + w.getWord() + " "
+ w.getCount());
// System.out.println(w.getWord());
}
if (k > 0) {
int lastCount = newList.get(k - 1).getCount(); // last printed count
// print words from the k-th
while (k < newList.size()
&& newList.get(k).getCount() == lastCount) {
Words w = newList.get(k);
System.out.println("Word : " + ++j + " " + w.getWord() + " "
+ w.getCount());
++k;
}
}

ArrayIndexOutOfBoundsException while counting ASCII character frequency

I am trying to count the frequency of ASCII characters from a String input that was converted to a character array.
I tried to implement the accepted answer from this thread, along with my code to print the results in a 3-column table.
package com.mypackage.mp;
import java.util.*;
public class AsciiCounter {
public static void displayAsciiOccurrence(String inputWords) {
int[] iaCount = new int[256]; //this
char[] caInputWords = inputWords.toCharArray();
int i = 0;
for(i = 0; i < caInputWords.length; i++) {
iaCount[caInputWords[i]]++;
}
// Print table
System.out.println("\nDEC\tASCII\tFREQ");
for(int ctr = 0; ctr < 256; ctr++) {
System.out.println(ctr +"\t" + (char) (ctr) + "\t" + iaCount[caInputWords[i]]); //this
}
}
public static void main(String[] args) {
String inputWords = null;
Scanner scn = new Scanner(System.in);
System.out.print("Enter words: ");
inputWords = scn.nextLine();
displayAsciiOccurrence(inputWords); //this
scn.close();
}
}
However, it is returning an ArrayIndexOutOfBoundsException. My desired output is supposed to be:
Enter words: AA bC! d
DEC ASCII FREQ
0
.. .. ..
32 2
33 ! 1
.. .. ..
65 A 2
66 B 0
67 C 1
..
98 b 1
99 c 0
100 d 1
..
255
(The .. pertains to whatever is in between and must print 0 as frequency.)
Stack Trace:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 8
at
com.mypackage.mp.AsciiCounter.displayAsciiOccurrence(AsciiCounter.java:20)
at
com.mypackage.mp.AsciiCounter.main(AsciiCounter.java:31)
The error is in your printing loop:
System.out.println(ctr +"\t" + (char) (ctr) + "\t" + iaCount[caInputWords[i]]);
Since i hasn't changed since the first loop, it is equal to caInputWords.length at this point.
I guess you just meant:
System.out.println(ctr +"\t" + (char) (ctr) + "\t" + iaCount[ctr]);
As a side note, you might not want to print all the ASCII characters themselves. Some of them don't represent printable characters or are whitespace. One simple way around this is to check that iaCount[ctr] > 0 before printing so you only print characters that were in the String to begin with.
You have a problem in your second loop:
for(int ctr = 0; ctr < 256; ctr++) {
System.out.println(ctr +"\t" + (char) (ctr) + "\t"
+ iaCount[caInputWords[i]] // HERE
);
}
You meant iaCount[ctr]! You use i which is 256 when you enter this loop, since it has been set to this value by your previous loop. And since the iaCount array is only 256 chars long, this index is out of bounds.
Also, you fail to check what happens if you enter a non ASCII character.
To avoid this kind of error, change your first for loop to:
for(int i = 0; i < 256; i++)
Doing so in your first loop would have shown that i didn't exist in the second.
the i variable has not been reset. but you don't need to use variable i at all after the frequency calculation. You need to use ctr for frequency of all the characters.
for(int ctr = 0; ctr < 256; ctr++) {
System.out.println(ctr +"\t" + (char) (ctr) + "\t" + iaCount[ctr]);
}
That line can throw exception.
System.out.println(ctr +"\t" + (char) (ctr) + "\t" + iaCount[caInputWords[i]]);
Change it to that
for(int ctr = 0; ctr < 256; ctr++) {
System.out.println(ctr +"\t" + (char) (ctr) + "\t" + iaCount[ctr]);
}

Categories

Resources