Question

In: Computer Science

Why am I getting this error: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 0 out of bounds...

Why am I getting this error:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0

at HW3.main(HW3.java:6)

The code:

import java.io.FileWriter;

import java.io.IOException;

public class HW3 {

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

// 0th argument contains the name of algorithm

String algo = args[0];

// 1st argument contains the name of file

// Make a new file

FileWriter fw = new FileWriter(args[1]);

if (algo.equals("p1")) {

// 2nd argument comes in the form of string.

// convert it to intger and run a loop

for (int i = 1; i <= Integer.parseInt(args[2]); i++) {

double[] x = new double[(int) Math.pow(10, i)];

// use start and end for recording time

long start = System.currentTimeMillis();

prefixAverage1(x);

long end = System.currentTimeMillis();

double totalTime = Math.log10(end - start);

fw.write(String.valueOf(totalTime));

String newLine = System.getProperty("line.separator");

fw.write(newLine);

}

} else if (algo.equals("p2")) {

for (int i = 1; i <= Integer.parseInt(args[2]); i++) {

double[] x = new double[(int) Math.pow(10, i)];

long start = System.currentTimeMillis();

prefixAverage2(x);

long end = System.currentTimeMillis();

double totalTime = Math.log10(end - start);

fw.write(String.valueOf(totalTime));

String newLine = System.getProperty("line.separator");

fw.write(newLine);

}

} else if (algo.equals("e1")) {

for (int i = 1; i <= Integer.parseInt(args[2]); i++) {

int[] x = new int[(int) Math.pow(10, i)];

long start = System.currentTimeMillis();

example1(x);

long end = System.currentTimeMillis();

double totalTime = Math.log10(end - start);

fw.write(String.valueOf(totalTime));

String newLine = System.getProperty("line.separator");

fw.write(newLine);

}

} else if (algo.equals("e2")) {

for (int i = 1; i <= Integer.parseInt(args[2]); i++) {

int[] x = new int[(int) Math.pow(10, i)];

long start = System.currentTimeMillis();

example2(x);

long end = System.currentTimeMillis();

double totalTime = Math.log10(end - start);

fw.write(String.valueOf(totalTime));

String newLine = System.getProperty("line.separator");

fw.write(newLine);

}

} else if (algo.equals("e3")) {

for (int i = 1; i <= Integer.parseInt(args[2]); i++) {

int[] x = new int[(int) Math.pow(10, i)];

long start = System.currentTimeMillis();

example3(x);

long end = System.currentTimeMillis();

double totalTime = Math.log10(end - start);

fw.write(String.valueOf(totalTime));

String newLine = System.getProperty("line.separator");

fw.write(newLine);

}

} else if (algo.equals("e4")) {

for (int i = 1; i <= Integer.parseInt(args[2]); i++) {

int[] x = new int[(int) Math.pow(10, i)];

long start = System.currentTimeMillis();

example4(x);

long end = System.currentTimeMillis();

double totalTime = Math.log10(end - start);

fw.write(String.valueOf(totalTime));

String newLine = System.getProperty("line.separator");

fw.write(newLine);

}

} else if (algo.equals("e5")) {

for (int i = 1; i <= Integer.parseInt(args[2]); i++) {

int[] x = new int[(int) Math.pow(10, i)];

long start = System.currentTimeMillis();

// You can take a new array here, I am just running it for x here

example5(x, x);

long end = System.currentTimeMillis();

double totalTime = Math.log10(end - start);

fw.write(String.valueOf(totalTime));

String newLine = System.getProperty("line.separator");

fw.write(newLine);

}

}

fw.close();

}

public static double[] prefixAverage1(double[] x) {

int n = x.length;

double[] a = new double[n];

for (int j = 0; j < n; j++) {

double total = 0;

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

total += x[i];

a[j] = total / (j + 1);

}

}

return a;

}

public static double[] prefixAverage2(double[] x) {

int n = x.length;

double[] a = new double[n];

double total = 0;

for (int j = 0; j < n; j++) {

total += x[j];

a[j] = total / (j + 1);

}

return a;

}

public static int example1(int[] arr) {

int n = arr.length, total = 0;

for (int j = 0; j < n; j++)

total += arr[j];

return total;

}

public static int example2(int[] arr) {

int n = arr.length, total = 0;

for (int j = 0; j < n; j += 2)

total += arr[j];

return total;

}

public static int example3(int[] arr) {

int n = arr.length, total = 0;

for (int j = 0; j < n; j++)

for (int k = 0; k <= j; k++)

total += arr[j];

return total;

}

public static int example4(int[] arr) {

int n = arr.length, prefix = 0, total = 0;

for (int j = 0; j < n; j++) {

prefix += arr[j];

total += prefix;

}

return total;

}

public static int example5(int[] first, int[] second) {

int n = first.length, count = 0;

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

int total = 0;

for (int j = 0; j < n; j++)

for (int k = 0; k <= j; k++)

total += first[k];

if (second[i] == total) count++;

}

return count;

}

}

Solutions

Expert Solution

import java.io.FileWriter;
import java.io.IOException;

public class HW3 {
        public static void main(String[] args) throws IOException {
                // here you need to pass the 3 command  line arguments to run this program
                // if you dont pass you will get this exception only
                if(args==null || args.length<3) {
                        System.out.println("ERROR!: Please pass the required arguments from command line");
                        return;
                }
// 0th argument contains the name of algorithm
                String algo = args[0];
// 1st argument contains the name of file
// Make a new file
                FileWriter fw = new FileWriter(args[1]);

                if (algo.equals("p1")) {

// 2nd argument comes in the form of string.

// convert it to intger and run a loop

                        for (int i = 1; i <= Integer.parseInt(args[2]); i++) {

                                double[] x = new double[(int) Math.pow(10, i)];

// use start and end for recording time

                                long start = System.currentTimeMillis();

                                prefixAverage1(x);

                                long end = System.currentTimeMillis();

                                double totalTime = Math.log10(end - start);

                                fw.write(String.valueOf(totalTime));

                                String newLine = System.getProperty("line.separator");

                                fw.write(newLine);

                        }

                } else if (algo.equals("p2")) {

                        for (int i = 1; i <= Integer.parseInt(args[2]); i++) {

                                double[] x = new double[(int) Math.pow(10, i)];

                                long start = System.currentTimeMillis();

                                prefixAverage2(x);

                                long end = System.currentTimeMillis();

                                double totalTime = Math.log10(end - start);

                                fw.write(String.valueOf(totalTime));

                                String newLine = System.getProperty("line.separator");

                                fw.write(newLine);

                        }

                } else if (algo.equals("e1")) {

                        for (int i = 1; i <= Integer.parseInt(args[2]); i++) {

                                int[] x = new int[(int) Math.pow(10, i)];

                                long start = System.currentTimeMillis();

                                example1(x);

                                long end = System.currentTimeMillis();

                                double totalTime = Math.log10(end - start);

                                fw.write(String.valueOf(totalTime));

                                String newLine = System.getProperty("line.separator");

                                fw.write(newLine);

                        }

                } else if (algo.equals("e2")) {

                        for (int i = 1; i <= Integer.parseInt(args[2]); i++) {

                                int[] x = new int[(int) Math.pow(10, i)];

                                long start = System.currentTimeMillis();

                                example2(x);

                                long end = System.currentTimeMillis();

                                double totalTime = Math.log10(end - start);

                                fw.write(String.valueOf(totalTime));

                                String newLine = System.getProperty("line.separator");

                                fw.write(newLine);

                        }

                } else if (algo.equals("e3")) {

                        for (int i = 1; i <= Integer.parseInt(args[2]); i++) {

                                int[] x = new int[(int) Math.pow(10, i)];

                                long start = System.currentTimeMillis();

                                example3(x);

                                long end = System.currentTimeMillis();

                                double totalTime = Math.log10(end - start);

                                fw.write(String.valueOf(totalTime));

                                String newLine = System.getProperty("line.separator");

                                fw.write(newLine);

                        }

                } else if (algo.equals("e4")) {

                        for (int i = 1; i <= Integer.parseInt(args[2]); i++) {

                                int[] x = new int[(int) Math.pow(10, i)];

                                long start = System.currentTimeMillis();

                                example4(x);

                                long end = System.currentTimeMillis();

                                double totalTime = Math.log10(end - start);

                                fw.write(String.valueOf(totalTime));

                                String newLine = System.getProperty("line.separator");

                                fw.write(newLine);

                        }

                } else if (algo.equals("e5")) {

                        for (int i = 1; i <= Integer.parseInt(args[2]); i++) {

                                int[] x = new int[(int) Math.pow(10, i)];

                                long start = System.currentTimeMillis();

// You can take a new array here, I am just running it for x here

                                example5(x, x);

                                long end = System.currentTimeMillis();

                                double totalTime = Math.log10(end - start);

                                fw.write(String.valueOf(totalTime));

                                String newLine = System.getProperty("line.separator");

                                fw.write(newLine);

                        }

                }

                fw.close();

        }

