Question

In: Computer Science

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;
  
   /*
       Getters and Setters for
       street address, city, state, zip code,
       bedrooms, and bathrooms.
   */  
  
   public String getStreetAddress() {
       return streetAddress;
   }
  
   public void setStreetAddress(String streetAddress) {
       this.streetAddress = streetAddress;
   }
  
   public String getCity() {
       return city;
   }
  
   public void setCity(String city) {
       this.city = city;
   }
  
   public String getState() {
       return state;
   }
  
   public void setState(String state) {
       this.state = state;
   }
  
   public String getZip() {
       return zipCode;
   }
  
   public void setZip(String zipCode) {
       this.zipCode = zipCode;
   }
  
   public int getBedrooms() {
       return bedrooms;
   }
  
   public void setBedrooms(int bedrooms) {
       this.bedrooms = bedrooms;
   }
  
   public double getBathrooms() {
       return bathrooms;
   }
  
   public void setBathrooms(double bathrooms) {
       this.bathrooms = bathrooms;
   }
  
   /*
   no arg constructor
   no parameters
   */
  
   public Dwelling() {
       /*
       Declaring Variables
       */
      
       streetAddress = "";
       city = "";
       state = "";
       zipCode = "";
       bedrooms = 0;
       bathrooms = 0.0;
   }
  
   public String toString() {
       return streetAddress + "|" + city + "|" + state +"|" +
               zipCode + "|" + bedrooms + "|" + bathrooms;
   }

   class House extends Dwelling{
       /*
       Declaring Variables
       */
       double acreage;
       int garageSize;
       /*
       no arg constructor
       no parameters
       */
       public House() {
           super();
           acreage = 0.0;
           garageSize = 0;
       }
       public String toString() {
           return (super.toString()+ "|" + acreage + "|" + garageSize);
       }
   }
  
   class Apartment extends Dwelling{
       /*
       Declaring Variables
       */
       String aptNum;
       boolean laundry;
      
       /*
       no arg constructor
       no parameters
       */
       public Apartment() {
           super();
           aptNum = "";
           laundry = false;
       }
       public String toString() {
           return (super.toString() + "|" + aptNum + "|" + laundry);
       }
   }
  
   public static class DriverTest{
       /*
       command line arguments
       */
      
       public static void main(String[] args) throws FileNotFoundException, IOException {
           File file = new File(args[0]);
           BufferedReader buffReader = new BufferedReader(new FileReader(file));
          
           System.out.print("Print output 1");
           ArrayList <Dwelling> listOfLines = new ArrayList <>();
          
           String line = buffReader.readLine();
          
           Dwelling d1[] = new Dwelling[5];
           int i = 0;
          
           while (line != null && i<5) {
               d1[i] = new Dwelling();
               d1[i].setStreetAddress(line);
               line = buffReader.readLine();
               d1[i].setCity(line);
               line = buffReader.readLine();
               d1[i].setState(line);
               line = buffReader.readLine();
               d1[i].setZip(line);
               line = buffReader.readLine();
               int bed = Integer.parseInt(line);
               d1[i].setBedrooms(bed);
               line = buffReader.readLine();
               d1[i].setBathrooms(Double.parseDouble(line));
               listOfLines.add(d1[i]);
               i++;
              
               line = buffReader.readLine();
               line = buffReader.readLine();
               line = buffReader.readLine();
               line = buffReader.readLine();
           }
           buffReader.close();
          
           for(Dwelling dwl: listOfLines) {
               /*
               Prints data in the console
               */
               System.out.println(dwl);
           }
           FileWriter write = new FileWriter(file);
          
           for(Dwelling str: listOfLines) {
               /*
               Writes data into the file
               */
               write.write(str + System.lineSeparator());
           }
           write.close();
       }
  
  
  
   }
  
}

Solutions

Expert Solution

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;

/*
    Getters and Setters for
    street address, city, state, zip code,
    bedrooms, and bathrooms.
*/  

public String getStreetAddress() {
    return streetAddress;
}

public void setStreetAddress(String streetAddress) {
    this.streetAddress = streetAddress;
}

public String getCity() {
    return city;
}

public void setCity(String city) {
    this.city = city;
}

public String getState() {
    return state;
}

public void setState(String state) {
    this.state = state;
}

public String getZip() {
    return zipCode;
}

public void setZip(String zipCode) {
    this.zipCode = zipCode;
}

public int getBedrooms() {
    return bedrooms;
}

public void setBedrooms(int bedrooms) {
    this.bedrooms = bedrooms;
}

public double getBathrooms() {
    return bathrooms;
}

public void setBathrooms(double bathrooms) {
    this.bathrooms = bathrooms;
}

/*
no arg constructor
no parameters
*/

public Dwelling() {
    /*
    Declaring Variables
    */
   
    streetAddress = "";
    city = "";
    state = "";
    zipCode = "";
    bedrooms = 0;
    bathrooms = 0.0;
}

public String toString() {
    return streetAddress + "|" + city + "|" + state +"|" +
            zipCode + "|" + bedrooms + "|" + bathrooms;
}

class House extends Dwelling{
    /*
    Declaring Variables
    */
    double acreage;
    int garageSize;
    /*
    no arg constructor
    no parameters
    */
    public House() {
        super();
        acreage = 0.0;
        garageSize = 0;
    }
    public String toString() {
        return (super.toString()+ "|" + acreage + "|" + garageSize);
    }
}

class Apartment extends Dwelling{
    /*
    Declaring Variables
    */
    String aptNum;
    boolean laundry;
   
    /*
    no arg constructor
    no parameters
    */
    public Apartment() {
        super();
        aptNum = "";
        laundry = false;
    }
    public String toString() {
        return (super.toString() + "|" + aptNum + "|" + laundry);
    }
}

}
public  class DriverTest{
    /*
    command line arguments
    */
   
    public static void main(String[] args) throws FileNotFoundException, IOException {
        if(args==null || args.length==0) {
                System.out.println("ERROR: Please pass the command line arguments to run the program successfully");
                return;
        }
        File file = new File(args[0]);
        BufferedReader buffReader = new BufferedReader(new FileReader(file));
       
        System.out.print("Print output 1");
        ArrayList <Dwelling> listOfLines = new ArrayList <>();
       
        String line = buffReader.readLine();
       
        Dwelling d1[] = new Dwelling[5];
        int i = 0;
       
        while (line != null && i<5) {
            d1[i] = new Dwelling();
            d1[i].setStreetAddress(line);
            line = buffReader.readLine();
            d1[i].setCity(line);
            line = buffReader.readLine();
            d1[i].setState(line);
            line = buffReader.readLine();
            d1[i].setZip(line);
            line = buffReader.readLine();
            int bed = Integer.parseInt(line);
            d1[i].setBedrooms(bed);
            line = buffReader.readLine();
            d1[i].setBathrooms(Double.parseDouble(line));
            listOfLines.add(d1[i]);
            i++;
           
            line = buffReader.readLine();
            line = buffReader.readLine();
            line = buffReader.readLine();
            line = buffReader.readLine();
        }
        buffReader.close();
       
        for(Dwelling dwl: listOfLines) {
            /*
            Prints data in the console
            */
            System.out.println(dwl);
        }
        FileWriter write = new FileWriter(file);
       
        for(Dwelling str: listOfLines) {
            /*
            Writes data into the file
            */
            write.write(str + System.lineSeparator());
        }
        write.close();
    }



}

Here the issue is you need to pass the name of the file from the command line arguments than only program works.. Otherwise it will give an error. Please pass the properr file name it will work

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

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...
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...
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 =...
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]);...
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(...
I keep getting an error that I cannot figure out with the below VS2019 windows forms...
I keep getting an error that I cannot figure out with the below VS2019 windows forms .net framework windows forms error CS0029 C# Cannot implicitly convert type 'bool' to 'string' It appears to be this that is causing the issue string id; while (id = sr.ReadLine() != null) using System; using System.Collections.Generic; using System.IO; using System.Windows.Forms; namespace Dropbox13 { public partial class SearchForm : Form { private List allStudent = new List(); public SearchForm() { InitializeComponent(); } private void SearchForm_Load(object...
In java, I keep getting the error below and I can't figure out what i'm doing...
In java, I keep getting the error below and I can't figure out what i'm doing wrong. Any help would be appreciated. 207: error: not a statement allocationMatrix[i][j];
Can anyone merge these two java programs I keep getting an error can't find main classes....
Can anyone merge these two java programs I keep getting an error can't find main classes. MySorts.java public class MySorts { public static void insertSort(int[] arr) { int i, temp, j; for (i = 1; i < arr.length; i++) { temp = arr[i]; j = i - 1; while (j >= 0 && arr[j] > temp) { arr[j + 1] = arr[j]; j = j - 1; } arr[j + 1] = temp; } } public static void selectSort(int[] arr)...
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);...
I keep getting the same error Error Code: 1822. Failed to add the foreign key constraint....
I keep getting the same error Error Code: 1822. Failed to add the foreign key constraint. Missing index for constraint 'test_ibfk_5' in the referenced table 'appointment', can you please tell me what is wrong with my code: -- Table III: Appointment = (site_name [fk7], date, time) -- fk7: site_name -> Site.site_name DROP TABLE IF EXISTS appointment; CREATE TABLE appointment (    appt_site VARCHAR(100) NOT NULL, appt_date DATE NOT NULL, appt_time TIME NOT NULL, PRIMARY KEY (appt_date, appt_time), FOREIGN KEY (appt_site)...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT