0% found this document useful (0 votes)
45 views19 pages

Week 6 - Level 2 - 10 (Step) Rithish S

The document contains a series of Java programming exercises aimed at practicing various concepts such as calculating BMI, finding unique characters in a string, identifying non-repeating characters, and checking for palindromes and anagrams. Each exercise includes a description, code implementation, and example outputs. The exercises are designed to enhance understanding of string manipulation, array handling, and basic algorithms in Java.

Uploaded by

santypravin3
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
45 views19 pages

Week 6 - Level 2 - 10 (Step) Rithish S

The document contains a series of Java programming exercises aimed at practicing various concepts such as calculating BMI, finding unique characters in a string, identifying non-repeating characters, and checking for palindromes and anagrams. Each exercise includes a description, code implementation, and example outputs. The exercises are designed to enhance understanding of string manipulation, array handling, and basic algorithms in Java.

Uploaded by

santypravin3
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 19

Name: RITHISH S

Regno:RA2411003012057
Sec:L2

Week 6 - Level 2 - 10 Practice Problems

1. An organization took up the exercise to find the Body Mass Index (BMI) of all the per-
sons in a team of 10 members. For this create a program to find the BMI and display
the height, weight, BMI, and status of each individual.

import java.util.Scanner;

public class BMICalculator {

public static String[][] calculateBMIAndStatus(double[][] data) {


String[][] result = new String[10][4];
for (int i = 0; i < 10; i++) {
double weight = data[i][0];
double heightCm = data[i][1];
double heightM = heightCm / 100.0;
double bmi = weight / (heightM * heightM);
String status;
if (bmi <= 18.4) {
status = "Underweight";
} else if (bmi <= 24.9) {
status = "Normal";
} else if (bmi <= 39.9) {
status = "Overweight";
} else {
status = "Obese";
}
result[i][0] = String.format("%.2f", heightCm);
result[i][1] = String.format("%.2f", weight);
result[i][2] = String.format("%.2f", bmi);
result[i][3] = status;
}
return result;
}

public static String[][] processData(double[][] hwData) {


return calculateBMIAndStatus(hwData);
}

public static void displayData(String[][] result) {


System.out.printf("%-10s %-10s %-10s %-15s\n", "Height(cm)", "Weight(kg)", "BMI", "Status");
for (int i = 0; i < 10; i++) {
System.out.printf("%-10s %-10s %-10s %-15s\n", result[i][0], result[i][1], result[i][2], result[i][3]);
}
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
double[][] hwData = new double[10][2];

for (int i = 0; i < 10; i++) {


System.out.println("Enter weight (kg) for person " + (i + 1) + ":");
hwData[i][0] = scanner.nextDouble();
System.out.println("Enter height (cm) for person " + (i + 1) + ":");
hwData[i][1] = scanner.nextDouble();
}
String[][] result = processData(hwData);
displayData(result);
scanner.close();
}
}
Output:
Height(cm) Weight(kg) BMI Status
150.00 45.00 20.00 Normal
165.00 60.00 22.04 Normal
170.00 75.00 25.95 Overweight
160.00 90.00 35.16 Overweight
175.00 100.00 32.65 Overweight
160.00 50.00 19.53 Normal
165.00 68.00 24.98 Normal
180.00 85.00 26.23 Overweight
170.00 95.00 32.87 Overweight
175.00 120.00 39.18 Overweight.

2. Find unique characters in a string using the charAt() method and display the result.
import java.util.Scanner;

public class UniqueCharactersFinder {

public static int getTextLength(String text) {


int length = 0;
try {
while (true) {
text.charAt(length);
length++;
}
} catch (IndexOutOfBoundsException e) {
}
return length;
}

public static char[] findUniqueCharacters(String text) {


int len = getTextLength(text);
char[] uniqueChars = new char[len];
int uniqueCount = 0;

for (int i = 0; i < len; i++) {


char current = text.charAt(i);
boolean isUnique = true;

for (int j = 0; j < i; j++) {


if (text.charAt(j) == current) {
isUnique = false;
break;
}
}

if (isUnique) {
uniqueChars[uniqueCount] = current;
uniqueCount++;
}
}

char[] result = new char[uniqueCount];


for (int i = 0; i < uniqueCount; i++) {
result[i] = uniqueChars[i];
}

return result;
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
System.out.println("Enter the text:");
String input = scanner.nextLine();
char[] unique = findUniqueCharacters(input);

System.out.print("Unique characters: ");


for (char c : unique) {
System.out.print(c + " ");
}

scanner.close();
}
}
Output:
Enter the text:
hello world
Unique characters: h e l o w r d

