0% found this document useful (0 votes)
35 views

tp[

n

Uploaded by

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

tp[

n

Uploaded by

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

Solutions to Unsolved Java Programs based

on Strings

Question 1

Write a program to input a sentence. Find and display


the following:
(i) Number of words present in the sentence
(ii) Number of letters present in the sentence
Assume that the sentence has neither include any digit
nor a special character.
import java.util.Scanner;

public class KboatWordsNLetters


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a sentence:");
String str = in.nextLine();

int wCount = 0, lCount = 0;


int len = str.length();
for (int i = 0; i < len; i++) {
char ch = str.charAt(i);
if (ch == ' ')
wCount++;
else
lCount++;
}

/*
* Number of words in a sentence are one
more than
* the number of spaces so incrementing
wCount by 1
*/
wCount++;

System.out.println("No. of words = " +


wCount);
System.out.println("No. of letters = " +
lCount);
}
}

Output

Question 2

Write a program in Java to accept a word/a String and


display the new string after removing all the vowels
present in it.
Sample Input: COMPUTER APPLICATIONS
Sample Output: CMPTR PPLCTNS
import java.util.Scanner;

public class KboatVowelRemoval


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a word or
sentence:");
String str = in.nextLine();

int len = str.length();


String newStr = "";

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

char ch =
Character.toUpperCase(str.charAt(i));

if (ch == 'A' ||
ch == 'E' ||
ch == 'I' ||
ch == 'O' ||
ch == 'U') {
continue;
}

newStr = newStr + ch;


}

System.out.println("String with vowels


removed");
System.out.println(newStr);
}
}

Output
Question 3

Write a program in Java to accept a name(Containing


three words) and display only the initials (i.e., first letter
of each word).
Sample Input: LAL KRISHNA ADVANI
Sample Output: L K A
import java.util.Scanner;

public class KboatNameInitials


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a name of 3 or
more words:");
String str = in.nextLine();
int len = str.length();

System.out.print(str.charAt(0) + " ");


for (int i = 1; i < len; i++) {
char ch = str.charAt(i);
if (ch == ' ') {
char ch2 = str.charAt(i + 1);
System.out.print(ch2 + " ");
}
}
}
}

Output
Question 4

Write a program in Java to accept a name containing


three words and display the surname first, followed by
the first and middle names.
Sample Input: MOHANDAS KARAMCHAND GANDHI
Sample Output: GANDHI MOHANDAS KARAMCHAND
import java.util.Scanner;

public class KboatSurnameFirst


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a name of 3
words:");
String name = in.nextLine();

/*
* Get the last index
* of space in the string
*/
int lastSpaceIdx = name.lastIndexOf(' ');

String surname =
name.substring(lastSpaceIdx + 1);
String initialName = name.substring(0,
lastSpaceIdx);

System.out.println(surname + " " +


initialName);
}
}

Output

Question 5

Write a program in Java to enter a String/Sentence and


display the longest word and the length of the longest
word present in the String.
Sample Input: “TATA FOOTBALL ACADEMY WILL PLAY
AGAINST MOHAN BAGAN”
Sample Output: The longest word: FOOTBALL: The
length of the word: 8
import java.util.Scanner;

public class KboatLongestWord


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a word or
sentence:");
String str = in.nextLine();

str += " "; //Add space at end of string


String word = "", lWord = "";
int len = str.length();

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


char ch = str.charAt(i);
if (ch == ' ') {

if (word.length() >
lWord.length())
lWord = word;

word = "";
}
else {
word += ch;
}
}

System.out.println("The longest word: " +


lWord +
": The length of the word: " +
lWord.length());
}
}

Output

Question 6

Write a program in Java to accept a word and display the


ASCII code of each character of the word.
Sample Input: BLUEJ
Sample Output:
ASCII of B = 66
ASCII of L = 76
ASCII of U = 85
ASCII of E = 69
ASCII of J = 74
import java.util.Scanner;

public class KboatASCIICode


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a word:");
String word = in.nextLine();

int len = word.length();

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


char ch = word.charAt(i);
System.out.println("ASCII of " + ch
+ " = " + (int)ch);
}
}
}

Output

Question 7

Write a program in Java to accept a String in upper case


