In: Computer Science
java Programming Problem 1: Reverse Characters Create an application ReverseCharacters in which you use an array-based stack to read a sentence from the keyboard, and reverse the order of the letters in each word. Print the initial sentence, as well as the result of the reversal operation. Your Tasks: Using the information given in your textbook, create a class named ArrayBasedStack, that will help you solve the problem given above by providing the stack operations you need for this application. Create a class ReverseCharacters that solves the problem mentioned above using an array-based stack, implemented in the class required above. Note that the order of the words in the sentence remains the same, the scope being to reverse the characters in each word. If you implement all the required methods correctly, the driver program should generate outputs similar to the following:
Short Summary:
**************Please do upvote to appreciate our time. Thank you!******************
Source Code:
ArrayBasedStack.java
package com.core.java;
//This is an array based stack providing stack operations
public class ArrayBasedStack {
//Instance variables
private int top;
private int capacity;
private char[] array;
//Constructor
public ArrayBasedStack(int capacity) {
this.capacity = capacity;
this.array = new
char[capacity];
this.top = -1;
}
//Checks if array is full
public boolean isFull() {
return this.top == this.capacity -
1;
}
//Checks if array is empty
public boolean isEmpty() {
return this.top == -1;
}
//Pushes an element to stack
public void push(char value) {
if(!this.isFull()) {
this.array[++this.top] = value;
}
}
//Pops an element out of stack
public char pop() {
return
this.isEmpty()?'\u0000':this.array[this.top--];
}
//Reverses the characters in the array
public String reverseCharacters(char[] str) {
int n=str.length;
int i;
for(i = 0; i < n; ++i) {
push(str[i]);
}
for(i = 0; i < n; ++i)
{
str[i] =
pop();
}
return
String.valueOf(str);
}
}
ReverseCharacters.java
package com.core.java;
import java.util.Scanner;
//This class is used to reverse the characters in each word in
the given sentence
public class ReverseCharacters {
public static void main(String[] args) {
//Get user input using
scanner
Scanner input=new
Scanner(System.in);
System.out.println("Enter your
sentence below:");
String str =
input.nextLine();
//Split the sentence by words
String[] strArr=str.split("
");
//Pass every word to reverse
for(int
i=0;i<strArr.length;i++)
{
char[] charArr =
strArr[i].toCharArray();
int size =
charArr.length;
//Create
ArrayBasedStack instance
ArrayBasedStack
stack = new ArrayBasedStack(str.length());
System.out.print( stack.reverseCharacters(charArr)+" ");
}
input.close();
}
}
Code Screenshot:
Output:
**************Please do upvote to appreciate our time. Thank you!******************