Design a class PendulumS to perform an operation on a word containing alphabets in upper case only…
Design a class PendulumS to perform an operation on a word containing alphabets in upper case only. Rearrange the word by putting the lowest ASCII value character at the centre and the second lowest ASCII value character to its right and the third to its left and so on.
Example 1 : Input : COMPUTER
Output : TPMCEORU
Example 2 : Input : SCIENCE
Output : SIECCEN
The details of the members of the class are given below:
Class name : PendulumS
Data members/instance variables:
wrd : to store the original word
newwrd : to store the rearranged word
Methods/Member functions:
PendulumS(String k) : parameterised constructor to initialise wrd = k and newwrd = ""
int minCharIndex(String str) : to find the index of the minimum ASCII value character in str and return it
void arrange( ) : to rearrange the characters of wrd as per the given instructions and store it in newwrd by invoking minCharIndex( )
void display( ) : to display the original word and the rearranged word
Specify the class PendulumS giving the details of the constructor( ), int minCharIndex(String), void arrange( ) and void display( ). Define the main( ) function to create an object and call the functions accordingly to enable the task.
Answer
Answer
AIWritten by AI (antigravity) - it can contain mistakes.
import java.util.Scanner;
class PendulumS
{
String wrd;
String newwrd;
PendulumS(String k)
{
wrd = k;
newwrd = "";
}
int minCharIndex(String str)
{
int minIdx = 0;
char minCh = str.charAt(0);
for (int i = 1; i < str.length(); i++)
{
if (str.charAt(i) < minCh)
{
minCh = str.charAt(i);
minIdx = i;
}
}
return minIdx;
}
void arrange()
{
String temp = wrd;
int len = wrd.length();
for (int i = 0; i < len; i++)
{
int idx = minCharIndex(temp);
char ch = temp.charAt(idx);
temp = temp.substring(0, idx) + temp.substring(idx + 1);
if (i == 0)
{
newwrd = "" + ch;
}
else if (i % 2 == 1)
{
newwrd = newwrd + ch; // place to the right
}
else
{
newwrd = ch + newwrd; // place to the left
}
}
}
void display()
{
System.out.println("Original word: " + wrd);
System.out.println("Rearranged word: " + newwrd);
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter a word in uppercase: ");
String input = sc.next();
PendulumS obj = new PendulumS(input);
obj.arrange();
obj.display();
}
}Explanation: minCharIndex finds the index of the character with the minimum ASCII value in a string. arrange extracts characters in ascending ASCII order and alternately appends them to the right and prepends them to the left of the center character, forming the pendulum arrangement.From ISC 2026 Computer Science Paper 1, question 8.