and replace all the vowels present in the String with
Asterisk (*) sign.
Sample Input: "TATA STEEL IS IN JAMSHEDPUR"
Sample output: T*T* ST**L *S *N J*MSH*DP*R
import java.util.Scanner;

public class KboatVowelReplace


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a string in
uppercase:");
String str = in.nextLine();
String newStr = "";
int len = str.length();

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


char ch = str.charAt(i);
if (ch == 'A' ||
ch == 'E' ||
ch == 'I' ||
ch == 'O' ||
ch == 'U') {
newStr = newStr + '*';
}
else {
newStr = newStr + ch;
}

System.out.println(newStr);
}
}

Output
Question 8

Write a program in Java to enter a sentence. Frame a


word by joining all the first characters of each word of the
sentence. Display the word.
Sample Input: Vital Information Resource Under Seize
Sample Output: VIRUS
import java.util.Scanner;

public class KboatFrameWord


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a sentence:");
String str = in.nextLine();
String word = "" + str.charAt(0);
int len = str.length();

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


char ch = str.charAt(i);
if (ch == ' ')
word += str.charAt(i + 1);
}

System.out.println(word);
}
}

Output

Question 9

Write a program in Java to enter a sentence. Display the


words which are only palindrome.
Sample Input: MOM AND DAD ARE NOT AT HOME
Sample Output: MOM
DAD
import java.util.Scanner;

public class KboatPalinWords


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a sentence:");
String str = in.nextLine();
str = str + " ";
String word = "";
int len = str.length();

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


char ch = str.charAt(i);
if (ch == ' ') {
int wordLen = word.length();
boolean isPalin = true;
for (int j = 0; j < wordLen / 2;
j++) {
if (word.charAt(j) !=
word.charAt(wordLen - 1 - j)) {
isPalin = false;
break;
}
}

if (isPalin)
System.out.println(word);

word = "";
}
else {
word += ch;
}
}
}
}

Output
Question 10

Write a program to accept a sentence. Display the


sentence in reversing order of its word.
Sample Input: Computer is Fun
Sample Output: Fun is Computer
import java.util.Scanner;

public class KboatReverseWords


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a sentence:");
String str = in.nextLine();
str = " " + str;
String word = "";
int len = str.length();

for (int i = len - 1; i >= 0; i--) {


char ch = str.charAt(i);
if (ch == ' ') {
System.out.print(word + " ");
word = "";
}
else {
word = ch + word;
}
}
}
}

Output

Question 11

Write a program to input a sentence and display the word


of the sentence that contains maximum number of
vowels.
Sample Input: HAPPY NEW YEAR
Sample Output: The word with maximum number of
vowels: YEAR
import java.util.Scanner;
public class KboatMaxVowelWord
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a sentence:");
String str = in.nextLine();

str = str + " ";


String word = "", mWord = "";
int count = 0, maxCount = 0;
int len = str.length();

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

char ch =
Character.toUpperCase(str.charAt(i));

if (ch == 'A' ||
ch == 'E' ||
ch == 'I' ||
ch == 'O' ||
ch == 'U') {
count++;
}

if (ch == ' ') {


if (count > maxCount) {
maxCount = count;
mWord = word;
}
word = "";
count = 0;
}
else {
word += ch;
}
}
System.out.println("The word with maximum
number of vowels: "
+ mWord);
}
}

Output

Question 12

Consider the sentence as given below:


Blue bottle is in Blue bag lying on Blue carpet
Write a program to assign the given sentence to a string
variable. Replace the word Blue with Red at all its
occurrence. Display the new string as shown below:
Red bottle is in Red bag lying on Red carpet
public class KboatStringReplace
{
public static void main(String args[]) {
String str = "Blue bottle is in Blue bag
lying on Blue carpet";
str += " ";
String newStr = "";
String word = "";
String target = "Blue";
String newWord = "Red";
int len = str.length();

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


char ch = str.charAt(i);
if (ch == ' ') {
if (target.equals(word)) {
newStr = newStr + newWord + "
";
}
else {
newStr = newStr + word + " ";
}
word = "";
}
else {
word += ch;
}

System.out.println(newStr);
}
}

Output
Question 13

Write a program to accept a word and convert it into


lower case, if it is in upper case. Display the new word by
replacing only the vowels with the letter following it.
Sample Input: computer
Sample Output: cpmpvtfr
import java.util.Scanner;

