How to apply distributive law to a String - java

I am working on a program that creates a truth table on any boolean function, but I don't really know how to deal with parenthesis.
If the input was AB+AC+AD, the program will display a perfect truth table, but if the input was A(B+C+D), I can't do anything while the string is on that form. So, I need to know how to remove parenthesis and make the input AB+AC+AD instead of A(B+C+D)
and if the input was A(BC+D(E)), I want to convert it to ABC+ADE, and so on. It might be an easy task, but for a beginner, it's really tough.
I tried to do it using stack data structure, but I am stuck when the input is A(B+C), the output was BA+C instead of AB+AC.
public static String distributive(String input) {
Stack<Character> stack = new Stack<>();
String currentVar = "";
String output = "";
for (char c : input.toCharArray()) {
if (c == '(') {
stack.push(c);
} else if (c == ')') {
stack.pop();
if (!stack.isEmpty()) {
output += currentVar;
}
currentVar = "";
} else if (c == '+' )//there's no need to put - or * cuz there's only + on the program ..
{
output += currentVar;
output += c;
if (!stack.isEmpty()) {
currentVar = "";
}
} else {
if (stack.isEmpty()) {
currentVar += c;
} else {
output += c;
}
}
}
return output;
}

Related

Palindrome Stack

I wrote this method to check to see if a words is a palindrome, but when it is a palindrome it keeps returning false
public boolean isPalindrome(String s){
int i;
int n = s.length();
Stack <Character> stack = new Stack <Character>();
for (i = 0; i < n/2; i++)
stack.push(s.charAt(i));
if (n%2 == 1)
i++;
while(!stack.empty( )) {
char c = stack.pop( );
if (c != s.charAt(i));
return false;
}
return true;
}
I'm not sure why you're not using { } brackets. Try to learn proper Java conventions early.
if (c != s.charAt(i)); // <- this semicolon is your problem
return false;
Is equivalent to:
if (c != s.charAt(i)) {
// Do nothing
}
// Do this no matter what
return false;
Furthermore, the logic on your for-loop may be flawed for similar reasons. Remove your semicolon, and better yet, practice always using brackets:
if (c != s.charAt(i)) {
return false;
}
#jhamon also points out that you never actually increment i in your while loop:
while(!stack.empty( )) {
char c = stack.pop( );
if (c != s.charAt(i)) {
return false;
}
i++;
}

Pig Latin Sentence Converter

I am trying a program that translates your sentence into pig latin. Here's the code I have so far:
public class PigLatin {
public static void main(String[] args) {
//Enter text in the quotes of System.ot.println(covertToLatin(" "));
System.out.println(covertToLatin("Type your sentence here."));
}
private static String covertToLatin(String string) {
String end = "";
String delims = "\\s+";
String[] words = string.split(delims);
for (int i = 0; i < words.length; i++) {
if(isVowel(words[i].toLowerCase().charAt(0))) {
end += words[i] + "ay";
} else {
end += words[i].substring(1) + words[i].substring(0, 1) + "ay";
}
}
return end;
}
private static boolean isVowel(char c) {
if (c == 'a')
return true;
if (c == 'e')
return true;
if (c == 'i')
return true;
if (c == 'o')
return true;
if (c == 'u')
return true;
return false;
}
}
It translates "Type your sentence here." to "ypeTayouryayentencesayere.hay" I am stumped as to finding a way to translate my whole sentence. can you please help me translate a whole sentence into pig latin? Also, it would help if you could find a way to make the sentence convert in all caps too.
for upper case, use String.toUpperCase() function
Start by translating one word first and then a complete sentence. For example STACK should print out ACKSTAY. Your program prints out TACKSAY.
Why is this? Let's look at your logic:
for (int i = 0; i < words.length; i++) {
if(isVowel(words[i].toLowerCase().charAt(0))) {
end += words[i] + "ay";
} else {
/*substring(1) is always 1 &&
you add substring(0,1) which is always the interval (0,1) they never change*/
end += words[i].substring(1) + words[i].substring(0, 1) +ay";
}
}
return end.toUpperCase();
}
private static boolean isVowel(char c) {
if ((c == 'a') | (c == 'e') | (c == 'i') | (c == 'o') | (c == 'u'))
return true;
return false;
}
Try writing your algorithm on paper first. For example always using the word stack.
First letter is an s (not a vowel) let's save it in a temp string.
second letter is t ( not a vowel) let's save it in a temp string.
a is a vowel! we print from a onwards + letters in temp + ay
end result = "ack" + "st" + "ay"
abstracting --> substring(i, endOfString) + substring(k,i) + "AY
so you actually need two counters! i,k used to print substring(i,EndOfString) and substring(i,k) which represents the temp array

