Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
5 views

Programming Assignment Unit 1

Uploaded by

Tornado Fair
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Programming Assignment Unit 1

Uploaded by

Tornado Fair
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 12

1.

CS 1103-01 - AY2025-T2
2. Programming Assignment Unit 1

Programming Assignment Unit 1


Completion requirements
To do: Make a submission
Opened: Thursday, 14 November 2024, 12:05 AM
Due: Thursday, 21 November 2024, 11:55 PM

Assignment Instructions

This assignment aims to assess your skills/knowledge on basics of String


creation and various string handling functions. This is a scenario based practical
assignment to create a text analysis tool, providing students with a hands-on
opportunity to apply their programming skills in a real-world context. The
assignment focuses on developing a program that performs various operations
on text input, enhancing students' skills in handling strings, data analysis, and
user interaction.

Scenario: You have been asked to create a text analysis tool that will perform
various operations on a given text input. This tool will help users gain insights
into the text data by performing character and word analysis.

Assignment Tasks:

1. User Input: Ask the user to input a paragraph or a lengthy text. Your
program should read and store this input.

2. Character Count: Calculate and display the total number of characters


in the input text.

3. Word Count: Calculate and display the total number of words in the
input text. Assume that words are separated by spaces.
4. Most Common Character: Find and display the most common
character in the text. In case of a tie, select any of the tied characters.

5. Character Frequency: Ask the user to input a character. Check and


display the frequency of occurrences of this character in the text. Be
case-insensitive (e.g., 'a' and 'A' should be considered the same
character).

6. Word Frequency: Ask the user to input a word. Check and display the
frequency of occurrences of this word in the text. Be case-insensitive.

7. Unique Words: Calculate and display the number of unique words in


the text (case-insensitive).

Submission Instructions

 Read the rubric on how you are going to be graded before you start to
work on this assignment.

 Remember to use appropriate variable names and follow best practices of


coding. Please provide a screenshot of the outputs. Submit the
assignment in MS Word or PDF file.

You will be assessed based on the following criteria:

1. Compilation – The code runs without any errors.


2. Input Validation – This ensures that the user's input meets certain
criteria or constraints before it is processed further.

3. Logic and Computation - This handles the core functionality and


processing of the questions.

4. Program flow and structure - It encompasses the overall structure and


behavior of the program.

5. Submission of code and screenshots of the output.

6. Code style and readability - Refers to the way the code is written,
organized, and presented. It focuses on making the code clear, easy to
understand, and maintainable.

This assignment will be assessed by your instructor using the rubric


below.

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
import java.util.TreeSet;

public class TextAnalyzer {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter a paragraph or lengthy text: ");


String text = scanner.nextLine();

// Character Count
int charCount = text.length();
System.out.println("Total characters: " + charCount);

// Word Count
String[] words = text.split("\\s+");
int wordCount = words.length;
System.out.println("Total words: " + wordCount);

// Most Common Character


Map<Character, Integer> charFreq = new HashMap<>();
for (char c : text.toCharArray()) {
charFreq.put(c, charFreq.getOrDefault(c, 0) + 1);
}
char mostCommonChar = ' ';
int maxFreq = 0;
for (Map.Entry<Character, Integer> entry : charFreq.entrySet()) {
if (entry.getValue() > maxFreq) {
maxFreq = entry.getValue();
mostCommonChar = entry.getKey();
}
}
System.out.println("Most common character: " + mostCommonChar);
// Character Frequency
System.out.print("Enter a character to find itas frequency: ");
char charToFind = scanner.next().charAt(0);
int charFreq2 = 0;
for (char c : text.toLowerCase().toCharArray()) {
if (c == Character.toLowerCase(charToFind)) {
charFreq2++;
}
}
System.out.println("Frequency of '" + charToFind + "': " + charFreq2);

// Word Frequency
System.out.print("Enter a word to find its frequency: ");
String wordToFind = scanner.next().toLowerCase();
int wordFreq = 0;
for (String word : words) {
if (word.equalsIgnoreCase(wordToFind)) {
wordFreq++;
}
}
System.out.println("Frequency of '" + wordToFind + "': " + wordFreq);

// Unique Words
Set<String> uniqueWords = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
for (String word : words) {
uniqueWords.add(word);
}
System.out.println("Number of unique words: " + uniqueWords.size());

scanner.close();
}
}
--------------------------------------------------------------

Hey there! Alaa here, ready to explain this awesome text analyzer code we have in front of us.
This code is like a detective for your text, finding out all sorts of interesting things about it. Let's
break it down step by step, shall we?

