# Untitled

unknown
plain_text
20 days ago
43 kB
2
Indexable
Never
EX 1(a) :
Imagine you're a software developer working on a project in a remote village. One day, an
elderly villager approaches you, intrigued by your work. They share stories of their youth,
when converting temperatures required complex calculations. Curious, they ask how your
program, which converts Celsius to Fahrenheit, might have impacted their past.
Input format:
● The user is prompted to enter the temperature in Celsius.
Output format:
● The program calculates the equivalent temperature in Fahrenheit based on the input
Celsius value.
● The result, the temperature in Fahrenheit, is then displayed to the user.
Sample Input:
javac CelsiusToFahrenheit.java
java CelsiusToFahrenheit 31
Expected Output:
Temperature in Fahrenheit: 87.8
Coding:
import java.util.Scanner;
public class CelsiusToFahrenheit {
public static void main(String[] args) {
// Create a Scanner object to read input from the user
Scanner scanner = new Scanner(System.in);
// Prompt the user to enter temperature in Celsius
// Read the temperature in Celsius from the user
double celsius = scanner.nextDouble();
// Convert Celsius to Fahrenheit
double fahrenheit = (celsius * 9/5) + 32;
// Display the result
System.out.println("Temperature in Fahrenheit: " + fahrenheit);
// Close the scanner to prevent resource leak
scanner.close();
}
}
EX 1(b) :
You are developing a BMI calculator for a health app. During the onboarding process, users
are prompted to input their weight and height. Implement a program where users can enter
their weight in kilograms and height in meters. Your program should then compute and
display their Body Mass Index (BMI). This tool helps users track their health and fitness
progress.
Input Format:
● The user is prompted to enter a double represented their weight in kilograms.
● The user is prompted to enter a double represented nput their height in meters.
Output Format:
● The program displays the calculated BMI value in integer.
● The BMI value is shown with an appropriate message, such as "Your BMI is: [BMI
value]".
Sample Input:
javac BMICalculator t.java
java BMICalculator 70 1.75
Expected Output:
Coding:
import java.util.Scanner;
public class BMICalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Prompt user to input weight in kilograms
double weight = scanner.nextDouble();
// Prompt user to input height in meters
double height = scanner.nextDouble();
// Calculate BMI
double bmi = weight / (height * height);
// Display the BMI
System.out.println("Your BMI is: " + (int)bmi);
scanner.close();
}
EX 1(c) :
A group of friends explores an ancient code-breaking game. Each player inputs a single
character, unveiling hidden messages encoded in ASCII. As they decipher symbols, they
uncover clues to an ancient treasure. Help them by Implement a code to find a ascii value of
a character.
Input Format:
● The program expects the user to input a single character
Output Format:
● After receiving input from the user, the program displays both the entered character
and its corresponding ASCII value.
Sample Input:
javac CharacterToASCII.java
java CharacterToASCII a
Sample Output:
Character: a ASCII value: 97
Coding:
import java.util.Scanner;
public class CharacterToASCII
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a character: ");
char character = scanner.next().charAt(0);
int asciiValue = (int) character;
System.out.println("Character: " + character);
System.out.println("ASCII value: " + asciiValue);
scanner.close();
}
}
EX 1(d) :
You're tasked with developing a Java program for a binary-to-decimal converter tool. The
program expects users to input a binary number as a string. After receiving the input, it
converts the binary number to its decimal equivalent and prints the decimal value as an
integer.
Input Format:
The program expects the user to input a binary number as a string.
Output Format:
After receiving input from the user, the program converts the binary number to its decimal
equivalent and prints the decimal value as an integer
Sample Input:
javac BinaryToDecimal.java
java BinaryToDecimal 1110
Sample Output:
Decimal value: 14
Coding:
import java.util.Scanner;
public class BinaryToDecimal
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
String binaryString = scanner.nextLine();
int decimalValue = Integer.parseInt(binaryString, 2);
System.out.println("Decimal value: " + decimalValue);
scanner.close();
}
}
EX 1(e) :
You're tasked with developing a simple currency converter tool. The program should prompt
users to input an amount in USD and convert it to EUR using a predefined exchange rate.
Upon input, it calculates and displays the converted amount in EUR. This tool facilitates
quick currency conversions, aiding users in international financial transactions and budget
planning.
Input Format:
● The user is prompted to input the amount in USD.
Output Format:
● The program displays the converted amount to EUR. The converted amount is
shown as an integer value
Note: 1 USD = 0.92 Euros
Sample Input:
javac CurrencyConverter.java
java CurrencyConverter 100
Sample Output:
92
Coding:
import java.util.Scanner;
public class CurrencyConverter
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
double usdToEurRate = 0.92;
double amountInUSD = scanner.nextDouble();
double convertedAmount = amountInUSD * usdToEurRate;
System.out.println(" " + (int)convertedAmount);
scanner.close();
} }
Result:
Ex No: 2 Implementation of java programs using decision making statements
Aim:
Algorithm:
EX 2(a) :
You're developing a retail billing system. Develop a program that calculates the total cost of
a purchase after applying discounts. If the purchase is over $1000, apply a 10% discount; between$500 and \$1000, apply 5%; otherwise, no discount. Prompt users for the purchase
amount, then display the total cost after discount.
Input Format:
● Prompts the user to enter the purchase amount.
Output Format:
● Displays the total cost after discount.
Sample Input:
1500
Expected Output:
Total cost after discount: 1350.0
Coding:
import java.util.Scanner;
public class PurchaseCostCalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Prompt the user to enter the purchase amount
double purchaseAmount = scanner.nextDouble();
double totalCost;
// Calculate total cost after applying discount based on purchase amount
if (purchaseAmount > 1000) {
// Apply 10% discount
totalCost = purchaseAmount * 0.9;
} else if (purchaseAmount >= 500 && purchaseAmount <= 1000) {
// Apply 5% discount
totalCost = purchaseAmount * 0.95;
} else {
// No discount
totalCost = purchaseAmount;
}
// Display the total cost after discount
System.out.println("Total cost after discount: " + totalCost);
scanner.close();
} }
EX 2(b) :
You've created a simple program that prompts users to input a number. Once the number is
entered, the program analyzes it to determine if it's positive, negative, or zero. Based on this
analysis, it provides immediate feedback to the user regarding the nature of the number.
Input Format:
● Prompts the user to enter a number.
Output Format:
● Displays whether the entered number is positive or negative.
Sample Input:
5
Expected Output:
The entered number is positive.
Coding:
import java.util.Scanner;
public class NumberClassifier {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
double number = scanner.nextDouble();
// Check if the entered number is positive, negative, or zero
if (number > 0) {
System.out.println("The entered number is positive.");
} else if (number < 0) {
System.out.println("The entered number is negative.");
} else {
System.out.println("The entered number is zero.");
}
scanner.close();
}
}
EX 2(c) :
You're building a geometry tool for analyzing triangles. Design a program that prompts users
to input the lengths of three sides of a triangle, determines if it's equilateral, isosceles, or
scalene using if statements, and displays the result.
Input Format:
● Prompts the user to enter the lengths of three sides.
Output Format:
● Displays the triangle is equilateral or the triangle is isosceles or the triangle is
scalene
Sample Input:
3 3 2
Expected Output:
The triangle is isosceles.
Coding:
import java.util.Scanner;
public class TriangleClassifier
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
double side1 = scanner.nextDouble();
double side2 = scanner.nextDouble();
double side3 = scanner.nextDouble();
if (side1 == side2 && side2 == side3)
{
System.out.println("The triangle is equilateral.");
}
else if (side1 == side2 || side1 == side3 || side2 == side3)
{
System.out.println("The triangle is isosceles.");
}
else
{
System.out.println("The triangle is scalene.");
} scanner.close();
}
}
EX 2(d) :
You're developing a calendar utility to translate numerical representations of weekdays into
their respective names. Design a program prompting users to input a number representing a
day (1 for Monday, 2 for Tuesday, …, 7 for Sunday), and output the corresponding day name
using a switch statement.
Input Format:
● Prompts the user to enter the day number.
Output Format:
● Displays the corresponding day name
Sample Input:
5
Expected Output:
The corresponding day is Friday
Coding:
import java.util.Scanner;
public class DayOfWeekConverter
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
int dayNumber = scanner.nextInt();
String dayName;
switch (dayNumber)
{
case 1:
dayName = "Monday";
break;
case 2:
dayName = "Tuesday";
break;
case 3:
dayName = "Wednesday";
break;
case 4: dayName = "Thursday";
break;
case 5:
dayName = "Friday";
break;
case 6:
dayName = "Saturday";
break;
case 7:
dayName = "Sunday";
break;
default:
dayName = "Invalid day number";
break;
}
System.out.println("The corresponding day is " + dayName);
scanner.close(); } }
Result:
Ex No: 3 Implementation of java programs using Looping statements
Aim:
Algorithm:
EX 3(a) :
Imagine you're a teacher creating a fun learning tool. With your program, generate
multiplication tables from 1 to 10 for each number entered. Every loop iteration reveals a
new set of answers, fostering a deeper understanding of multiplication.
Input Format:
● Prompts the user to enter a number.
Output Format:
● Displays the Multiplication table for the entered number.
Sample Input:
5
Expected Output:
Multiplication table for 5:
5 × 1 = 5
5 × 2 = 10
5 × 3 = 15
5 × 4 = 20
5 × 5 = 25
5 × 6 = 30
5 × 7 = 35
5 × 8 = 40
5 × 9 = 45
5 × 10 = 50
Coding:
import java.util.Scanner;
public class MultiplicationTableGenerator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int number = scanner.nextInt();
System.out.println("Multiplication table for " + number + ":");
// Generate and print the multiplication table from 1 to 10
for (int i = 1; i <= 10; i++) {
System.out.println(number + " × " + i + " = " + (number * i));
}
scanner.close();
}
}
EX 3(b) :
Imagine you're a mathematical consultant assisting clients with number inquiries. A user
enters a positive integer, seeking its factors. Implement a program to help the user to find the
factors the numbers.
Input Format:
● Prompts the user to enter a positive integer.
Output Format:
● Display the Factors of the entered number.
Sample Input :
10
Expected Output :
Factors of 10: 1 2 5 10
Coding:
import java.util.Scanner;
public class FactorFinder {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int number = scanner.nextInt();
// Validate the input
if (number <= 0) {
System.out.println("Error: Please enter a positive integer.");
return;
}
// Initialize variables
int divisor = 1;
// Print the factors of the number
System.out.print("Factors of " + number + ": ");
while (divisor <= number) {
if (number % divisor == 0) {
System.out.print(divisor + " ");
}
divisor++;
}
scanner.close();
}
}
EX 3(c) :
In a school competition, students are participating in a relay race. The race organizer needs
to arrange batons for each team. They have batons in sets, where each set contains a
certain number of batons. However, they need to find out the minimum number of sets
required to distribute an equal number of batons to each team. Implement a program to help
the race organizer find the minimum number of sets required to distribute batons equally
among all teams. Assume that each team requires the same number of batons, and the
number of batons in each set and the number of teams are provided as inputs
Input Format:
● The input format consists of two integers separated by a space, representing the
number of batons in each set (num1) and the number of teams (num2).
Output Format:
● The output format consists of a single integer representing the minimum number of
sets required to distribute batons equally among all teams.
Sample Input :
60 96
Expected Output :
480
Coding:
import java.util.Scanner;
public class LCMCalculator
{
public static int findLCM(int num1, int num2)
{
int lcm = (num1 > num2) ? num1 : num2;
while (true)
{
if (lcm % num1 == 0 && lcm % num2 == 0)
{
return lcm;
} lcm++;
}
}
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
int num1 = scanner.nextInt();
int num2 = scanner.nextInt();
int lcm = findLCM(num1, num2);
System.out.println(+ lcm);
scanner.close();
}
}
EX 3(d) :
You're tasked with developing a tool that computes squares of numbers within specified
limits. Imagine you're embarking on a journey through the realm of numbers, exploring their
squares. Implement a program using a do-while loop to iterate through these numbers,
uncovering their squares along the way.
Input Format:
● The program prompts the user to enter a positive integer representing the limit up to
which squares are to be printed.
Output Format:
● The program prints the squares of numbers from 1 up to the entered limit.
Sample Input :
5
Expected Output :
Squares of numbers from 1 to 5: 1 4 9 16 25
Coding:
import java.util.Scanner;
public class SquaresPrinter
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
// Prompt the user to enter the limit
// System.out.print("Enter the limit: ");
int limit = scanner.nextInt();
// Validate the input
if (limit <= 0)
{
System.out.println("Error: Please enter a positive integer as the return;
}
// Initialize variables
int number = 1;
System.out.print("Squares of numbers from 1 to " + limit + ": ");
// Calculate and print the squares using a do-while loop
do {
int square = number * number;
System.out.print(square + " ");
number++;
} while (number <= limit);
scanner.close();
}
}
Result:
Ex No: 4 Implementation of java programs using Jump statements
Aim:
Algorithm:
EX 4(a) :
Imagine you're a curious explorer delving into the world of prime numbers. Envision seekers
inputting their chosen numbers eagerly. Implement a program to traverse through each
number's factors up to its square root, determining its primality. Each iteration brings you
closer to unraveling the mysteries of prime numbers.
Input Format:
● Prompts the user to enter a positive integer.
Output Format:
● Displays the number is a prime number or not.
Sample Input:
5
Expected Output:
5 is a prime number.
CODE:
import java.util.Scanner;
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int number = scanner.nextInt();
// Validate the input
if (number <= 1) {
System.out.println("Error: Please enter a positive integer greater than 1.");
return;
}
boolean isPrime = true;
// Check divisibility of the number by all integers up to its square root
for (int i = 2; i * i <= number; i++) {
if (number % i == 0) {
isPrime = false;
break;
}
}
// Print whether the number is prime or not
if (isPrime) {
System.out.println(number + " is a prime number.");
} else {
System.out.println(number + " is not a prime number.");
}
scanner.close();
}
}
EX 4(b) :
Imagine you're a software developer creating a tool for numerical transformations. A user,
fascinated by number manipulation, inputs a positive integer. Implement a program to
gracefully reverse the digits of their number using a while loop, providing them with the
mirror image of their input for exploration
Input Format:
● Prompts the user to enter a positive integer.
Output Format:
● Displays the reversed number.
Sample Input:
123
Expected Output:
Reversed number: 321
Coding:
import java.util.Scanner;
public class NumberReverser {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int number = scanner.nextInt();
// Validate the input
if (number <= 0) {
System.out.println("Error: Please enter a positive integer.");
return;
}
// Initialize variables
int reversedNumber = 0;
int remainder;
// Reverse the number
while (number > 0) {
remainder = number % 10;
reversedNumber = reversedNumber * 10 + remainder;
number /= 10;
}
// Print the reversed number
System.out.println("Reversed number: " + reversedNumber);
scanner.close();
}
}
Result:
Ex No: 5 Implementation of 1D Array
Aim:
Algorithm:
EX 5(a) :
Imagine you're developing software for a weather monitoring station. You're tasked with
creating a program to analyze temperature data stored in an array of doubles. Your goal is to
determine the maximum temperature recorded and its corresponding time index.
Input Format:
● Prompts the user to input the array of doubles representing temperature readings.
Output Format:
● The output consists of two lines:
● The maximum temperature recorded.
● The index of the maximum temperature in the array.
Sample Input:
5
25.5
30.0
28.3
29.7
27.8
Expected Output:
Maximum Temperature: 30.0
Index of Maximum Temperature: 1
Coding:
import java.util.Scanner;
public class MaxTemperature {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int size = scanner.nextInt();
// Create an array of doubles with the specified size
double[] temperatures = new double[size];
for (int i = 0; i < size; i++) {
temperatures[i] = scanner.nextDouble();
}
scanner.close();
// Find the maximum temperature and its index
double maxTemperature = temperatures[0];
int maxIndex = 0;
for (int i = 1; i < size; i++) {
if (temperatures[i] > maxTemperature) {
maxTemperature = temperatures[i];
maxIndex = i;
}
}
// Print the maximum temperature and its index
System.out.println("Maximum Temperature: " + maxTemperature);
System.out.println("Index of Maximum Temperature: " + maxIndex);
}
}
EX 5(b) :
You're developing software for a temperature monitoring system. Your task is to create a
program that analyzes temperature data stored in an array of integers. The program finds
the highest recorded temperature, along with its index.
Input Format:
● The input consists of two lines:
● The first line contains a single integer 'n' representing the size of the array.
● The second line contains 'n' integers separated by spaces representing the elements
of the array.
Output Format:
● The output consists of two lines:
● The maximum element in the array.
● The index of the maximum element in the array.
Sample Input:
5
10 20 30 40 50
Expected Output:
Maximum Element: 50
Index of Maximum Element: 4
Coding:
import java.util.Scanner;
public class MaxElementFinder {
public static void main(String[] args) {
// Create a Scanner object to read input from the user
Scanner scanner = new Scanner(System.in);
int size = scanner.nextInt();
// Create an array of integers with the specified size
int[] array = new int[size];
for (int i = 0; i < size; i++) {
array[i] = scanner.nextInt();
}
scanner.close();
// Find the maximum element and its index
int maxElement = array[0];
int maxIndex = 0;
for (int i = 1; i < size; i++) {
if (array[i] > maxElement) {
maxElement = array[i];
maxIndex = i;
}
}
// Print the maximum element and its index
System.out.println("Maximum Element: " + maxElement);
System.out.println("Index of Maximum Element: " + maxIndex);
}
}
EX 5(c) :
Suppose you are building a leaderboard for a gaming competition. You need to determine
the player who achieved the second-highest score. Develop a program to find the
second-highest score from an array of player scores. Ensure that your program handles
scenarios where there might be ties for the highest score and ensures that the
second-highest score is accurately identified. Test your program with various test cases to
verify its correctness.
Input Format:
● The first line of input contains an integer N representing the number of players.
● The second line contains N integers separated by spaces, representing the scores of
each player.
Output Format:
● The output format consists of a single integer representing the second-highest score
achieved by a player in the competition
Sample Input:
6 6 -5 -10 -3 -8 -2
Expected Output:
-2
Coding:
import java.util.Scanner;
public class SecondLargestInArray
{
public static int findSecondLargest(int[] arr)
{
int max = Integer.MIN_VALUE;
int secondMax = Integer.MIN_VALUE;
for (int num : arr) { if (num > max)
{
secondMax = max; max = num;
}
else if (num > secondMax && num != max)
{ secondMax = num;
}
}
return secondMax;
}
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt(); int[] arr = new int[n];
for (int i = 0; i < n; i++)
{
arr[i] = scanner.nextInt();
}
int secondLargest = findSecondLargest(arr);
System.out.println(+ secondLargest);
scanner.close();
}
}
Result:
Ex No: 6 Implementation of 2D Array
Aim:
Algorithm:
EX 6(a) :
You're developing software for a financial analytics tool. Your task is to design a program to
process a dataset stored in a 2D array of integers. The program calculates the total value of
all entries in the dataset and prints the result.
Input Format:
● The input consists of multiple lines, each containing integers separated by spaces
representing the rows of the 2D array.
Output Format:
● The output consists of a single line containing a single integer representing the sum
of all elements in the 2D array.
Sample Input:
1 2 3
4 5 6
7 8 9
Expected Output:
Sum of all elements in the 2D array: 45
Coding:
import java.util.Scanner;
public class TwoDArraySum {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int sum = 0;
int rowCount = 0;
while (scanner.hasNextLine()) {
String line = scanner.nextLine().trim();
if (line.isEmpty()) {
break;
}
String[] elements = line.split(" "); // Split the line into individual elements
// Update row count
rowCount++;
// Sum the elements in the current row
for (String element : elements) {
sum += Integer.parseInt(element);
}
}
scanner.close();
// Print the sum of all elements in the 2D array
System.out.println("Sum of all elements in the 2D array: " + sum);
}
}
EX 6(b) :
You're developing a data analysis tool for financial data. Your task is to develop a program to
process a dataset stored in a 2D array of doubles. The program identifies the highest value
in the dataset, along with its corresponding row and column indices.
Input Format:
● The input consists of multiple lines, each containing doubles separated by spaces
representing the rows of the 2D array.
Output Format:
The output consists of three lines:
● The first line contains the maximum element found in the 2D array.
● The second line contains the row index of the maximum element.
● The third line contains the column index of the maximum element.
Sample Input:
3
3
1.1 2.2 3.3
4.4 5.5 6.6
7.7 8.8 9.9
Expected Output:
Maximum Element: 9.9
Row Index of Maximum Element: 2
Column Index of Maximum Element: 2
Coding:
import java.util.Scanner;
public class MaxElement2DArray {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int rows = scanner.nextInt();
int columns = scanner.nextInt();
// Create a 2D array of doubles
double[][] array = new double[rows][columns];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
array[i][j] = scanner.nextDouble();
}
}
scanner.close();
// Find the maximum element and its indices
double maxElement = array[0][0];
int maxRowIndex = 0;
int maxColumnIndex = 0;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
if (array[i][j] > maxElement) {
maxElement = array[i][j];
maxRowIndex = i;
maxColumnIndex = j;
}
}
}
// Print the maximum element and its indices
System.out.println("Maximum Element: " + maxElement);
System.out.println("Row Index of Maximum Element: " + maxRowIndex);
System.out.println("Column Index of Maximum Element: " + maxColumnIndex);
}
}
EX 6(c) :
You're developing software for a scientific data analysis tool. Your task is to design a
program to process matrices. The program initializes a 2D array representing a matrix and
computes its transpose, providing both the original and transposed matrices for further
analysis.
Input Format:
● The input consists of multiple lines, each containing integers separated by spaces
representing the rows of the matrix.
Output Format:
● The output consists of two parts: The original matrix, with rows separated by
newlines and elements separated by spaces. The transposed matrix, with rows
separated by newlines and elements separated by spaces.
Sample Input:
2 2
1 2
3 4
Expected Output:
Original Matrix:
1 2
3 4
Transposed Matrix:
1 3
2 4
Coding:
import java.util.Scanner;
public class MatrixTranspose
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
int rows = scanner.nextInt();
int columns = scanner.nextInt();
int[][] matrix = new int[rows][columns];
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < columns; j++)
{
matrix[i][j] = scanner.nextInt();
}
}
scanner.close();
System.out.println("Original Matrix:");
printMatrix(matrix);
int[][] transposedMatrix = transposeMatrix(matrix);
System.out.println("Transposed Matrix:");
printMatrix(transposedMatrix); }
private static void printMatrix(int[][] matrix)
{
for (int[] row : matrix)
{
for (int element : row)
{
System.out.print(element + " ");
} System.out.println();
}
}
private static int[][] transposeMatrix(int[][] matrix)
{
int rows = matrix.length;
int columns = matrix[0].length;
int[][] transposedMatrix = new int[columns][rows];
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < columns; j++)
{
transposedMatrix[j][i] = matrix[i][j];
}
} return transposedMatrix;
}
}
Result:
Ex No: 7 Implementation of String functions
Aim:
Algorithm:
EX 7(a) :
As a linguistic data analyst, you're developing a Text Refinement Tool to process text inputs.
Users expect the tool to remove duplicate characters and count occurrences of vowels for
linguistic analysis. The tool accepts a string as input and redefines it, presenting the refined
text without duplicate characters and providing counts of vowels. Design a program that
meets these requirements efficiently.
Input Format:
● A single line containing a string entered by the user.
Output Format:
● The output consists of the refined text without duplicate characters.
● If any vowels are present, print the counts of each vowel (a, e, i, o, u).
● If no vowels are found, indicate "No vowels found."
Constraints:
● Implement the solution with optimal time and space complexity.
● Ensure accurate removal of duplicate characters and counting of vowels.
● Handle cases with mixed uppercase and lowercase characters appropriately.
Sample Input:
aeiouu
Expected Output:
aeiou
a1
e1
i1
o1
u2
Coding:
import java.util.Scanner;
public class TextRefinementTool {
public static String refineText(String input) {
StringBuilder refinedText = new StringBuilder();
int[] vowelCount = new int[26]; // Array to store counts of vowels (a to z)
for (char c : input.toCharArray()) {
if (!Character.isWhitespace(c)) { // Ignore whitespace characters
char lowercaseChar = Character.toLowerCase(c);
if (lowercaseChar >= 'a' && lowercaseChar <= 'z') {
vowelCount[lowercaseChar - 'a']++; // Increment corresponding vowel count
}
if (refinedText.indexOf(String.valueOf(c)) == -1) {
refinedText.append(c); // Append non-duplicate characters
}
}
}
StringBuilder output = new StringBuilder().append(refinedText);
// Append vowel counts if any
boolean hasVowels = false;
for (int i = 0; i < vowelCount.length; i++) {
char vowel = (char) ('a' + i);
if (vowelCount[i] > 0 && (vowel == 'a' || vowel == 'e' || vowel == 'i' || vowel == 'o' ||
vowel == 'u')) {
output.append("\n").append(vowel).append("").append(vowelCount[i]);
hasVowels = true;
}
}
if (!hasVowels) {
output.append("\nNo vowels found.");
}
return output.toString();
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
//System.out.print("Enter a string: ");
String input = scanner.nextLine();
String refinedOutput = refineText(input);
System.out.println(refinedOutput);
scanner.close();
}
}
EX 7(b) :
You are tasked with enhancing a popular text-editing app with a new feature to stylize text for
a more captivating presentation. With the app's extensive user base, efficiency and
performance are critical considerations. Users desire a feature that reverses the word order
of their input sentence while alternating the case of each letter, starting with uppercase for a
visually engaging effect.
Input Format:
● A single line containing the input string s.
Output Format:
● A single line containing the transformed string.
Constraints:
● The input string s consists of alphabetic characters and spaces only.
● The length of s is at most 10^5 characters.
● The app must process user input efficiently to accommodate high usage volumes.
● The transformation should alternate the case of each letter, beginning with an
uppercase letter for readability and style.
● The app should reverse the order of words in the input sentence to provide a
dynamic and engaging presentation.
Sample Input:
hello world
Expected Output:
WORLD HELLO
Coding:
import java.util.Scanner;
public class TextTransformer {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
scanner.close();
System.out.println(transformText(input));
}
public static String transformText(String input) {
String[] words = input.split(" ");
StringBuilder transformed = new StringBuilder();
boolean isUpper = true;
for (int i = words.length - 1; i >= 0; i--) {
char[] chars = words[i].toCharArray();
for (char c : chars) {
if (Character.isUpperCase(c)) {
transformed.append(Character.toLowerCase(c));
} else if (Character.isLowerCase(c)) {
transformed.append(Character.toUpperCase(c));
} else {
transformed.append(c); // Maintain non-alphabetic characters as is
}
}
if (i > 0) {
transformed.append(" ");
}
}
return transformed.toString();
} }
EX 7(c) :
You're developing a tool that reverse a given string S, such that the reversed string does not
contain any repeated characters or spaces. The program should eliminate any duplicate
characters and spaces while reversing the string.
Input Format:
The first line of input contains a single string S.
Output Format:
Print the modified string after reversing S without any repeated characters or spaces. If user
enterd only alphapets if not then print "Invalid input".
Sample Input:
hello world
Expected Output:
dlroWeH
Coding:
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
// Processing the input String output = reverseString(input);
// Displaying the output System.out.println(output); scanner.close();
}
public static String reverseString(String S)
{
if (!S.matches("[A-Za-z ]*"))
{
return "Invalid input";
}
StringBuilder result = new StringBuilder();
for (int i = S.length() - 1; i >= 0; i--)
{
char ch = S.charAt(i);
if (ch != ' ' && result.indexOf(String.valueOf(ch)) == -1)
{ result.append(ch); } } return result.toString();
}
}
Result:
Ex No: 8 Implementation of java program using Streams
Aim:
Algorithm:
EX 8(a) :
You are working as a software developer for a company that processes text documents.
Your team is tasked with developing a tool that analyzes text files to gather specific statistics.
The tool should be able to read a text file named input.txt, calculate the number of
characters, words, and lines in the file, and display these statistics to the user.
Project Description:
As part of the development team, you are tasked with a program that reads a text file
(input.txt) and counts the number of characters, words, and lines in the file. Display these
counts as output.
● Create a text file named input.txt with some content.
● Read the content of input.txt using Java I/O.
● Count the number of characters (including spaces and special characters), words
(separated by spaces), and lines in the file.
● Display the counts as output using java
Sample Input:
Hello, this is a sample text file.
It contains multiple lines with words and characters.
Let's analyze this text using Java.
Expected Output:
Character count: 94
Word count: 18
Line count: 3
Coding:
import java.io.IOException;
public class TextFileAnalyzer {
public static void main(String[] args) {
String fileName = "input.txt";
int charCount = 0;
int wordCount = 0;
int lineCount = 0;
String line;
while ((line = br.readLine()) != null) {
lineCount++;
String[] words = line.split("\\s+");
wordCount += words.length;
for (String word : words) {
charCount += word.length();
}
}
} catch (IOException e) {
System.err.println("Error reading the file: " + e.getMessage());
return;
}
System.out.println("Character count: " + charCount);
System.out.println("Word count: " + wordCount);
System.out.println("Line count: " + lineCount);
}
}
EX 8(b) :
Assume that you are tasked with a program that prompts the user to enter a file name. The
program should then check if the file exists in the current directory. If the file exists, it should
display a message saying "File found!" along with the absolute path of the file. If the file does
● Prompt the user to enter a file name.
● Check if the specified file exists in the current directory.
● If the file exists, display a message "File found!" along with the absolute path of the
file.
● If the file does not exist, display a message "File not found!".
Sample Input:
Enter the file name:
sample.txt
Expected Output:
File found!
Absolute path: C:\path\to\your\directory\sample.txt
Coding:
import java.io.File;
import java.util.Scanner;
public class FileExistenceChecker {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Prompt the user to enter a file name
System.out.println("Enter the file name:");
String fileName = scanner.nextLine();
// Create a File object with the specified file name
File file = new File(fileName);
// Check if the file exists in the current directory
if (file.exists()) {
// File found
System.out.println("File found!");
System.out.println("Absolute path: " + file.getAbsolutePath());
} else {
}
scanner.close();
}
}
Result:
Ex No: 9 Implementation of java program using Date and Number classes
Aim:
Algorithm:
EX 9(a) :
Imagine you're developing a utility to determine users' current ages for a registration
platform. Develop a program that prompts users to input their birth year.
Input Format:
● Users prompt to enter their birth year as an integer.
Output Format:
● The program displays the user's current age as an integer.
● If the input contains negative value, the program displays "Invalid input. Birth year
cannot be negative".
Sample Input:
1998
Expected Output:
26
Coding:
import java.util.Scanner;
import java.time.LocalDate;
public class AgeCalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Initialize birth year variable
int birthYear = 0;
// Prompt the user to enter their birth year until a valid input is provided
while (true) {
// System.out.print("Enter your birth year: ");
// Check if the input is an integer
if (scanner.hasNextInt()) {
birthYear = scanner.nextInt();
// Check if the birth year is not negative
if (birthYear >= 0) {
break; // Exit the loop if valid input is provided
} else {
System.out.println("Invalid input. Birth year cannot be negative.");
}
} else {
// Consume the invalid input
scanner.next();
System.out.println("Invalid input. Please enter a valid year.");
}
}
// Get the current year
int currentYear = LocalDate.now().getYear();
// Calculate the user's current age
int age = currentYear - birthYear;
// Print the calculated age
System.out.println(+ age);
// Close the Scanner object
scanner.close();
}}
EX 9(b) :
In a financial application, Your task is to implement a function to round transaction amounts
to the nearest integer to ensure accurate representation of monetary values in reports and
accounting records.
Input Format:
● A floating-point number representing the value to be rounded to the nearest integer.
Output Format:
● An integer representing the rounded value of the input floating-point number.
Sample Input:
5.7
Expected Output:
Rounded number: 6
Coding:
import java.util.Scanner;
public class NearestIntegerRounder {
public static int roundToNearestInteger(double number) {
return (int) Math.round(number);
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
double inputNumber = scanner.nextDouble();
int roundedNumber = roundToNearestInteger(inputNumber);
// Display the rounded number
System.out.println("Rounded number: " + roundedNumber);
scanner.close();
}
}
Result:
Ex No: 10 Implementation of simple java program using Tokenizing
Aim:
Algorithm:
EX 10(a) :
Imagine you are developing a text analysis tool for a language teacher. The tool aims to help
teachers identify specific writing patterns in their students' essays. One of the patterns they
want to analyze is the frequent use of short words starting with 'a' or 'A'.
● Tokenize the sentence into words.
● Use pattern matching to locate words that start with 'a' or 'A' and have exactly three
characters.
● Print the located words as output.
Sample Input:
Enter a sentence: Apple and ant are animals.
Expected Output:
Short words starting with 'a' or 'A' and having exactly three characters:
and
are
Coding:
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ShortWordsAnalyzer {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a sentence: ");
String sentence = scanner.nextLine();
// Tokenize the sentence into words
String[] words = sentence.split("\\s+");
// Use pattern matching to locate words that start with 'a' or 'A' and have exactly three
characters
Pattern pattern = Pattern.compile("\\b[aA]\\w{2}\\b");
System.out.println("Short words starting with 'a' or 'A' and having exactly three
characters:");
for (String word : words) {
Matcher matcher = pattern.matcher(word);
if (matcher.matches()) {
System.out.println(word);
}
}
scanner.close();
}
}
EX 10(b) :
Develop application called "DataFinder" that reads a text document and locates specific data
patterns using tokenizing and pattern matching techniques. The application should prompt
the user to enter a file path for the text document and specify the data pattern to search for.
Upon finding matches, the program should format and display the located data.
● Prompt the user to enter the file path of the text document and the data pattern to
search for.
● Read the content of the text document and tokenize it into words or lines.
● Use pattern matching to locate instances of the specified data pattern within the
tokenized content.
● Format and display the located data, showing each match in a clear and organized
manner.
Sample Input:
Enter the file path of the text document: input.txt
Enter the data pattern to search for: \\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Z|a-z]{2,}\\b
Expected Output:
Match found: john@example.com
Match found: alice@example.com
Coding:
import java.io.IOException;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class DataFinder {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the file path of the text document: ");
String filePath = scanner.nextLine();
// Prompt the user to enter the data pattern to search for
System.out.print("Enter the data pattern to search for: ");
String dataPattern = scanner.nextLine();
// Read the content of the text document and tokenize it
String line;
// Use pattern matching to locate instances of the specified data pattern within the
tokenized content
Pattern pattern = Pattern.compile(dataPattern);
Matcher matcher = pattern.matcher(line);
while (matcher.find()) {
// Format and display the located data
System.out.println("Match found: " + matcher.group());
}
}
} catch (IOException e) {
System.out.println("Error reading the file: " + e.getMessage());
}
scanner.close();
}
}
Result