3. Write a program to find the first non-repeating character in a string and show the
result

import java.util.Scanner;
public class FirstNonRepeatingCharacter {

public static char findFirstNonRepeatingChar(String text) {


int[] freq = new int[256];

int length = 0;
try {
while (true) {
char c = text.charAt(length);
freq[c]++;
length++;
}
} catch (IndexOutOfBoundsException e) {
}

for (int i = 0; i < length; i++) {


if (freq[text.charAt(i)] == 1) {
return text.charAt(i);
}
}

return '\0';
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
System.out.println("Enter the text:");
String input = scanner.nextLine();
char result = findFirstNonRepeatingChar(input);
if (result != '\0') {
System.out.println("First non-repeating character: " + result);
} else {
System.out.println("No non-repeating characters found.");
}

scanner.close();
}
}
Output:
Enter the text:
Success
First non-repeating character: u

4. Write a program to find the frequency of characters in a string using the charAt()
method and display the result.

import java.util.Scanner;

public class CharacterFrequency {

public static String[][] findCharFrequencies(String text) {


int[] freq = new int[256];

int length = 0;
try {
while (true) {
char c = text.charAt(length);
freq[c]++;
length++;
}
} catch (IndexOutOfBoundsException e) {
}

boolean[] visited = new boolean[256];


String[][] result = new String[length][2];
int index = 0;
for (int i = 0; i < length; i++) {
char c = text.charAt(i);
if (!visited[c]) {
result[index][0] = String.valueOf(c);
result[index][1] = String.valueOf(freq[c]);
visited[c] = true;
index++; }
}
String[][] finalResult = new String[index][2];
for (int i = 0; i < index; i++) {
finalResult[i] = result[i];
}

return finalResult;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the text:");
String input = scanner.nextLine();
String[][] frequencies = findCharFrequencies(input);
System.out.println("Character | Frequency");
for (int i = 0; i < frequencies.length; i++) {
System.out.println(" " + frequencies[i][0] + " | " + frequencies[i][1]);
}
scanner.close();
}
}

Output:
Enter the text:
hello world
Character | Frequency
h | 1
e | 1
l | 3
o | 2
| 1
w | 1
r | 1
d | 1

5. Write a program to find the frequency of characters in a string using unique char-
acters and display the result.

import java.util.Scanner;
public class FrequencyUsingUniqueChars {

public static int getLength(String text) {


int len = 0;
try {
while (true) {
text.charAt(len);
len++;
}
} catch (IndexOutOfBoundsException e) {
}
return len;
}

public static char[] getUniqueCharacters(String text) {


int len = getLength(text);
char[] unique = new char[len];
int uniqueCount = 0;

for (int i = 0; i < len; i++) {


char current = text.charAt(i);
boolean isUnique = true;
for (int j = 0; j < i; j++) {
if (text.charAt(j) == current) {
isUnique = false;
break;
}
}
if (isUnique) {
unique[uniqueCount++] = current;
}
}

char[] result = new char[uniqueCount];


for (int i = 0; i < uniqueCount; i++) {
result[i] = unique[i];
}
return result;
}

public static String[][] getCharFrequencies(String text) {


int[] freq = new int[256];
int len = getLength(text);

for (int i = 0; i < len; i++) {


freq[text.charAt(i)]++;
}

char[] uniqueChars = getUniqueCharacters(text);


String[][] result = new String[uniqueChars.length][2];
for (int i = 0; i < uniqueChars.length; i++) {
result[i][0] = String.valueOf(uniqueChars[i]);
result[i][1] = String.valueOf(freq[uniqueChars[i]]);
}

return result;
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
System.out.println("Enter the text:");
String input = scanner.nextLine();

String[][] frequencies = getCharFrequencies(input);

System.out.println("Character | Frequency");
for (int i = 0; i < frequencies.length; i++) {
System.out.println(" " + frequencies[i][0] + " | " + frequencies[i][1]);
}

scanner.close();
}
}

