I am a java beginner with very weak understanding of java. To my already working code which already calculates the number of words in a sentence, total number of characters of a sentence and the total number of characters for each word, I would like to add another function.
I would like to add a piece of code which calculates the average of word length, for example if I type in 'hey hi cat dog i', the output would be 2.4. (Because the total number of characters for this sentence is 12, divided by the number of words (5 words) gives the average of 2.4).
Underneath there is my piece of code I'm working on and this is what I created based on many tutorials, but they all teach the average for numbers, not word lengths. My thinking is that my code should firstly count the sum of characters for each words (word.length) and then divide it by the sum of words (sentence.length). But it seems not to work. Can you please help me to correct this piece of code?
{
//prints out average word length
int length = wordcount / word.length ;
sum = sum + word.length / sentence length; //this counts the sum of characters of words and divides them by the number of words to calculate the average
System.out.println("The average word length is " + sum);} //outputs the sum calculated above
{
Underneath there is my full code to help you understand better what I mean. Thank you for all your help!
public class Main
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in); //This adds a scaner/text window to the program.
while(true)
{ // have created infinite loop.
System.out.print("Enter your text or enter 'quit' to finish the program: ");
String sentence = in.nextLine();
if(sentence.equals("quit"))
{ // if enterd value is 'quit' than it comes out of loop
break;
}
else
{ //else if 'quit' wasn't typed it, the program displays whats underneath.
System.out.println("You have entered: "
+ sentence); // to print what the user has entered in the text window/scanner.
System.out.println("The total number of characters is " + sentence.length()
+ "."); // to print the total number of characters
System.out.println("This piece of text has " + countWords(sentence)
+ " words."); //this method counts the number of words in the entered sentence.
String[] words =
sentence.split(" "); // to get the individual words, splits them when the free space (" ") is found.
int maxWordLength = 0;
int wordLength = 0;
for(int i = 0; i < words.length; i++)
{
wordLength = words[i].length();
if(wordLength > maxWordLength)
{ //This piece of code is an array which counts the number of words with the same number of characters.
maxWordLength = wordLength;
}
}
int[] intArray = new int[maxWordLength + 1];
for(int i = 0; i < words.length; i++)
{
intArray[words[i].length()]++;
}
for(int i = 1; i < intArray.length; i++)
{
System.out.printf("There are " + "%d word(s) of length %d<\n>", intArray[i], i);
}
System.out.println("The numbers of characters for each word:"); //word.length method counts the number of characters for each word.
for(int i = 0; i < words.length; i++)
{
System.out.println(words[i] + " = " + words[i].length() + " characters");
}
}
}
}
{
//prints out average word length
int length = wordcount / world.length;
sum = sum + word.length / sentence
length; //this counts the sum of characters of words and divides them by the number of words to calculate the average
System.out.println("The average word length is " + sum);
} //outputs the sum calculated above
{
in.close();
}
private static int countWords(String str)
{ //this piece of code splits the words when the space (" ") is found and prints out the length of words.
String words[] = str.split(" ");
int count = words.length;
return count;
}
}
Use the split method.
Here is an example:
//returns the average word length of input string s
//the method is of double type since it will likely not return an integer
double avgWordLength(String s){
String delims=",;. ";//this contains all the characters that will be used to split the string (notice there is a blank space)
//now we split the string into several substrings called "tokens"
String[] tokens = s.split(delims);
int total=0;//stores the total number of characters in words;
for(int i=0; i<tokens.length(); i++){
total += tokens[i].length(); //adds the length of the word to the total
}
double avg = total/tokens.length();
return avg;
}
And there you have it.
you can try like this
String input = "hello Alpha this is bravo";
String[] strArray = input.split(" ");
float totalChars = 0;
for(String s : strArray){
totalChars += s.length();
}
float words = strArray.length;
float averageWordLength = (float)(totalChars/words);
System.out.println(averageWordLength);
You simply need to call something like:
public static double getAverageCharLength(String str) {
String words[] = str.split(" ");
int numWords = words.length;
int totalCharacters = 0;
for(int i = 0; i < numWords; i++)
totalCharacters = totalCharacters + words[i].length();
return totalCharacters/numWords;
}
I can't really tell you where you're going wrong because I can't understand the jumble that is your code. But this is the logic you should follow.
Note: This will not calculate correctly the average word length if your words contain special characters like apostrophes. I'm not sure if you need to look out for that in your case but if you do, look into regular expressions to specify what characters to ignore and using String methods like contains().
Also note that you have no method signatures for the following two methods you're trying to define:
{
//prints out average word length
int length = wordcount / world.length;
sum = sum + word.length / sentence
length; //this counts the sum of characters of words and divides them by the number of words to calculate the average
System.out.println("The average word length is " + sum);
} //outputs the sum calculated above
{
in.close();
}
Maybe try going over the Java syntax in the oracle docs if you're unsure on how to go about writing these methods correctly.
Related
Index out of bound Exception... and sorting is wrong, please check below code, what is the problem ??
it takes string and an integer as input, it computes all the substrings of length k then sees which substring is lexicographically first and last and sorts it inside collection array and returns lexicographically smallest as smallest and largest as largest
public static String getSmallestAndLargest(String s, int k) {
String smallest = "";
String largest = "";
String[] collections = new String[s.length()-k];
for(int i=0;i<=s.length()-k-1; i++) {
// if(i==(s.length()-k)){
// collections[i] = s.substring(i,i+k-1);
// }
collections[i] = s.substring(i,i+k);
}
for(int i=0; i<collections.length;i++){
System.out.print(collections[i]+" ");
}
System.out.println("");
for(int i=0;i<collections.length-1;i++){
for(int q=1;q<collections.length;q++){
if(collections[i].compareTo(collections[q])<0){
String temp = collections[i];
collections[i]=collections[q];
collections[q]=temp;
}
}
}
smallest = collections[0];
largest = collections[collections.length-1];
for(int i=0; i<collections.length;i++){
System.out.print(collections[i]+" ");
}
System.out.println("");
// s.substring(0,3) , s.substring(3,6) , substring(i,i+k)
return smallest + "\n" + largest;
}
Your array size is to small. For Example: if your string is 6 characters long and the substring length k would be 5, your array should fit 2 strings inside.
To compensate for the too small array you reduced the loop also by 1, effectively ignoring the last substring.
Whatever sorting-algorithm you tried to implement made little sense. If you want to implement the sorting yourself, have a look here. If you're fine with using java sorting the array for you, use Collections.sort() which takes the array in form of a list.
Additional Note: uppercase characters have a lower index
The fixed code would look like this:
public static String getSmallestAndLargest(String s, int k) {
String smallest = "";
String largest = "";
//1. create an array with the length of possible substrings
String[] collections = new String[s.length() - k + 1];
//2. fill the array with these substrings
for (int i = 0; i <= s.length() - k; i++) {
collections[i] = s.substring(i, i + k);
}
//print all substrings in original order
for (int i = 0; i < collections.length; i++) {
System.out.print(collections[i] + " ");
}
System.out.println("");
//3. sort the array
Collections.sort(Arrays.asList(collections));
smallest = collections[0];
largest = collections[collections.length - 1];
//print in sorted order
for (int i = 0; i < collections.length; i++) {
System.out.print(collections[i] + " ");
}
System.out.println("");
return smallest + "\n" + largest;
}
If you're asking a question you should also provide context and examples for your inputs, the expected outputs and the whole Stacktrace if there is one. That way other people don't need to reproduce the error themselves to help you. Also formatting and commenting your code helps a lot.
Having difficulty trying to write code for this problem above. Please find the code below. Have to read in 5 numbers and compute the frequency of positive numbers entered.
import java.util.Scanner;
public class Lab02Ex2PartB {
public static void main (String [] args){
Scanner input = new Scanner(System.in);
System.out.println("Please enter a positive integer");
int number = input.nextInt();
for(int i = -2 ; i < 4 ; i++)
System.out.println("Positive Count is: " + i);
}
}
Your problem is that you have a task that needs to be repeated (about the user entering a value); but your loop (the perfect mean to do things repeatedly) ... doesn't cover that part!
for(int i=-2 ; i<4 ; i++)
System.out.println("Positive Count is: " +i);
Instead, do something like:
for (int loops = 0; loops < 5; loops++) {
int number = input.nextInt();
Then of course, you need to remember those 5 values, the easiest way there: use an array; Turning your code into:
int loopCount = 5;
int numbers[] = new[loopCount];
for (int loops = 0; loops < loopCount; loops++) {
numbers[loops] = input.nextInt();
And then, finally, when you asked for all numbers, then you check the data you got in your array to compute frequencies. A simple approach would work like this:
for (int number : numbers) {
if (number > 0) {
System.out.println("Frequency for " + number + " is: " + computeFrequency(number, numbers));
}
with a little helper method:
private int computeFrequency(int number, int allNumbers[]) {
...
Please note: this is meant to get you going - I don't intend to do all your homework for you. You should still sit down yourself and figure what "computing the frequency" actually means; and how to do that.
Try this one, Remember if you only want to know the frequency(not storing)
import java.util.Scanner;
public class Lab02Ex2PartB {
public static void main (String [] args){
int i = 1;// is a counter for the loop
int positive =0;// counts positive numbers
while(i<=5){
Scanner input = new Scanner(System.in);
System.out.println("Please enter a whole positive number");
int number = input.nextInt();
if(number > 0){
positive ++;
}
i++;
}
System.out.println("Positive Count is: "+ positive);
How can the number of elements in an array be counted?
So the array can hold 10 elements, but not all are filled.
How do I count the number of elements that are entered?
Also, what is the correct way to find the average of an array?
What I have now gives me this,
The number of valid grades entered is 10
[D#7ea987ac[D#7ea987acAverage: 0.0
//validate strings entered by user
if(convertedInput >= 0 && convertedInput <=100){
ValidArray[validArraycount] = convertedInput;
validArraycount ++;
}
}
catch(NumberFormatException e){
}
//Prints number of valid values entered
System.out.println("The number of valid grades entered is " + vArrayLen);
//for printing array backwards
for (int i = (arraycount-1); i>=0; i--){
System.out.print(ValidArray);
}
//calculates sum of all values in array of ValidArray (of grades)
for(double d : ValidArray){
sum += d;
}
//avergae of valid number array
double average = (sum/ValidArray.length);
System.out.println("Average: " + average);
}
}
Thank You.
EDIT:
The input is suppose to be up to 10 strings. Anything can be entered. Valid strings are double numbers between 0-10 that can be 0 and 10. All strings not valid are discarded.
As of now this is what my code looks like:
import java.util.*;
public class Grades{
public static void main(String args[]){
int arraycount = 0;
final int SIZE = 100;
int validArrayCount = 0;
final int ValidArraySize = 100;
int valuesinValidArray = 0;
Scanner reader = new Scanner(System.in);
String initialInput = new String ("");
String [] sArray = new String[SIZE];
double [] ValidArray = new double[ValidArraySize];
double sum = 0;
boolean exit = false;
System.out.println("You may enter up to 100 grades.");
System.out.println("When you are done entering grades, press the enter/return key.");
//Prints to user. Stops if nothing is entered.
while((arraycount < SIZE)&&(exit == false)){
System.out.println("Enter line " + (arraycount+1) + ": ");
initialInput = reader.nextLine();
if (initialInput.length()<1){
exit = true;
}
else{
sArray[arraycount]=initialInput;
arraycount++;
}
}
//convert string to double
try{
double convertedInput = Double.parseDouble(initialInput);
//validate strings entered by user
if(convertedInput >= 0 && convertedInput <=100){
ValidArray[validArrayCount] = convertedInput;
validArrayCount ++;
}
}
catch(NumberFormatException e){
}
//Prints number of valid values entered
System.out.println("The number of valid grades entered is " + vArrayLen);
//for printing array backwards
for (int i = (ValidArraySize-1); i>=0; i--){
System.out.println(ValidArray[i] + "");
}
//calculates sum of all values in array of ValidArray (of grades)
for(double d : ValidArray){
sum += d;
}
//avergae of valid number array
double average = (sum/validArrayCount);
System.out.println("Average: " + average);
}
}
validArrayCount already holds the number of elements that are entered.
Instead of printing vArrayLen for the number of valid grades entered, print out validArrayCount:
System.out.println("The number of valid grades entered is " + validArrayCount);
To get the average, you can divide by validArrayCount instead of ValidArray.length:
double average = (sum/validArrayCount);
Also, you have to add the array indices when printing the array backwards:
// for printing array backwards
for (int i = validArrayCount-1; i>=0; i--){
System.out.print(ValidArray[i] + " ");
}
System.out.println(); //For inserting a new line after printing all array elements
You are already doing it, also ValidArray is a terrible name. You forgot to use the array index in your for loop and the number you are using for that is validArraycount -
// Prints number of valid values entered
System.out.println("The number of valid grades entered is "
+ validArraycount);
// for printing array backwards
for (int i = validArraycount-1; i>=0; i--){
System.out.print(ValidArray[i] + " "); // <-- don't forget the index.
}
System.out.println(); // <-- next line.
double sum = 0;
// sum the values in array of ValidArray (of grades)
for(double d : ValidArray){
sum += d;
}
// Average. Sum / the count
double average = (sum / validArraycount);
System.out.println("Average: " + average);
The goal of this code was to create a program using main method java to analysis a piece text which has been entered from a user.
They do this by entering the text into a scanner which is then analysed by the program. The analysis is to produce word frequency, mean length and also print out the results in a form of a asterisks chart, were a single "*" represents 1 words.
For example " Birds can maybe fly" produces this results:
Enter text:
Birds can maybe fly
Birds can maybe fly
1 letter words: 0
2 letter words: 0
3 letter words: 2
4 letter words: 0
5 letter words: 2
mean lenght: 4.0
1 letter words
2 letter words
3 letter words **
4 letter words
5 letter words **
So far I've completed the word frequency and the word mean, but the part I'm stuck on is creating the asterisks chart. This is an area in which I've never touch upon and was wondering how I would go about it, would I use a histogram or just use my int and then print out a "*" instead of a number?. I'm not expecting anyone to just hand me code, but if someone could give me a hint in what I should do or just point me the right direction or maybe just give me an explanation in what I should do, it would be greatly appreciated.
Code:
import java.util.Scanner;
public class Freq
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
while (true)
{
System.out.println("Enter text: ");
String s;
s = scan.nextLine();
String input = s;
String strippedInput = input.replaceAll("\\W", " ");
System.out.println("" + strippedInput);
String[] strings = strippedInput.split(" ");
int[] counts = new int[6];
int total = 0;
for (String str : strings)
if (str.length() < counts.length)
counts[str.length()] += 1;
for (String s1 : strings)
total += s1.length();
for (int i = 1; i < counts.length; i++)
System.out.println(i + " letter words: " + counts[i]);
System.out.println(("mean lenght: ") + ((double) total / strings.length));
}
}
}
Commons Lang StringUtils.repeat()
Usage:
String str = "*";
int n = 2;
String repeated = StringUtils.repeat(str, n);
repeated will be: **
You could just loop over counts and for each cell print a number of asterisks equal to the number stored in it:
for (int i = 0; i < counts.length; ++i) {
StringBuilder sb = new StringBuilder(i).append(" letter words ");
for (int j = 0; j <= counts[i]; ++j) {
sb.append('*');
}
System.out.println(sb);
}
I keep trying to add (many times) +1 to a number (the number is zero) already in an array which is zero but it is not working.
int i=0;//var for arrays
int [] countArray = new int[10];
/////////////////////
//__________ ask for values --------------
System.out.println("Hello please enter the number you would" +
" like to be sorted separated by commas. \n" +
"Example: \" 2,3,5,83,2 \".\t only use" +
" commas. to separate numbers\n");
//----------- save values -----
Scanner scan = new Scanner(System.in);
String allInput = scan.nextLine();//single string object with all input
String [] arr = allInput.split(",");//string array that holds all values
//as String
int [] numbersArray =new int[arr.length] ;//numbers
for ( String w: arr){//change Strings to Int
numbersArray[i]= Integer.valueOf(arr[i]);
i++;
}
//__ set all number in count to zero because necessary
i=0;
for ( int x: countArray){//set all numbers to zero
countArray[i]=0;
i++;
} //everything zeroed
i=0;
This works now, thank you guys:
for (int x = 0; x < numbersArray.length; x++){
if (numbersArray[x] >=10 && numbersArray[x] <=100) {
countArray[(numbersArray[x]-1)/10]++;}
else{
if (numbersArray[x] >=0 && numbersArray[x] <=10)
{
countArray[1 -1]++;}
}
}
Instead of using a for-each loop to edit all the values, try to iterate through them using a standard for loop. Here is a shorthand version of what you wrote. Try this:
for (int x = 0; x < numbersArray.length; x++){
countArray[(numbersArray[x]-1)/10]++;
}