简体   繁体   中英

Java debugging line 309 indexoutofbounds error. Main method is not running. i'm trying to insert from a text file

  import java.io.*;
 import java.util.*;



public class ESPInterpreter {
private Variable [] variable_table;
private String error;
private  int Line;


public ESPInterpreter() { 
    variable_table = new Variable['{'];

    for (int i = 0; i < '{'; i++) {
        variable_table[ i ] = new Variable();

    } 
    error ="";
    Line=1;
}

public void ShowHowToUseVariableClass() {
    char c = 'F';



}

public  void read(String fileName){
    String line ="";
    try {
            File file = new File(fileName);
               Scanner scanner = new Scanner(file);
               while (scanner.hasNextLine()) {
                   line= scanner.nextLine();
                   compiling(line);
                   Line++;
               }
               scanner.close();
              } catch (FileNotFoundException e) {
               e.printStackTrace();
              }       
         }


public void compiling(String line){
    String read;
    char eq ='=';
     read= line.substring(0, line.indexOf(" "));
     if(read.equals("read")){
         String value;
int value1;
         Scanner input = new Scanner(System.in);
         value = line.substring(line.lastIndexOf(" ")+1);
         if(!value.matches("[a-z]")){
                System.out.println("Line: "+Line +" "+ line+"\nerror: variable "+value+" is not allowed");
                System.exit(0);
            }
         if(value.length() ==1){
         char c= value.charAt(0);
         System.out.println("Enter an integer number for variable " + value 
+ ": ");
         value1=input.nextInt();
         variable_table[c].setchar(value);
     variable_table[c].setValue(value1);
         }}
     else if(read.equals("print")){
         print(line);

     }

     else if(line.contains("=")){   calculate(line);}
     else{
         System.out.println("Line: "+Line +" "+ line+"\nerror: "+read+" is 
not allowed");
            System.exit(0);
     }



}
private void calculate(String line){
    String[] split=line.split(" = ");
    String print= "";


    char t = split[0].charAt(0);
int v=0;


    if(!split[0].matches("[a-z]")){
        System.out.println("Line: "+Line +" "+ line+"\nerror: variable 
"+split[0]+" is not allowed");
        System.exit(0);
    }

    char t1= split[1].charAt(0);
            if(split[1].matches("[0-9]+")){

     v = Integer.parseInt(split[1]);

            variable_table[t].setValue(v);
        variable_table[t].setchar(split[0]);                
            }

    else{

        print= calculate1(split[1]);
        if(print.contains("(")){
            String print1 =  print.substring(1, print.length()-1).replaceAll("  ", "");
            variable_table[t].setValue(printCalculation(print1));
            variable_table[t].setchar(split[0]);
        }
        else{print = split[0]+" = "+ print.substring(1, print.length()-1).replace(",", "").replaceAll("  ", "");
        math(print);}
    }
}
public void math(String line){
    String[] split=line.split(" = ");

 String print = split[0]+ " = "+Integer.toString(math1(split[1]));
 char t = split[0].charAt(0);

variable_table[t].setchar(split[0]);
variable_table[t].setValue(math1(split[1]));
}
public int math1(String line){
    line = line.replaceAll(" ","");

    int result = 0;
    String a = line.replace("-", "+-");
    String[] b = a.split("\\+");

    for (String m1 : b) {
        String[] M = m1.split("\\*");
        int mResult = 1;
        for (String OP : M) {
            if (OP.contains("/")) {
                String[] division = OP.split("\\/");
                int dtotal = Integer.parseInt(division[0]);
                for (int i = 1; i < division.length; i++) {
                    dtotal /= Integer.parseInt(division[i]);
                }
                mResult *= dtotal;
            } else {
                mResult *= Integer.parseInt(OP);
            }
        }
        result += mResult;
    }
    return result;
} 
public String print(String line){
    String[] split=line.split("print ");
    String print="";
    String print1 ="";

    char t = split[1].charAt(0);

     if(split[1].matches("[a-z]") && split[1].length() ==1){
         System.out.println(t +": "+variable_table[t].getValue()); 
     }
     else if(split[1].contains("(")){
         print1 = calculate1(split[1]);

         print1 =  print1.substring(1, print1.length()-1);
    System.out.println(printCalculation(print1));
     }
     else {print = calculate1(split[1]);
     print =  print.substring(1, print.length()-1).replace(",", "").replaceAll("  ", "");
         System.out.println(math1(print));
     }
    return "";

}
private int printCalculation(String line) {

    if(isMatch(line)== true){
           line = line.replaceAll("\\(","").replaceAll("\\)","").replaceAll("\\,","");     
    }
     return math1(line);}

public static boolean isMatch(String str) {
    if (str.charAt(0) == '{')
        return false;

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

    char c;
    for(int i=0; i < str.length(); i++) {
        c = str.charAt(i);

        if(c == '(')
            stack.push(c);
        else if(c == ')')
            if(stack.empty())
                return false;
            else if(stack.peek() == '(')
                stack.pop();
            else
                return false;

    }
    return stack.empty();
}

public String calculate1(String line){
    String arr2="";
    String arr1="";
    String arr5 ="";
    String [] arr = line.split("");
    if(line.contains(" ")){
    arr5 = line.replaceAll(" ","");
    }
    else arr5 = line; 

    for(int i=0;i<'{';i++){

        while(variable_table[i].getChar() ==null){
        variable_table[i].setchar("");
        } 


    for(int j=0;j<arr.length;j++){

            if(variable_table[i].getChar().equals(arr[j])){

        arr1= Integer.toString(variable_table[i].getValue());

            arr2+=line.replace(arr[j], arr1)+" ";

            }}                  }

    String arr3[] = arr2.split(" ");

    int n= arr3.length;
String a[] = new String[arr5.length()];

String b[] = new String[n-a.length];

String print="";
System.arraycopy(arr3, 0, a, 0, a.length);

System.arraycopy(arr3, a.length, b, 0, b.length);

print= Arrays.toString(arr3);

int n1= a.length;
for(int i=0; i<a.length;i++){
for(int j=i;j<b.length; j+=n1){

    if(a[i].matches(".*[a-z].*") && b[j].matches("[0-9]+")){

a[i]=b[j];
    }

    }

}
print= Arrays.toString(a);
for(int i=0;i<a.length;i++){
if(a[i].matches(".*[a-zA-Z]+.*")){
    System.out.println("Line: "+Line +" "+ line+"\nerror: variable "+a[i] +" is not defined");
    System.exit(0);
}
else if(a[i].equals("%") ||a[i].equals("%")||a[i].equals("%")){
    System.out.println("Line: "+Line +" "+ line+"\nSyntax error: "+a[i] );
    System.exit(0);
}

}
return print;
}
public static void main( String [ ] args ) {
    String file="";
    Scanner input= new Scanner(System.in);  

   Line 309 is below:
    System.out.println("file name is "+ args[0]);
    ESPInterpreter readFile = new ESPInterpreter();
    readFile.read(args[0]);
    ESPInterpreter sample = new ESPInterpreter();
    sample.ShowHowToUseVariableClass();
}

}

I added the complete code line 309 is pointed out. If you find any other errors please let me know. I have 2 other java files with this program and 3 esp files to input. The error I'm receiving is Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0 at ESPInterpreter.main(ESPInterpreter.java:278) I appreciate any help as I have no idea what I'm doing. Thanks.

Add a control to check if args is null , right before calling System.out.println("file name is "+ args[0]);

if(args==null){
    System.out.println("args is null. Exit from program");
    System.exit(0);
}

System.out.println("file name is "+ args[0]);
ESPInterpreter readFile = new ESPInterpreter();
readFile.read(args[0]);

ESPInterpreter sample = new ESPInterpreter();

sample.ShowHowToUseVariableClass();

For what ArrayIndexOutOfBoundsException is read What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?

Your problem is that you are using the program arguments without checking if any is provided. When you start the program they must be already set. (for example in the command line java ESPInterpreter myFile.txt )

To fix this you can add an check if the are really set:

public static void main( String [ ] args ) {
    if(args.length > 0) {
        // Add your code here
    } else {
        System.out.println("The required argument for the filename isn't set!");
    }
}

But in your case it would be better to ask the user when the program is already started to enter a filename:

public static void main(String[] args) {
    Scanner input= new Scanner(System.in);
    System.out.println("Enter the filename:");
    String file = input.nextLine();

    System.out.println("file name is "+ file);
    ESPInterpreter readFile = new ESPInterpreter();
    readFile.read(file);
    ESPInterpreter sample = new ESPInterpreter();
    sample.ShowHowToUseVariableClass();
}

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