public class KboatVowelReplace


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter a word: ");
String str = in.nextLine();
str = str.toLowerCase();
String newStr = "";
int len = str.length();

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


char ch = str.charAt(i);
if (str.charAt(i) == 'a' ||
str.charAt(i) == 'e' ||
str.charAt(i) == 'i' ||
str.charAt(i) == 'o' ||
str.charAt(i) == 'u') {

char nextChar = (char)(ch + 1);


newStr = newStr + nextChar;

}
else {
newStr = newStr + ch;
}
}

System.out.println(newStr);
}
}

Output
Question 14

Write a program to input a sentence. Create a new


sentence by replacing each consonant with the previous
letter. If the previous letter is a vowel then replace it with
the next letter (i.e., if the letter is B then replace it with C
as the previous letter of B is A). Other characters must
remain the same. Display the new sentence.
Sample Input : ICC WORLD CUP
Sample Output : IBB VOQKC BUQ
import java.util.Scanner;

public class KboatReplaceLetters


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

System.out.println("Enter a sentence: ");


String str = in.nextLine();

int len = str.length();

String newStr = "";

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


char ch = str.charAt(i);
char chUp =
Character.toUpperCase(ch);
if (chUp == 'A'
|| chUp == 'E'
|| chUp == 'I'
|| chUp == 'O'
|| chUp == 'U') {
newStr = newStr + ch;
}
else {
char prevChar = (char)(ch - 1);
char prevCharUp =
Character.toUpperCase(prevChar);
if (prevCharUp == 'A'
|| prevCharUp == 'E'
|| prevCharUp == 'I'
|| prevCharUp == 'O'
|| prevCharUp == 'U') {
newStr = newStr + (char)(ch +
1);
}
else {
newStr = newStr + prevChar;
}
}
}

System.out.println(newStr);

}
}

Output
Question 15

A 'Happy Word' is defined as:

Take a word and calculate the word's value based on


position of the letters in English alphabet. On the
basis of word’s value, find the sum of the squares of
its digits. Repeat the process with the resultant
number until the number equals 1 (one). If the
number ends with 1 then the word is called a 'Happy
Word'.
Write a program to input a word and check whether it a
‘Happy Word’ or not. The program displays a message
accordingly.

Sample Input: VAT


Place value of V = 22, A= 1, T = 20
[Hint: A = 1, B = 2, ----------, Z = 26]
Solution:
22120 22 + 22 + 12 + 22 + 02 = 13
12 + 32 = 10
12 + 02 = 1

Sample Output: A Happy Word


import java.util.Scanner;

public class KboatHappyWord


{
private static boolean isHappyNumber(long
num) {
long sum = 0;
long n = num;
do {
sum = 0;
while (n != 0) {
int d = (int)(n % 10);
sum += d * d;
n /= 10;
}
n = sum;
} while (sum > 6);

return (sum == 1);


}

public static void main(String args[]) {


Scanner in = new Scanner(System.in);
System.out.println("Enter a word: ");
String word = in.next();
word = word.toUpperCase();
String wordValueStr = "";
int len = word.length();
for (int i = 0; i < len; i++) {
wordValueStr +=
String.valueOf(word.charAt(i) - 64);
}

long wordValue =
Long.parseLong(wordValueStr);
boolean isHappy =
isHappyNumber(wordValue);

if (isHappy)
System.out.println("A Happy Word");
else
System.out.println("Not a Happy
Word");
}
}

Output
Question 16

Write a program to input a sentence. Count and display


the frequency of each letter of the sentence in
alphabetical order.
Sample Input: COMPUTER APPLICATIONS
Sample Output:

Character Frequency Character Frequency


A 2 O 2
C 2 P 3
I 1 R 1
L 2 S 1
M 1 T 2
N 1 U 1
import java.util.Scanner;
public class KboatLetterFreq
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a sentence:");
String str = in.nextLine();
str = str.toUpperCase();
int freqMap[] = new int[26];
int len = str.length();

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


char ch = str.charAt(i);
if (Character.isLetter(ch)) {
int chIdx = ch - 65;
freqMap[chIdx]++;
}
}

System.out.println("Character\tFrequency");
for (int i = 0; i < freqMap.length; i++)
{
if (freqMap[i] > 0) {
System.out.println((char)(i + 65)
+ "\t\t" +
freqMap[i]);
}
}
}
}

Output
Question 17

Write a program to accept a string. Convert the string


into upper case letters. Count and output the number of
double letter sequences that exist in the string.
Sample Input: "SHE WAS FEEDING THE LITTLE
RABBIT WITH AN APPLE"
Sample Output: 4
import java.util.Scanner;
public class KboatLetterSeq
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter string: ");
String s = in.nextLine();
String str = s.toUpperCase();
int count = 0;
int len = str.length();

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


if (str.charAt(i) == str.charAt(i +
1))
count++;
}

System.out.println("Double Letter
Sequence Count = " + count);

}
}

Output
Question 18

Special words are those words which start and end with
the same letter.
Example: EXISTENCE, COMIC, WINDOW
Palindrome words are those words which read the same
from left to right and vice-versa.
Example: MALYALAM, MADAM, LEVEL, ROTATOR,
CIVIC
All palindromes are special words but all special words
are not palindromes.
Write a program to accept a word. Check and display
whether the word is a palindrome or only a special word
or none of them.
import java.util.Scanner;

public class KboatSpecialPalindrome


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter a word: ");
String str = in.next();
str = str.toUpperCase();
int len = str.length();

if (str.charAt(0) == str.charAt(len - 1))


{
boolean isPalin = true;
for (int i = 1; i < len / 2; i++) {
if (str.charAt(i) !=
str.charAt(len - 1 - i)) {
isPalin = false;
break;
}
}

if (isPalin) {
System.out.println("Palindrome");
}
else {
System.out.println("Special");
}
}
else {
System.out.println("Neither Special
nor Palindrome");
}

}
}

Output
Question 19

Write a program to input a sentence. Convert the


sentence into upper case letters. Display the words along
with frequency of the words which have at least a pair of
consecutive letters.
Sample Input: MODEM IS AN ELECTRONIC DEVICE
Sample Output:
MODEM
DEVICE
Number of words containing consecutive letters: 2
import java.util.Scanner;

public class KboatStringConsecutive


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter the string: ");
String str = in.nextLine();
str = str.toUpperCase();
str += " ";
String word = "";
int count = 0;
int len = str.length();

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


if (str.charAt(i) == ' ') {
int wordLen = word.length();
for (int j = 0; j < wordLen - 1;
j++) {
if (word.charAt(j) + 1 ==
word.charAt(j + 1)) {
count++;
System.out.println(word);
break;
}
}

word = "";
}
else {
word += str.charAt(i);
}
}

System.out.println("Number of words
containing consecutive letters: " + count);
}
}

Output

Question 20

Write a program to accept a word (say, BLUEJ) and


display the pattern:

(a)

BLUEJ
BLUE
BLU
BL
B
import java.util.Scanner;

public class KboatStringPattern


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter a word: ");
String word = in.nextLine();
int len = word.length();

for (int i = len - 1; i >= 0; i--) {


for (int j = 0; j <= i; j++) {
char ch = word.charAt(j);
System.out.print(ch);
}
System.out.println();
}
}
}

Output
(b)

J
EE
UUU
LLLL
BBBBB
import java.util.Scanner;

public class KboatStringPattern


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter a word: ");
String word = in.nextLine();
int len = word.length();

for (int i = len - 1; i >= 0; i--) {


for (int j = len - 1; j >= i; j--) {
char ch = word.charAt(i);
System.out.print(ch);
}
System.out.println();
}
}
}

Output

(c)

BLUEJ
LUEJ
UEJ
EJ
J
import java.util.Scanner;

public class KboatStringPattern


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter a word: ");
String word = in.nextLine();
int len = word.length();

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


for (int j = i; j < len; j++) {
char ch = word.charAt(j);
System.out.print(ch);
}
System.out.println();
}
}
}

Output

Question 21
Write a program to display the pattern:
(a)

ABCDE
BCDE
CDE
DE
E
public class KboatStringPattern
{
public static void main(String args[]) {
String word = "ABCDE";
int len = word.length();

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


for (int j = i; j < len; j++) {
char ch = word.charAt(j);
System.out.print(ch);
}
System.out.println();
}
}
}

