Search code examples
javabreakcontinue

How to break label within a different method java


Here is my source code:

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;


public class PostfixConverter{



  static int top = 0;
  static String[] mainStack = new String[100];

  final static String asterisk = "*";
  final static String divisor = "/";
  final static String plus = "+";
  final static String minus = "-";
  final static String store = "ST TEMP";

  static int temp = 0;
  static int directionCounter = 0;
  static String[] directions = new String[100];
  static PostfixConverter s = new PostfixConverter();
  static String tempString = "TEMP";

  public static void main(String args[]) throws Exception {

      String string = null;

      String load = "LD ";
      String multiply = "ML ";
      String add = "AD ";
      String div = "DV ";
      String subtract = "SB ";

      String example = "AB+C-";

      try {
          // file reader code
          FileReader file = new     FileReader("ignore for now");
          BufferedReader reader = new BufferedReader(file);

          String line = "";

          while ((line = reader.readLine()) != null) {
              example = line;

              // for loop to print directions
              Characterloop:
              for (int i = 0; i < example.length(); i++) {

                  // get letter entered by user 1 by 1
                  char letter = example.charAt(i);

                  // convert char to string
                  String convertedChar = java.lang.String.valueOf(letter);

                  // finds operands in order or priority



                  // multiply character
                  if (convertedChar.equals(asterisk)) {

                      processOperand(PostfixConverter.multiply(string),  PostfixConverter.multiply(string), load,
                              multiply);
                  }

                  // division character
                  else if (convertedChar.equals(divisor)) {

                      processOperand(PostfixConverter.addition(string), PostfixConverter.addition(string), load, div);
                  }

                  // addition character
                  else if (convertedChar.equals(plus)) {

                      processOperand(PostfixConverter.addition(string), PostfixConverter.addition(string), load, add);
                  }

                  // subtraction character
                  else if (convertedChar.equals(minus)) {

                      processOperand(PostfixConverter.addition(string), PostfixConverter.addition(string), load,
                              subtract);

                  }
                  // letter character
                  else {
                      s.push(convertedChar);
                  }

              }

              // print out the instructions
              System.out.println("Assembly Directions are as follows: ");
              int printDirections = 0;
              for (int i = 0; i < directionCounter; i++) {
                  System.out.println(directions[printDirections]);
                  printDirections++;
              }
              printDirections = 0;
              directionCounter = 0;
              System.out.println("This is the end of the directions.");
              System.out.println("");
              directionCounter = 0;
              temp = 0;
              top = 0;

          }reader.close();

      } catch (FileNotFoundException exception) {
          System.out.println("The file was not found.");
      }
    }

    private static void processOperand(String postFileConverterOutput, String postFileConverterOutput2,
          String instruction1, String instruction2) {
      String outcome;
      String opReturn1 = postFileConverterOutput;
      String opReturn2 = postFileConverterOutput2;
      directions[directionCounter] = instruction1 + opReturn2;
      directionCounter++;
      directions[directionCounter] = instruction2 + opReturn1;
      directionCounter++;
      temp++;
      outcome = tempString + java.lang.String.valueOf(temp);
      directions[directionCounter] = store + java.lang.String.valueOf(temp);
      directionCounter++;
      s.push(outcome);
  }

  // multiply method
  public static String multiply(String a) {
     if(top == 0){
        System.out.println("Invalid Argument");
        System.out.println("Please resubmit a correct String");
        break Characterloop;
     }

      String multVariable = PostfixConverter.pop(mainStack[top]);
      top--;
      return multVariable;
  }

  // addition method
  public static String addition(String a) {
     if(top == 0){
        System.out.println("Invalid Argument");
        System.out.println("Please resubmit a correct String");
     }

      String addVariable = PostfixConverter.pop(mainStack[top]);
      top--;
      return addVariable;
  }

  // subtraction method
  public static String subtraction(String a) {
     if(top == 0){
        System.out.println("Invalid Argument");
        System.out.println("Please resubmit a correct String");
     }

      String subVariable = PostfixConverter.pop(mainStack[top]);
      top--;
      return subVariable;
  }

  // division method
  public static String division(String a) {
     if(top == 0){
        System.out.println("Invalid Argument");
        System.out.println("Please resubmit a correct String");
     }

      String divVariable = PostfixConverter.pop(mainStack[top]);
      top--;
      return divVariable;
  }

  public static boolean empty() {
     boolean check = false;

     if (top < 0){
          check = true;
     }
      else{
          check = false;
      }return check;
  }

  public static String pop(String j) {
     if (top < 0) {
         System.out.println("Stack is empty");
         System.exit(1);
     }
     return mainStack[top - 1];
 }

  public void push(String x) {
      if (top == 99) {
          System.out.println("Stack Overflow");
          System.exit(1);
      } else
          mainStack[top] = x;
         System.out.println("Top:" + top + "||" + " Array: " + mainStack[top]);
      top++;
   }// end push

   }

How can I get this method to stop running the loop when an invalid string is given? The item I am asking about is in asterisks below ** question **. Say for example i am given the postfix string " AB+*AB+ " and " AB+". Obviously this is invalid as there cannot be two operators with only two operands. How can I skip over the first statement and print "invalid argument" and continue onto the next string (AB+)? I researched break and continue, but I do not know how to implement this within another method. This is for a homework assignment and would just like to be pointed into the right direction.

// multiply method
  public static String multiply(String a) {
     if(top == 0){
        System.out.println("Invalid Argument");
        System.out.println("Please resubmit a correct String");
        **break Characterloop;**
     }

Solution

  • Something like this could be done using exceptions and try/catch. However doing so should be used sparingly. Throwing an exception should not be used to "return" something to the user. But throwing an exception has benefits:

    • They are easier to reuse
    • You can attach information to a exception
    • Compile time checking (checked exceptions only). For labels, if a break statement worked as you intended, there would be no compile time checks that verify that the method is only called, if there's a method call in the stack that contains the appropriate label
    • They have better IDE support (try / catch block generation)
    • You can catch whole groups of exceptions, if they have a common superclass

    Let's simplyfy the problem code:

    code with invalid breaks

    break

    void a() {
        label1: while (check()) {
            b();
        }
    }
    
    void b() {
        c();
    }
    
    void c() {
        if (check2()) {
            break label1;
        }
        doSomething();
    }
    

    continue

    void d() {
        label2: while(check()) {
            e();
        }
        doSomething();
    }
    
    void e() {
        f();
    }
    
    void f() {
        if (check2()) {
            continue label2;
        }
        doSomething();
    }
    

    solution using exception

    break

    class MyException1 extends Exception {
    }    
    
    void a() {
        try {
            while (check()) {
                b();
            }
        } catch (MyException1 ex) {
             // we're already outside the loop; nothing to be done here
        }
    }
    
    void b() throws MyException1 {
        c();
    }
    
    void c() throws MyException1 {
        if (check2()) {
            throw new MyException1();
        }
        doSomething();
    }
    

    continue

    class MyException2 extends Exception {
    } 
    
    void d() {
        while(check()) {
            try {
                e();
                doSomething();
            } catch (MyException2 ex) {
                // nothing to do here; We're already at the end of the loop body
            }
        }
    }
    
    void e() throws MyException2 {
        f();
    }
    
    void f() throws MyException2 {
        if (check2()) {
            throw new MyException2();
        }
        doSomething();
    }