1. Getting Ready:

First things first, we need some tools to work with. We import a bunch of helpful things from
java.util. Think of them like a toolbox with a scanner (to read what you type), maps (to store
information), and sets (like a collection without duplicates). We also define a class called
TextAnalyzer - that's like our workspace for this detective work.

2. Let's Hear It!

Now, comes the fun part! We use the scanner to ask you for some text. It can be a paragraph, a
story, or even a song lyric - anything you want to analyze. We store this text in a variable called
text.

3. Counting Characters:

Time to put on our detective hat! First, we want to know the total number of characters in the
text. We use the handy length() method on the text variable. It's like counting each letter,
space, and punctuation mark. We then print this number out, letting you know how long the text
is.

4. How Many Words?

Next up, we want to see how many words are hiding in that text. We use a method called
split() on the text variable. This method acts like a pair of scissors, cutting the text into
separate words based on spaces. We store these words in an array called words. Then, we use the
magic of length() again, but this time on the words array, to see how many elements (words) it
has. This tells us the total number of words in the text. We print that out too!

5. Unveiling the Most Common Character:


Now, things get a little more detective-y! We want to find the character that appears the most in
the text. Imagine the character is a suspect, and we want to see which one shows up the most
often at the crime scene (the text). Here's where it gets interesting:

 We create a Map called charFreq. Maps are like fancy notebooks where we can keep
track of things. In this case, we'll use the characters as keys and a number (their
frequency) as values.
 We loop through each character in the text (using toCharArray() to convert it into
individual characters). For each character, we check if it's already in our charFreq map.
If it is, we add 1 to its existing frequency (like marking another appearance in our
detective notes). If it's a new character, we add it to the map with a frequency of 1 (its
first appearance).
 After looping through all characters, we find the champion - the most frequent character!
We loop through the charFreq map again, comparing frequencies. If a character's
frequency is higher than the current champion, we update the champion and its
frequency. Finally, we print out the most common character, along with its frequency.

6. Find a Specific Character:

Now, suppose you have a hunch about a particular character. Maybe you noticed a lot of "e"s
while reading the text? We can use our detective skills to find the exact frequency of any
character you want!

 We ask you to enter a character using the scanner.


 We convert the entered character to lowercase (because uppercase and lowercase
versions are considered the same for this investigation).
 We loop through each character in the lowercase version of the text. If the current
character matches the one you entered, we increase a counter variable charFreq2.
 Finally, we print out the frequency of the character you entered.

7. Word Frequency Investigation:

Similar to finding a specific character, we can also investigate the frequency of a specific word
in the text.

 We ask you to enter a word using the scanner.


 We convert the entered word to lowercase (again, case doesn't matter here).
 We loop through each word in the words array. If the current word (ignoring case)
matches the one you entered, we increase a counter variable wordFreq.
 Finally, we print out the frequency of the word you entered.

8. Unveiling the Unique Words:


Imagine a list of suspects, but some might be twins or triplets! Here, we want to find the number
of unique words in the text, excluding any duplicates. We can use a Set for this, which is like a
special list that doesn't allow duplicates.
 We create a Set called uniqueWords that automatically removes duplicates.
 We loop through each word in the words array and add each word to the uniqueWords
set.
 Finally, we print the size of the uniqueWords set, which tells us the number of unique
words in the text.
Wrapping Up:
And there you have it! Our text analyzer is now complete. It can count characters, words, find
the most common character, and even help you find specific characters or words and their
frequencies. It's like a little detective, uncovering the secrets hidden within your text.
Conclusion
This Python code effectively analyzes a given text, providing valuable insights into its content.
By calculating character and word counts, identifying the most frequent character, and
determining the frequency of specific characters and words, the code offers a comprehensive text
analysis tool.
The code's clear structure and concise functions make it easy to understand and adapt for various
text analysis tasks. It demonstrates the power of Python's string manipulation capabilities and
data structures to extract meaningful information from textual data.

I hope this explanation is clear and helpful! Let me know if you have any other questions.
References and sources
1- bronze badges. (1959b, December 1). Java - string input exception handling.
Stack Overflow. https://stackoverflow.com/questions/26279208/java-string-input-
exception-handling

2- YouTube. (2023, February 20). exception handling. YouTube.


https://www.youtube.com/watch?v=PHzm_Iox1mE
3- Awan, A. A. (2023, February 24). Exception & Error Handling : Tutorial by
datacamp. DataCamp. https://www.datacamp.com/tutorial/exception-handling-
python

You might also like