Why isn't this program running properly? [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
The assignment was to create a postfix to infix converter using Stacks. The program compiles properly but when I tried to make a demo class, I received a null point exception line 32. Please share any observations, better coding conventions, or solutions.
import java.util.Stack;
public class PostfixtoInfix {
private String expression;
private Stack<Character> s;
Character pOpen = new Character('(');
Character pClose = new Character(')');
public String PostfixtoInfix(String e) {
expression = e;
String output = "";
for (int i = 0; i < e.length(); i++) {
char currentChar = e.charAt(i);
if (isOperator(currentChar)) {
while (!s.empty() && s.peek() != pOpen
&& hasHigherPrecedence(s.peek(), currentChar)) {
output += s.peek();
s.pop();
}
s.push(currentChar);
} else if (isOperand(currentChar)) {
output += currentChar;
} else if (currentChar == '(') {
s.push(currentChar);
} else if (currentChar == ')') {
while (!s.empty() && s.peek() != pClose) {
output += s.peek();
s.pop();
}
}
while (!s.empty()) {
output += s.peek();
s.pop();
}
}
return output;
}
public boolean isOperator(char c) {
if (c == '+' || c == '-' || c == '/' || c == '*' || c == '^')
return true;
return false;
}
public boolean isOperand(char c) {
if (c >= '0' && c <= '9')
return true;
if (c >= 'a' && c <= 'z')
return true;
if (c >= 'A' && c <= 'Z')
return true;
return false;
}
public int getOperatorWeight(char operator) {
int weight = -1;
switch (operator) {
case '+':
case '-':
weight = 1;
break;
case '*':
case '/':
weight = 2;
break;
case '^':
weight = 3;
}
return weight;
}
public boolean hasHigherPrecedence(char operator1, char operator2) {
int op1 = getOperatorWeight(operator1);
int op2 = getOperatorWeight(operator2);
if (op1 == op2) {
if (isRightAssociative(operator1))
return false;
else
return true;
}
return op1 > op2 ? true : false;
}
public boolean isRightAssociative(char op) {
if (op == '^')
return true;
return false;
}
}
To fix the NPE initialize your objects. Unlike C++, Stack<Character> s; is equivalent to Stack<Character> s = null;; not to Stack<Character> s = new Stack<>();!
Beware of == and != not behaving as you might expect for boxed objects.
Character a = new Character('A');
Character aa = new Character('A');
System.out.println(a == aa);
gives the (correct!) answer false.
They are different objects. If you want to compare for equality, use either:
System.out.println(a.equals(aa));
System.out.println((char)a==(char)aa);
The first uses an explicit method for comparing the object contents. The second one avoids this problem by using non-object primitives, where equality is bitwise, not reference-equality.
It appears that you declare a private member s, never assign anything to it, and then attempt to use it in expressions like s.empty() and s.pop(). If nothing is ever assigned to s, then it is null, and attempting to call a method on it will result in a NullPointerException.
To create an empty stack, you probably want to change the declaration to:
private Stack <Character> s = new Stack<Character>();
First of all, you have a method looking like a constructor:
public String PostfixtoInfix(String e) {
try changing it to something else, like:
public String transform(String e) {
Second, your s field never gets assigned a stack. Put
s = new Stack<Character>();
in your constructor. Also, new Character('a') != new Character('a'), because that will bypass automatic (pillowweight cached) boxing. Use instead just simple chars as pOpen and pClose.
Your access modifier may be preventing the program to access the stack.
Change:
private Stack <Character> s;
to:
protected Stack <Character> s;
Read more here

How to make a java infix to postfix while including spaces

I am trying to make a java class that allow the user to put in space when putting in the tokens for the calculator and then turns it into postfix.
But it is not giving the correct output. For example, for an input of 1+2, the output should be 12+ but it is 12.
import java.util.*;
public class Infix
{
Stack loco = new Stack();
//create a scanner
//now to create a stack
public String Prefix(String gordo)
{
//Here is where the Program Begin
//type the the regular expression
String[] red;
red=gordo.split("(?=[()+\\-*/])|(?<=[()+\\-*/])"); //tokenize the string include delimiter
System.out.println("THE EXPRESSION IN INFIX IS");
for(int k=0;i<red.length;k++)
{
red[i]=red[i].trim(); //remove white spaces
}
//now we will test out if what is stored is digit or character
System.out.println("BREAKING IT ALL DOWN INTO A STRING OF CHARACTERS");
String ramon;
char[] c; //an array of characters
char feo; // a single character
String post=""; //this is where the post fix expression will be put in
for(int i=0;i<red.length;i++)
{
ramon=red[i];
c=ramon.toCharArray();
for(int j=0;j<c.length;j++)
{
System.out.println(c[j]); //print what is stored in C
feo=c[j];
if(Character.isLetterOrDigit(feo) == true)
{
post=post+feo; //add character to string to post fix
}
else if( feo == '(' )
{
loco.push(feo);
}
else if( feo == ')')
{
char look;
while((look = LookAt()) != '(')
{
post=post+look; //add it all in there
PopIt();
}
}
//this does the associtivity and the operator precdence
//if the operator is lower or equal to the precedence change
//the current operand pop it from stack and put it into output
//string
else
{
while(LaPrio(feo) <= LaPrio(LookAt()))
{
post=post+LookAt();
PopIt();
}
}
}
}
System.out.println("THIS IS THE POSTFIX EXPRESSION");
return post;
}
//this will determine operator precedence
private int LaPrio(char operator)
{
if(operator == '/' || operator == '*' || operator == '%')
{
return 2;
}
if(operator == '+' || operator == '-')
{
return 1;
}
return 0;
}
//this will do the see what is one top of the stack
private Character LookAt()
{
if( !loco.empty() == false) //if there no items it will return false plus ! make it true
{
return(Character) loco.peek();
}
else
return 0;
}
private void PopIt()
{
if(!loco.empty())
{
loco.pop();
}
}
}

Comparing stack pop and queue dequeue in Java (palindromes)

Full disclosure: this is for an assignment, so please don't post actual code solutions!
I have an assignment that requires me to take a string from the user and pass it into a stack and a queue, then use those two to compare the chars to determine if the string is a palindrome. I have the program written, but there appears to be some logic error somewhere. Here's the relevant code:
public static void main(String[] args) {
UserInterface ui = new UserInterface();
Stack stack = new Stack();
Queue queue = new Queue();
String cleaned = new String();
boolean palindrome = true;
ui.setString("Please give me a palindrome.");
cleaned = ui.cleanString(ui.getString());
for (int i = 0; i < cleaned.length(); ++i) {
stack.push(cleaned.charAt(i));
queue.enqueue(cleaned.charAt(i));
}
while (!stack.isEmpty() && !queue.isEmpty()) {
if (stack.pop() != queue.dequeue()) {
palindrome = false;
}
}
if (palindrome) {
System.out.printf("%s is a palindrome!", ui.getString());
} else
System.out.printf("%s is not a palindrome :(", ui.getString());
stack.dump();
queue.clear();
}
public class Stack {
public void push(char c) {
c = Character.toUpperCase(c);
Node oldNode = header;
header = new Node();
header.setData(c);
header.setNext(oldNode);
}
public char pop() {
Node temp = new Node();
char data;
if (isEmpty()) {
System.out.printf("Stack Underflow (pop)\n");
System.exit(0);
}
temp = header;
data = temp.getData();
header = header.getNext();
return data;
}
}
public class Queue {
public void enqueue(char c) {
c = Character.toUpperCase(c);
Node n = last;
last = new Node();
last.setData(c);
last.setNext(null);
if (isEmpty()) {
first = last;
} else n.setNext(last);
}
public char dequeue() {
char data;
data = first.getData();
first = first.getNext();
return data;
}
}
public String cleanString(String s) {
return s.replaceAll("[^A-Za-z0-9]", "");
}
Basically, when running my code through the debugger in Eclipse, my pop and dequeue methods appear to only select certain alphanumerics. I am using replaceAll("[^A-Za-z0-9]", "") to "clean" the user's string of any nonalphanumeric chars (!, ?, &, etc.). When I say it only selects certain chars, there doesn't seem to be any pattern that I can discern. Any ideas?
Your general algorithm works properly, assuming your queue and stack are correct (i tried this using the Deque implementations found in the jdk). Since your assignment involves the datastructures, i've pretty much just took your main logic and replaced the datastructures with ArrayDequeue, so I don't feel like i'm answering this for you.
String word = "ooffoo";
word = word.replaceAll("[^A-Za-z0-9]", "");
Deque<Character> stack = new ArrayDeque<Character>(word.length());
Deque<Character> queue = new ArrayDeque<Character>(word.length());
for (char c : word.toCharArray()) {
stack.push(c);
queue.add(c);
}
boolean pal = true;
while (! stack.isEmpty() && pal == true) {
if (! stack.pop().equals(queue.remove())) {
pal = false;
}
}
System.out.println(pal);
I'd recommend using a debugger to see exactly what was being compared, or at the very least spit out some print lines:
while (!stack.isEmpty() && !queue.isEmpty()) {
Character sc = stack.pop();
Character qc = queue.dequeue();
System.out.println(sc + ":" + qc);
if (sc != qc) {
palindrome = false;
}
}

Categories