Output:
Enter the text:
Banana
Character | Frequency
b | 1
a | 3
n | 2

6. Write a program to find the frequency of characters in a string using nested loops and display
the result.

import java.util.Scanner;

public class FrequencyUsingNestedLoops {

public static String[] getCharFrequencies(String text) {


char[] chars = text.toCharArray();
int[] freq = new int[chars.length];

for (int i = 0; i < chars.length; i++) {


freq[i] = 1;
if (chars[i] == '0') continue;
for (int j = i + 1; j < chars.length; j++) {
if (chars[i] == chars[j]) {
freq[i]++;
chars[j] = '0';
}
}
}

int count = 0;
for (int i = 0; i < chars.length; i++) {
if (chars[i] != '0') {
count++;
}
}

String[] result = new String[count];


int index = 0;
for (int i = 0; i < chars.length; i++) {
if (chars[i] != '0') {
result[index++] = chars[i] + " = " + freq[i];
}
}

return result;
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
System.out.println("Enter the text:");
String input = scanner.nextLine();

String[] frequencies = getCharFrequencies(input);

System.out.println("Character Frequencies:");
for (String entry : frequencies) {
System.out.println(entry);
}

scanner.close();
}
}
Output:
Enter the text:
Mississippi
Character Frequencies:
m=1
i=4
s=4
p=2

7. Write a program to to check if a text is palindrome and display the result.

import java.util.Scanner;

public class PalindromeChecker {

public static boolean isPalindromeLogic1(String text) {


int start = 0;
int end = text.length() - 1;

while (start < end) {


if (text.charAt(start) != text.charAt(end)) {
return false;
}
start++;
end--;
}
return true;
}

public static boolean isPalindromeLogic2(String text, int start, int end) {


if (start >= end) return true;
if (text.charAt(start) != text.charAt(end)) return false;
return isPalindromeLogic2(text, start + 1, end - 1);
}

public static boolean isPalindromeLogic3(String text) {


char[] original = text.toCharArray();
char[] reverse = reverseText(text);
for (int i = 0; i < original.length; i++) {
if (original[i] != reverse[i]) {
return false;
}
}
return true;
}

public static char[] reverseText(String text) {


int len = text.length();
char[] reverse = new char[len];
for (int i = 0; i < len; i++) {
reverse[i] = text.charAt(len - 1 - i);
}
return reverse;
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
System.out.println("Enter the text:");
String input = scanner.nextLine();

boolean result1 = isPalindromeLogic1(input);


boolean result2 = isPalindromeLogic2(input, 0, input.length() - 1);
boolean result3 = isPalindromeLogic3(input);

System.out.println("Palindrome Check (Logic 1 - Iterative): " + result1);


System.out.println("Palindrome Check (Logic 2 - Recursive): " + result2);
System.out.println("Palindrome Check (Logic 3 - Char Array): " + result3);

scanner.close();
}
}
Output:
Enter the text:
Madam
Palindrome Check (Logic 1 - Iterative): true
Palindrome Check (Logic 2 - Recursive): true
Palindrome Check (Logic 3 - Char Array): true

8. Write a program to check if two texts are anagrams and display the result.
import java.util.Scanner;

public class AnagramChecker {

public static boolean areAnagrams(String text1, String text2) {


if (text1.length() != text2.length()) return false;

int[] freq1 = new int[256];


int[] freq2 = new int[256];

for (int i = 0; i < text1.length(); i++) {


freq1[text1.charAt(i)]++;
freq2[text2.charAt(i)]++;
}

for (int i = 0; i < 256; i++) {


if (freq1[i] != freq2[i]) return false;
}

return true;
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

System.out.println("Enter first text:");


String text1 = scanner.nextLine();

System.out.println("Enter second text:");


String text2 = scanner.nextLine();

boolean result = areAnagrams(text1, text2);


System.out.println("Are the texts anagrams? " + result);
scanner.close();
}
}
Output:
Enter first text:
listen
Enter second text:
Silent
Are the texts anagrams? True

9. Create a program to display a calendar for a given month and year. The program
should take the month and year as input from the user and display the calendar
for that month. E.g. for 07 2005 user input, the program should display the
calendar as shown below.

import java.util.Scanner;

