I'm writing a program that will take in an equation and check if all the parentheses line up and it will output if it is good or not.
For Ex: (3+4) is good
((3*8) is NOT Good
I'm not allowed to use java's built in push() pop() methods ext..
I have to make my own which I think I got....I think!
The problem I'm having is in the Test() method.
First I'm not sure how to write the while loop like:
while(there are still characters)
Anyway the output I'm getting is: stack is empty -1
Any help is appreciated. I'm one of the slower program learners and I couldn't be trying any harder. Thanks.
Here's what I got:
public class Stacked {
int top;
char stack[];
int maxLen;
public Stacked(int max) {
top = -1;
maxLen = max;
stack = new char[maxLen];
}
public void push(char item) {
top++;
stack[top] = item;
}
public int pop() {
//x = stack[top];
//top = top - 1;
top--;
return stack[top];
}
public boolean isStackEmpty() {
if(top == -1) {
System.out.println("Stack is empty" + top);
return true;
} else
return false;
}
public void reset() {
top = -1;
}
public void showStack() {
System.out.println(" ");
System.out.println("Stack Contents...");
for(int j = top; j > -1; j--){
System.out.println(stack[j]);
}
System.out.println(" ");
}
public void showStack0toTop() {
System.out.println(" ");
System.out.println("Stack Contents...");
for(int j=0; j>=top; j++){
System.out.println(stack[j]);
}
System.out.println(" ");
}
//}
public boolean test(String p ){
boolean balanced = false;
balanced = false;
//while ( )
for(char i = '('; i < p.length(); i++ ){
push('(');
}
for (char j = ')'; j < p.length(); j++){
pop();
}
if (isStackEmpty()) {
balanced = true;
//return balanced;
}
return balanced;
}
public static void main(String[] args) {
Stacked stacks = new Stacked(100);
String y = new String("(((1+2)*3)");
stacks.test(y);
//System.out.println(stacks.test(y));
}
}
Now I'm getting somewhere. I need to be pointed in the right direction again. Thanks everyone this helped big time. I still have a lot more to do but this is good for now. Eventually I need to create a two more methods: one "infix to postfix" and the other "evaluating postfix" and at the end I'll need to read in answers from a text file instead of putting my own into the main method. Thanks again much appreciated.
Unless you need to actually evaluate the equation, a stack is too complicated a solution here. You simply need a counter:
int openParentheses = 0;
for (int i = 0; i < p.length(); i++) {
if (p.charAt(i) == '(') {
openParentheses++;
} else if (p.charAt(i) == ')') {
openParentheses--;
}
//check if there are more closed than open
if (openParentheses < 0) {
return false;
}
}
if (openParentheses == 0) {
return true;
} else {
return false;
}
If you absolutely must use stacks, use this:
for (int i = 0; i < p.length(); i++) {
if (p.charAt(i) == '(') {
push('x'); //doesn't matter what character you push on to the stack
} else if (p.charAt(i) == ')') {
pop();
}
//check if there are more closed than open
if (stackIsEmpty()) {
return false;
}
}
if (isStackEmpty()) {
return true;
} else {
return false;
}
I agree with Griff except that you should include another check if you didn't have more closed parentheses than open. (x*y))( is not a valid entry.
int openParentheses = 0;
for (int i = 0; i < p.length(); i++) {
if (p.charAt(i) == '(') {
openParentheses++;
} else if (p.charAt(i) == ')') {
openParentheses--;
}
if(openParentheses<0)
return false;
}
if (openParentheses == 0) {
return true;
} else {
return false;
}
You may be required to use a stack, but this could be done with a simple counter. This will show you a how to iterate over the characters of a String:
boolean test(String p) {
int balance = 0;
for (int idx = 0; idx < p.length(); ++idx) {
char ch = p.charAt(idx);
if (ch == '(')
++balance;
else if (ch == ')')
--balance;
if (balance < 0)
return false;
}
return balance == 0;
}
Of course, you could replace the increment and decrement with pushes and pops, respectively, on a stack.
For parsing you can use a for loop over the index and address the character of the string at the certain index.
But you actually do not need a stack, an integer variable openBraces is sufficient:
initialize with 0
for '(' you increment the variable one
for ')' you decrement the variable one
if openBraces is <0, you immediately give an error
if at the end openBraces is not equal to 0, you give an error.
Since you should do your homework yourself, I did not post source code, only explanations ;)
I think you just need this --
for ( int i = 0 ; i < p.length(); i++ ) {
char c = p.charAt(i);
if ( c == '(' )
push('(');
else if ( c == ')' ) {
if ( isStackEmpty() ) {
// Return error here because of unbalanced close paranthesis
}
pop();
}
else {
// do nothing
}
}
You CAN use a stack if you must, but considering how simplistic this is, you just need a counter that you increment and decrement and check for 0 at the end.
If you do use a counter, you should check after every decrement if the value is less than 0. If so, throw an error.
Edited based on Ryan/Dave Ball's comments.
It could be done like this:
String equation = "(2+3))";
Integer counter = 0;
//while(equation)
for(int i=0; i<equation.length();i++)
{
if(equation.charAt(i)=='(')
{
counter++;
}
else
if(equation.charAt(i)==')')
{
counter--;
}
}
if(counter == 0)
{
System.out.println("Is good!!!");
}
else
{
System.out.println("Not good!!!");
}
}
Related
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++;
}
I am trying to figure out part of an assignment and I have been beating my head against a wall for some time now. I'm trying to transcribe DNA sequences to RNA sequences. I am, however, getting an ArrayOutOfBoundsException. I am new to using enhanced for loops to iterate so my mistake may be hiding in there somewhere. It doesn't occur until the if statement parameters have been met.
private String dnaToRNA(String input) {
StringBuilder b = new StringBuilder();
char[] arr = input.toCharArray();
for (char a : arr) {
if (a == 'T') {
arr[a] ='U';
}
}
for (char a : arr) {
if (a == 'A'){
b.append ('U');
}
else if (a == 'U') {
b.append('A');
}
else if (a == 'C') {
b.append('G');
}
else if (a == 'G') {
b.append('C');
}
}
return b.reverse().toString();
}
}
public void transcribe(int pos1) {
if (pos1 > linkedList.size()) {
System.out.println("Position selected out of range");
return;
}
if (linkedList.get(pos1) != null && isValidDNA(linkedList.get(pos1))) {
linkedList.set(pos1, dnaToRNA(linkedList.get(pos1)));
}
}
The problem is in the statement arr[a] ='U';
The problem is that char is represented as an int internally and 'T' equals 84 hence you get an ArrayIndexOutOfBoundsException.
You need to iterate over it with a traditional counter:
for (int i = 0; i < arr.length; i++) {
if (arr[i] == 'T') {
arr[i] ='U';
}
}
You want 1 less than size , so : if (pos1 >= linkedList.size()) {.
When pos1 == linkedList.size() it will be out of bounds
So I have the majority of the code written and it works. Except for the iterative method keeps showing that it is not a palindrome regardless of what is typed in. I am at a loss as to how to remedy it here is the code.
//David Crouse Assignment 2
import java.util.Scanner;
public class Assignment2 {
public static boolean loop = false;
//main
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Welcome to the Palindrome Checker!");
do{
System.out.print("Enter a string to check if it is a palindrome. ");
System.out.print("Enter x to exit.");
String word = input.nextLine();
word = word.replaceAll("\\s","");
word = word.toLowerCase();
//Exit Program
if(word.equalsIgnoreCase("x")){
System.out.println("End of program. Good Bye!");
System.exit(0);
}
if(iterativePalindromeChecker(word)){
System.out.println("Iterative Result: Palindrome!");
}else{
System.out.println("Iterative Result: Not a palindrome");
}
if(recursivePalindromeChecker(word)){
System.out.println("Recursive Result: Palindrome!\n");
}else{
System.out.println("Recursive Result: Not a palindrome\n");
}
loop = true;
}while (loop == true);
}
//Iterative Method
public static boolean iterativePalindromeChecker(String str){
boolean result = false;
int length = str.length();
int i, begin, end, middle;
begin = 0;
end = length - 1;
middle = (begin + end)/2;
for (i = begin; i <= middle; i++) {
if (str.charAt(begin) == str.charAt(end)) {
begin++;
end--;
}
else {
break;
}
}
if (i == middle + 1) {
result = false;
}
return result;
}
//Recusive Methods
public static boolean recursivePalindromeChecker(String str){
if(str.length() == 0 || str.length() == 1)
return true;
if(str.charAt(0) == str.charAt(str.length()-1))
return recursivePalindromeChecker(str.substring(1,str.length()-1));
return false;
}
}
Your iterative method never sets result to be true. Here's a modified version:
public static boolean iterativePalindromeChecker(String str){
int length = str.length();
int i, begin, end, middle;
begin = 0;
end = length - 1;
middle = (begin + end)/2;
for (i = begin; i <= middle; i++) {
if (str.charAt(begin) == str.charAt(end)) {
begin++;
end--;
}
else {
return false;
}
}
return true;
}
Your iterative method does not set result = true anywhere, so it really can't help it. Although I think the iterative method could be better overall. Take a close look at what is happening in the recursive one and see if you can implement some of it (like the guard conditions) more closely in the iterative method, and keep in mind that you are not limited to a single index value in a for loop either. e.g.:
public static boolean iterativePalindromeChecker(String str) {
for(int start = 0, end = str.length() - 1; start < end; start++, end--) {
if(str.charAt(start) != str.charAt(end)) {
return false;
}
}
return true;
}
I'm guessing someone once told you that a function should only have one return point, and trying to follow that led you to using a mutable result variable which screwed you here. Using break poses the same ostensible problem anyway. Save yourself the headache and just return as soon as you know the answer.
public static boolean iterativePalindromeChecker(String str) {
int begin = 0;
int end = str.length() - 1;
while (begin < end) {
if (str.charAt(begin) != str.charAt(end)) {
return false;
}
begin++;
end--;
}
return true;
}
I have some specific task. We have String like "(()[]<>)" or something familiar with this. A question in my interview qustion was how check either String is correct or incorrect. For example: "()[]<>" - true, "([)" - false, "[(])" - false, "([<>])" - true. Thank you guys very much!
I can' t take what's wrong with my code.
Thank a lot guys!!!
Please help!
import java.util.Stack;
public class Test {
public static void main(String[] args) {
String line = "(<>()[])";
Test test = new Test();
boolean res = test.stringChecker(line);
System.out.println(res);
}
public boolean stringChecker(String line){
boolean result = false;
char letter = '\u0000';
char[] arr = line.toCharArray();
Stack<Character> stack = new Stack();
for (int i = 0; i < arr.length; i++) {
if (arr[i] == '(' || arr[i] == '[' || arr[i] == '<') {
stack.push(arr[i]);
}
if(arr[i] == ')' || arr[i] == ']' || arr[i] == '>'){
if(stack.peek() == arr[i]){
result = true;
stack.pop();
}
}
}
return result;
}
}
(0) You are pushing < ( and { but in your peek you are checking for >, ), and }
(1) You are starting with result false and setting it to true on the first successful match. Instead you should start with result true and set it to false on the first failed match.
(2) You should check that the stack is empty when you have run out of characters.
(3) You should check for the stack being empty before you peek.
(4) You might want to check for characters that are not expected.
In addition to #TheodoreNorvell 's explanation here is how an implementation could look like
public boolean stringChecker(String input) {
boolean result = true;
char[] arr = input.toCharArray();
Stack<Character> stack = new Stack<>();
try {
for (int i = 0; result && i < arr.length; i++) {
if (arr[i] == '(' || arr[i] == '[' || arr[i] == '<') {
stack.push(arr[i]);
} else if(arr[i] == ')') {
Character c = stack.pop();
result = c.equals('(');
} else if(arr[i] == ']') {
Character c = stack.pop();
result = c.equals('[');
} else if(arr[i] == '>') {
Character c = stack.pop();
result = c.equals('<');
} else {
// found some char that is not allowed
// here it is not just ignored,
// it invalidates the input
result = false;
}
}
// when the teher is not more chars in the array
// the stack has to be empty
result = result && stack.isEmpty() ;
} catch(EmptyStackException e) {
// found a closing bracket in the array
// but there is nothing on the stack
result = false;
}
return result;
}
#Test
public void stringChecker() {
Assert.assertTrue(stringChecker("[]"));
Assert.assertTrue(stringChecker("[(<>)]"));
Assert.assertFalse(stringChecker("([<>)]"));
Assert.assertFalse(stringChecker(">"));
// invalid char
Assert.assertFalse(stringChecker("<[]e>"));
// stack is not empty
Assert.assertFalse(stringChecker("("));
}
Note that in such a situation a switch-case statement is more elegant than if-else if-else.
How can I write the below code without using regex?
public static boolean validateCode(String code){
boolean hasAtLeastOneNumber = Pattern.compile("[0-9].*[0-9]")
.matcher(code).find();
boolean hasAtLeastTwoLetters = Pattern.compile("[a-zA-Z].*[a-zA-Z]")
.matcher(code).find();
boolean hasAtLeastOneHyphen = Pattern.compile("-")
.matcher(code).find();
}
How about
public static boolean validateCode2(String code) {
int numbers = 0, letters = 0, hyphens = 0;
for (char c : code.toCharArray()) {
if (Character.isDigit(c)) numbers++;
if (Character.isAlphabetic(c)) letters++;
if (c=='-') hyphens++;
}
return numbers>=2 && letters>=2 && hyphens>=1;
}
For hasAtLeastOneNumber:
for (char c : code.toCharArray()) {
if (Character.isDigit(c)) {
return true;
}
return false;
For hasAtLeastTwoLetters:
int numFound = 0;
for (char c : code.toCharArray()) {
if (Character.isLetter(c)) {
numFound++;
if (numFound >= 2) {
return true;
}
}
}
return false;
For hasAtLeastOneHyphen:
for (char c : code.toCharArray()) {
if (c == '-') {
return true;
}
}
return false;
If you don't want to use toCharArray, you could use:
for (int i=0; i<code.length(); i++) {
char c = code.charAt(i);
// do the rest of the test here
}
That's basically equivalent to using toCharArray except that it's slightly more confusing: someone who looks at the code would need to take a second or two to figure it out. With toCharArray it's obvious what you're doing.
You can loop through the string and test it for ranges of characters. See an example on IDEONE, or ask me if you need an explanation.
import java.util.*;
import java.lang.*;
class Main
{
public static void main (String[] args) throws java.lang.Exception
{
System.out.println(validarCodigo("No-numbers"));
System.out.println(validarCodigo("1-A"));
System.out.println(validarCodigo("This 1 Matches -- :-)"));
}
public static boolean validarCodigo(String codigo) {
int i;
char[] chars = codigo.toCharArray();
char current;
boolean tieneAlmenosUnNumero = false;
boolean tieneAlmenosDosLetras = false;
boolean tieneAlmenosUnGuion = false;
// Check for at least one number
for (i=0; i<chars.length; i++) {
current = chars[i];
if (current >= '0' && current <= '9') {
tieneAlmenosUnNumero = true;
break;
}
}
// Check for at least two letters
int found = 0;
for (i=0; i<chars.length; i++) {
current = chars[i];
boolean lower = current >= 'a' && current <= 'z';
boolean upper = current >= 'A' && current <= 'Z';
if (lower || upper) found++;
if (found == 2){
tieneAlmenosDosLetras = true;
break;
}
}
// Check for at least one hyphen
for (i=0; i<chars.length; i++) {
current = chars[i];
if (current == '-') {
tieneAlmenosUnGuion = true;
break;
}
}
return tieneAlmenosUnNumero && tieneAlmenosDosLetras && tieneAlmenosUnGuion;
}
}