Output
(b)

A
BC
DEF
GHIJ
KLMNO
public class KboatStringPattern
{
public static void main(String args[]) {
char ch = 'A';

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


for (int j = 0; j <= i; j++) {
System.out.print(ch++);
}
System.out.println();
}
}
}
Output

(c)

ABCDE
ABCDA
ABCAB
ABABC
AA B C D
public class KboatStringPattern
{
public static void main(String args[]) {
String word = "ABCDE";
int len = word.length();

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


for (int j = 0; j < len - i; j++) {
System.out.print(word.charAt(j));
}
for (int k = 0; k < i; k++) {
System.out.print(word.charAt(k));
}
System.out.println();
}
}
}

Output

Question 22

Write a program to generate a triangle or an inverted


triangle till n terms based upon the User’s choice of the
triangle to be displayed.

Example 1:
Input: Type 1 for a triangle and
Type 2 for an inverted triangle
Enter your choice 1
Enter the number of terms 5
Sample Output:
* * * * *
* * * *
* * *
* *
*
Example 2:
Input: Type 1 for a triangle and
Type 2 for an inverted triangle
Enter your choice 2
Enter the number of terms 5
Sample Output:
A B C D E
A B C D
A B C
A B
A
import java.util.Scanner;

public class KboatTriangleChoice


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Type 1 for a triangle
and");
System.out.println("Type 2 for an
inverted triangle of alphabets");
System.out.print("Enter your choice: ");
int choice = in.nextInt();
System.out.print("Enter the number of
terms: ");
int n = in.nextInt();

switch (choice) {
case 1:
for (int i = 0; i <= n; i++) {
for (int j = 0; j < i; j++) {
System.out.print(' ');
}
for (int k = i; k <= n; k++)
{
System.out.print('*');
}
System.out.println();
}
break;

case 2:
n += 64;
for (int i = n; i >= 65; i--) {
for (int j = 65; j <= i; j++)
{

System.out.print((char)j);
}
System.out.println();
}
break;

default:
System.out.println("Incorrect
choice");
break;
}
}
}

Output
Question 23
Write a program to generate a triangle or an inverted
triangle based upon User’s choice.

Example 1:
Input: Type 1 for a triangle and
Type 2 for an inverted triangle
Enter your choice 1
Enter a word : BLUEJ
Sample Output:
B
LL
UUU
EEEE
JJJJJ

Example 2:
Input: Type 1 for a triangle and
Type 2 for an inverted triangle
Enter your choice 2
Enter a word : BLUEJ
Sample Output:
BLUEJ
BLUE
BLU
BL
B
import java.util.Scanner;

public class KboatTriangleMenu


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Type 1 for a triangle
and");
System.out.println("Type 2 for an
inverted triangle");
System.out.print("Enter your choice: ");
int choice = in.nextInt();
in.nextLine();
System.out.print("Enter a word: ");
String word = in.nextLine();
int len = word.length();

switch (choice) {
case 1:
for(int i = 0; i < len; i++) {
for(int j = 0; j <= i; j++) {
System.out.print(word.charAt(i));
}
System.out.println();
}
break;

case 2:
for(int i = len - 1; i >= 0; i--)
{
for(int j = 0; j <= i; j++) {

System.out.print(word.charAt(j));
}
System.out.println();
}
break;

default:
System.out.println("Incorrect
choice");
break;
}
}
}

Output
Question 24

Using the switch statement, write a menu driven program


for the following:

(a) To print the Floyd’s triangle:


1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
(b) To display the following pattern:
I
IC
ICS
ICSE

For an incorrect option, an appropriate error message


should be displayed.
import java.util.Scanner;

public class KboatPattern


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Type 1 for Floyd's
triangle");
System.out.println("Type 2 for an ICSE
pattern");

System.out.print("Enter your choice: ");


int ch = in.nextInt();

switch (ch) {
case 1:
int a = 1;
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(a++ + "\t");
}
System.out.println();
}
break;

case 2:
String s = "ICSE";
for (int i = 0; i < s.length(); i++)
{
for (int j = 0; j <= i; j++) {
System.out.print(s.charAt(j)
+ " ");
}
System.out.println();
}
break;

default:
System.out.println("Incorrect
Choice");
}
}
}

You might also like