public class MonthlyCalendar {

public static String getMonthName(int month) {


String[] months = {"January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"};
return months[month - 1];
}

public static boolean isLeapYear(int year) {


return (year % 400 == 0) || ((year % 4 == 0) && (year % 100 != 0));
}

public static int getNumberOfDays(int month, int year) {


int[] days = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
if (month == 2 && isLeapYear(year)) {
return 29;
}
return days[month - 1];
}

public static int getStartDay(int month, int year) {


int y0 = year - (14 - month) / 12;
int x = y0 + y0 / 4 - y0 / 100 + y0 / 400;
int m0 = month + 12 * ((14 - month) / 12) - 2;
int d0 = (1 + x + (31 * m0) / 12) % 7;
return d0; // 0 = Sunday, 1 = Monday, ..., 6 = Saturday
}

public static void displayCalendar(int month, int year) {


String monthName = getMonthName(month);
int days = getNumberOfDays(month, year);
int startDay = getStartDay(month, year);
System.out.printf(" %s %d\n", monthName, year);
System.out.println("Sun Mon Tue Wed Thu Fri Sat");
for (int i = 0; i < startDay; i++) {
System.out.print(" ");
}

for (int day = 1; day <= days; day++) {


System.out.printf("%3d ", day);
if ((day + startDay) % 7 == 0) {
System.out.println();
}
}
System.out.println();
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
System.out.print("Enter month (1-12): ");
int month = scanner.nextInt();

System.out.print("Enter year (e.g., 2025): ");


int year = scanner.nextInt();

displayCalendar(month, year);

scanner.close();
}
}

Output:
Enter month (1-12): 7
Enter year (e.g., 2025): 2005
July 2005
Sun Mon Tue Wed Thu Fri Sat
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31

10. Write a program to create a deck of cards, initialize the deck, shuffle the deck, and
distribute the deck of n cards to x number of players. Finally, print the cards the
players have.

import java.util.Scanner;
public class CardGame {

// Initialize deck
public static String[] initializeDeck() {
String[] suits = {"Hearts", "Diamonds", "Clubs", "Spades"};
String[] ranks = {"2", "3", "4", "5", "6", "7", "8", "9", "10",
"Jack", "Queen", "King", "Ace"};

int numOfCards = suits.length * ranks.length;


String[] deck = new String[numOfCards];
int index = 0;

for (String suit : suits) {


for (String rank : ranks) {
deck[index++] = rank + " of " + suit;
}
}
return deck;
}

// Shuffle deck
public static void shuffleDeck(String[] deck) {
int n = deck.length;
for (int i = 0; i < n; i++) {
int randomCardNumber = i + (int)(Math.random() * (n - i));
String temp = deck[i];
deck[i] = deck[randomCardNumber];
deck[randomCardNumber] = temp;
}
}

// Distribute cards
public static String[][] distributeCards(String[] deck, int n, int players) {
if (n % players != 0) {
System.out.println("Cards cannot be evenly distributed among players.");
return null;
}

int cardsPerPlayer = n / players;


String[][] distributed = new String[players][cardsPerPlayer];

for (int i = 0; i < players; i++) {


for (int j = 0; j < cardsPerPlayer; j++) {
distributed[i][j] = deck[i * cardsPerPlayer + j];
}
}
return distributed;
}

// Print cards
public static void printPlayersCards(String[][] playersCards) {
if (playersCards == null) return;

for (int i = 0; i < playersCards.length; i++) {


System.out.println("Player " + (i + 1) + ":");
for (String card : playersCards[i]) {
System.out.println(" " + card);
}
System.out.println();
}
}

// Main method
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);

String[] deck = initializeDeck();


shuffleDeck(deck);

System.out.print("Enter number of cards to distribute: ");


int n = sc.nextInt();

System.out.print("Enter number of players: ");


int players = sc.nextInt();

if (n > deck.length) {
System.out.println("Not enough cards in the deck.");
} else {
String[][] playersCards = distributeCards(deck, n, players);
printPlayersCards(playersCards);
}

sc.close();
}
}

Output:
Enter number of cards to distribute: 20
Enter number of players: 4
Player 1:
3 of Spades
10 of Clubs
Ace of Hearts
5 of Diamonds
King of Spades

Player 2:
2 of Diamonds
7 of Clubs
6 of Spades
Jack of Hearts
3 of Hearts

...

You might also like