Search code examples
javastringparenthesescharat

Picking out parentheses out of a String in Java


I am new to Java and trying to finish a program that will read a statement by the user and and scan to see if the amount of LEFT parenthesis match the RIGHT. The person who started the program created a stack but never made any use of it so I left it alone since I'm not very good with stacks. However, I was able to create a loop to to go through every character in the String to find the parenthesis, compare them, then print out if they are even or not. However I am having trouble with the while loop that goes through the String to find all parentheses. It's not working for some reason and I don't understand why. Any explanation on how to make this work will be greatly appreciated.

import java.util.*
public class ParenMatch
       {
public static void main (String[] args)
    {
Stack s = new Stack();
String line; // the string of characters to be checked
Scanner scan = new Scanner(System.in);
System.out.println ("\nParenthesis Matching");
System.out.print ("Enter a parenthesized expression: ");
line = scan.nextLine();

char parenline[] = new char[line.length()];

int x;
while(x < parenline.length) {
parenline[x] = line.charAt(x); 
        x++; 
    }
 int l,r,i,morel,morer = 0; 
while (i > parenline.length) {
        if (parenline[i] == "(" )
            l++;
        if (line.charAt(i) == ")") 
            r++; 
        i++;
    }

    if (l > r) {
        morel = l-r;  
        System.out.println("There are " +morel+ " more left parentheses than    right"); 
    }

    if (r > l) {
        morer = r-l; 
        System.out.println("There are " +morer+ " more right parentheses then left"); 
    }
    if (r == l) {
        System.out.println("The amount of left and right parentheses are even."); 
    }
}

}


Solution

  • You need to initialize x so for example.

    int x = 0;
    

    You cannot increment an uninitialized variable. Also to define parenline instead of looping and adding the char at the locations in the string just using one of the strings native methods:

    char parenline[] = line.toCharArray();
    

    Sorry if i explained this badly.