java - Why isn't this "else" statement working? -
edited
here's whole program. wrapped char in character wrapper use .equals() , fixed index issue, , replaced constants literals. program compiles , runs fine, tells if symbols matched, still skips "else" statement when there 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 argument dummy!"); system.exit(0); } string filestring = ""; /**open file , 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 file not found " + e); }//catch /**build list of characters file*/ char[] chararray = new char[filestring.length()]; (int = 0; < filestring.length(); i++) { chararray[i] = filestring.charat(i); }//for building chararray /**create stack manipulate grouping symbols*/ stack<character> stack = new stack<character>(); /**pushes grouping symbols stack , pops them when correspond*/ (int = 0; < 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 mistake @ index: " + i); system.out.println("\nhere's code (the error in middle):\n"); for(int j = - 20; j <= + 20; j++) { system.out.print(chararray[j]); } system.out.println("\n"); } } }//for /**inform user of result*/ if (stack.isempty()) { system.out.println("congratulations! grouping symbols matched!"); } else { system.out.println("i'm sorry. please fix program."); } }//main }//class
the final "else" statement skipped @ run time when there error.
the assignment write program using list or collection checks if grouping symbols in program overlapped. file should entered command line argument.
here's asked professor (no answer yet):
why can't create scanner read every character .txt(or .java) file? tried using delimiter of "" (no space) avoid ridiculous string char[] manipulation stack().
what's friggin' "else" statement?
thanks!
if print statement debugging, shouldn't placed inside else
. want mistake go inside 1 of else-ifs fixed (or popped), and then print where mistake found. rid of else statement. make it
} else if (temp == 6 && stack.peek().equals(five)) { stack.pop(); } system.out.println("there mistake @ index: " + chararray[i]); //it work
Comments
Post a Comment