        public static double[] prefixAverage1(double[] x) {

                int n = x.length;

                double[] a = new double[n];

                for (int j = 0; j < n; j++) {

                        double total = 0;

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

                                total += x[i];

                                a[j] = total / (j + 1);

                        }

                }

                return a;

        }

        public static double[] prefixAverage2(double[] x) {

                int n = x.length;

                double[] a = new double[n];

                double total = 0;

                for (int j = 0; j < n; j++) {

                        total += x[j];

                        a[j] = total / (j + 1);

                }

                return a;

        }

        public static int example1(int[] arr) {

                int n = arr.length, total = 0;

                for (int j = 0; j < n; j++)

                        total += arr[j];

                return total;

        }

        public static int example2(int[] arr) {

                int n = arr.length, total = 0;

                for (int j = 0; j < n; j += 2)

                        total += arr[j];

                return total;

        }

        public static int example3(int[] arr) {

                int n = arr.length, total = 0;

                for (int j = 0; j < n; j++)

                        for (int k = 0; k <= j; k++)

                                total += arr[j];

                return total;

        }

        public static int example4(int[] arr) {

                int n = arr.length, prefix = 0, total = 0;

                for (int j = 0; j < n; j++) {

                        prefix += arr[j];

                        total += prefix;

                }

                return total;

        }

        public static int example5(int[] first, int[] second) {

                int n = first.length, count = 0;

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

                        int total = 0;

                        for (int j = 0; j < n; j++)

                                for (int k = 0; k <= j; k++)

                                        total += first[k];

                        if (second[i] == total)
                                count++;

                }

                return count;

        }

}

Issue:

       // here you need to pass the 3 command line arguments to run this program
       // if you dont pass you will get this exception only
       if(args==null || args.length<3) {
           System.out.println("ERROR!: Please pass the required arguments from command line");
           return;
       }

Note : Please comment below if you have concerns. I am here to help you

If you like my answer please rate and help me it is very Imp for me


Related Solutions

I keep getting this error, Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 0 out of bounds for...
I keep getting this error, Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0    at simpleInheritance/simpInher.Dwelling$DriverTest.main(Dwelling.java:146) Can someone help me fix it? import java.io.BufferedReader;    import java.io.FileNotFoundException;    import java.io.FileReader;    import java.util.*;    import java.io.*;    import java.io.FileWriter;    import java.io.IOException;    class Dwelling {    /*    Declaring Variables    */    String streetAddress;    String city;    String state;    String zipCode;    int bedrooms;    double bathrooms;       /*   ...
I'm getting this error: Exception in thread "main" java.lang.NoSuchMethodError: main I tried using public static void...
I'm getting this error: Exception in thread "main" java.lang.NoSuchMethodError: main I tried using public static void main(String[] args){ but that negates all of the methods that I try to write. I'm just trying to make it so that I can enter values. Thanks. Code below: import java.util.Scanner; public class DataSet2 { private double value; private double sum; private int count; public void add(double value){    System.out.println("Enter values, enter -1 to finish");    Scanner scan = new Scanner(System.in);    value =...
I keep get this exception error Exception in thread "main" java.lang.NullPointerException    at Quadrilateral.returnCoordsAsString(Quadrilateral.java:44)    at...
I keep get this exception error Exception in thread "main" java.lang.NullPointerException    at Quadrilateral.returnCoordsAsString(Quadrilateral.java:44)    at Quadrilateral.toString(Quadrilateral.java:51)    at tester1.main(tester1.java:39) In this program I needed to make a Point class to create a coordinate square from x and y. I also needed to make a Quadrilateral class that has an instance reference variable to Point .The Quadrilateral class then inherits itself to other classes or in this case other shapes like square, trapazoid. I thought I did it right but...
when i run the program on eclipse it gives me this error: Exception in thread "main"...
when i run the program on eclipse it gives me this error: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0    at SIM.main(SIM.java:12) how do I fix that ? (please fix it ) import java.util.*; import java.util.Scanner; import java.util.ArrayList; import java.io.File; import java.io.FileNotFoundException; import java.lang.Math; public class SIM{    public static void main(String[] args) throws FileNotFoundException {       int cacheSize = Integer.parseInt( args[1] ); int assoc = Integer.parseInt( args[2] ); int replacement = Integer.parseInt(...
Why am I getting this error using 000webhost , but I do not get this error...
Why am I getting this error using 000webhost , but I do not get this error running XAMPP? Warning: Cannot modify header information - headers already sent by (output started at /storage/ssd2/006/14881006/public_html/test/index.php:1) in /storage/ssd2/006/14881006/public_html/test/index.php on line 8 Code is below. ******************************************************************************************************************** <!DOCTYPE html> <?php    //Determine if the submit button has been clicked to set the cookie name and value    if (isset($_POST['name'])){            $cookie_name = $_POST['name'];            $cookie_value = $_POST['value'];            setcookie($cookie_name, $cookie_value,...
I am getting an error at linen 57 and can't figure out how to fix it....
I am getting an error at linen 57 and can't figure out how to fix it. // Java program to read a CSV file and display the min, max, and average of numbers in it. import java.io.File; import java.io.FileNotFoundException; import java.util.Arrays; import java.util.Scanner; public class Main {     // method to determine and return the minimum number from the array     public static int minimum(int numbers[])     {         int minIdx = 0;         for(int i=1;i<numbers.length;i++)         {             if((minIdx...
My code works in eclipse, but not in Zybooks. I keep getting this error. Exception in...
My code works in eclipse, but not in Zybooks. I keep getting this error. Exception in thread "main" java.util.NoSuchElementException at java.base/java.util.Scanner.throwFor(Scanner.java:937) at java.base/java.util.Scanner.next(Scanner.java:1478) at Main.main(Main.java:34) Your output Welcome to the food festival! Would you like to place an order? Expected output This test case should produce no output in java import java.util.Scanner; public class Main {    public static void display(String menu[])    {        for(int i=0; i<menu.length; i++)        {            System.out.println (i + " - " + menu[i]);...
Why am I getting the error: ValueError: The truth value of a Series is ambiguous. Use...
Why am I getting the error: ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all() Fielding is a DataFrame, but I am not sure why I am getting this error. Any help would be appreciated! RAR = [] for i in range(0,len(Fielding)): position = (Fielding['POS'][i]) value = 0 if position == 'C': value = (9.0/150.0) * (Fielding['GS'][i]) elif position == 'SS': value = (7.0/150.0) * (Fielding['GS'][i]) elif position == '2B': value = (3.0/150.0)...
This is in Python I am getting an error when I run this program, also I...
This is in Python I am getting an error when I run this program, also I cannot get any output. Please help! #Input Section def main(): name=input("Please enter the customer's name:") age=int(input("Enter age of the customer: ")) number_of_traffic_violations=int(input("Enter the number of traffic violations: ")) if age <=15 and age >= 105: print('Invalid Entry') if number_of_traffic_violations <0: print('Invalid Entry') #Poccessing Section def Insurance(): if age < 25 and number_of_tickets >= 4 and riskCode == 1: insurancePrice = 480 elif age >=...
Syntax error in C. I am not familiar with C at all and I keep getting...
Syntax error in C. I am not familiar with C at all and I keep getting this one error "c error expected identifier or '(' before } token" Please show me where I made the error. The error is said to be on the very last line, so the very last bracket #include #include #include #include   int main(int argc, char*_argv[]) {     int input;     if (argc < 2)     {         input = promptUserInput();     }     else     {         input = (int)strtol(_argv[1],NULL, 10);     }     printResult(input);...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT