简体   繁体   中英

Why isn't this “else” statement working?

edited

Here's the whole program. I wrapped the char in a Character wrapper to use .equals() and fixed the index issue, and replaced the constants with literals. The program compiles and runs fine, tells you if the symbols are matched, but still skips that "else" statement when there is an unmatched symbol:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.Stack;


public class Exercise22_11 {

/**
 * 
 */
public static void main(String[] args) {

        /**for command line argument*/

        if(args.length == 0) {
            System.out.println("You didn't enter an argument dummy!");
            System.exit(0);
        }


        String fileString = "";

        /**Open the file and read it*/

        try{    
            File myOutFile = new File(args[0]);
            Scanner input = new Scanner(myOutFile);
            while (input.hasNext()){
        fileString += input.next();
            }

        }//try

        catch (FileNotFoundException e){
      System.out.println("Sorry that file is not found " + e);
        }//catch

        /**Build the list of characters from file*/

        char[] charArray = new char[fileString.length()];

        for (int i = 0; i < fileString.length(); i++) {
            charArray[i] = fileString.charAt(i);
        }//for building charArray

        /**Create a stack to manipulate grouping symbols*/

        Stack<Character> stack = new Stack<Character>();

        /**Pushes grouping symbols into stack and pops them when they correspond*/

        for (int i = 0; i < charArray.length; i++) {
            Character temp = new Character(charArray[i]);

            if (temp.equals('{') || temp.equals('(') || temp.equals('[')) {
                stack.push(temp);
            }   else if (temp.equals('}') || temp.equals(')') || temp.equals(']')) {
                if (temp.equals('}') && stack.peek().equals('{')){
                    stack.pop();
                }   else if (temp.equals(')') && stack.peek().equals('(')) {
                    stack.pop();
                }   else if (temp.equals(']') && stack.peek().equals('[')) {
                    stack.pop();
                }   else {
                    System.out.println("There is a mistake at index: " + i);
                    System.out.println("\nHere's the code (the error is in the middle):\n");
                    for(int j = i - 20; j <= i + 20; j++) {
                        System.out.print(charArray[j]);
                    }
                    System.out.println("\n");
                }
            }

        }//for

        /**Inform user of result*/

        if (stack.isEmpty()) {
            System.out.println("Congratulations!  Your grouping symbols are matched!");
        }
        else {
            System.out.println("I'm sorry.  Please fix your program.");
        }



}//main



}//class

The final "else" statement is skipped at run time when there is an error.

The assignment was to write a program using a list or collection that checks if the grouping symbols in a program are overlapped. The file should be entered as a command line argument.

Here's what I asked the professor (no answer yet):

  1. Why can't I create a scanner to read every character from the .txt(or .java) file? I tried using a delimiter of "" (no space) to avoid the RIDICULOUS String to Char[] to manipulation with the stack().

  2. What's with the friggin' "else" statement?

Thanks!

If this print statement is for debugging, then it shouldn't be placed inside an else . You want your mistake to go inside one of the else-ifs to be fixed (or popped), and then print where the mistake was found . Get rid of that else statement. Make it

}   else if (temp == SIX && stack.peek().equals(FIVE)) {
                    stack.pop();
                }   
    System.out.println("There is a mistake at index: " + charArray[i]); //it will work now

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM