Array out of bounds exception when outputting array to file

Could someone please tell me why i'm getting this array out of bounds exception?
public class Assignment1 {
public static void main(String[] names)throws IOException {
BufferedReader keyboard = null;
String userChoice;
String inputFile = null;
String studentData;
String searchFile = null;
String searchName;
String stringIn;
PrintWriter outputFile;
FileWriter fWriter = null;
BufferedReader fReader = null;
int first;
int last;
int mid;
int midValue;
int i;
int number;
// creates keyboard as a buffered input stream
keyboard = new BufferedReader(new InputStreamReader(System.in));
//prompts user to choose 1 or 2 to make a corresponding choice
System.out.println("Please Enter: ");
System.out.println("1 to Create a File: ");
System.out.println("2 to Search a File: ");
userChoice = keyboard.readLine(); //user enters 1 or 2
// converts a String into an int value
number = Integer.parseInt(userChoice);
fReader = new BufferedReader(new FileReader("studentData.txt"));
if (number == 1) {          
System.out.println("Please Enter the File Name to Create: ");
studentData = keyboard.readLine();
File file = new File("studentData.txt");
fWriter = new FileWriter("studentData.txt");
outputFile = new PrintWriter(fWriter);
names = new String[200];
i=0;
//keep looping till sentinel
while (studentData != "end" && studentData != null &&
i < names.length) {
if (studentData.equals("end")) break; //break and call sort
System.out.println("Enter a name and press Enter. " +
"Type 'end' and press Enter when done: ");
studentData = keyboard.readLine();
//loop for putting the names into the array
for(i=0; i<names.length; i++) ;
outputFile.println(names);
} [b]outputFile.close();

package assignment1;
import java.io.*;
import java.util.*;
public class Assignment1 {
    public static void main(String[] names)throws IOException {
       BufferedReader keyboard = null;
       String userChoice;
       String inputFile = null;
       String studentData;
       String searchFile = null;
       String searchName;
       String stringIn;
       PrintWriter outputFile;
       FileWriter fWriter = null;
       BufferedReader fReader = null;
       int first;
       int last;
       int mid;
       int midValue;
       int i;
       int number;
       // creates keyboard as a buffered input stream
       keyboard = new BufferedReader(new InputStreamReader(System.in));
       //prompts user to choose 1 or 2 to make a corresponding choice
       System.out.println("Please Enter: ");
       System.out.println("1 to Create a File: ");
       System.out.println("2 to Search a File: ");
       userChoice = keyboard.readLine();    //user enters 1 or 2
       // converts a String into an int value
       number = Integer.parseInt(userChoice); 
       fReader = new BufferedReader(new FileReader("studentData.txt"));
       if (number == 1) {          
           System.out.println("Please Enter the File Name to Create: ");
           studentData = keyboard.readLine();
           File file = new File("studentData.txt");
           fWriter = new FileWriter("studentData.txt");
           outputFile = new PrintWriter(fWriter);
           names = new String[200];
           i=0;
            //keep looping till sentinel
            while (studentData.equals("end") && studentData != null &&
                   i < names.length) {
               if (studentData.equals("end")) break;   //break and call sort
               System.out.println("Enter a name and press Enter. " +
                                   "Type 'end' and press Enter when done: ");
                studentData = keyboard.readLine();
                //loop for putting the names into the array
                for(i=0; i<names.length; i++) ;
                outputFile.println(names);
} outputFile.close();
//call selectionSort() to order the array
     selectionSort(names);
     // Now output to a file.
fWriter = new FileWriter("studentData.txt");
outputFile = new PrintWriter(fWriter);
} else if (number == 2) {
System.out.println("Please Enter a File Name to search: ");
searchFile = keyboard.readLine();
inputFile = ("studentData.txt");
} if (searchFile == "studentData.txt") {                      
// Input from a file. See input file streams.
fReader = new BufferedReader(new FileReader("studentData.txt"));
System.out.println("Please enter a Name to search for: ");
searchName = keyboard.readLine();
//enter binary search code
first = 0;
last = 199;
while (first < last)
mid = (first + last)/2; // Compute mid point.
if (searchName.compareTo(names[mid]) < 0) {
last = mid; // repeat search in bottom half.
} else if (searchName.compareTo(names[mid]) > 0) {
first = mid + 1; // Repeat search in top half.
} else {
// Found it.
System.out.println("The Name IS in the file.");
} // did not find it.
System.out.println("The Name IS NOT in the file.");
} else //if userChoice != 1 or 2, re-prompt then start over
System.out.println("Please Enter 1 or 2 or correctly " +
"enter an existing file!!");
// fWriter = new FileWriter("studentdata.txt");
//outputFile = new PrintWriter(fWriter); //output
public static void selectionSort(String[] names) {
//use compareTo!!!!
int smallIndex;
int pass, j = 1, n = names.length;
String temp;
for (pass = 0; pass < n-1; pass++)
//Code for Do/While Loop
do {
//scan the sublist starting at index pass
smallIndex = pass;
//jtraverses sublist names[pass+1] to names[n-1]
for (j = pass+1; j < n; j++)
//if smaller string found, smallIndex=that position
if (names[j].compareTo(names[smallIndex]) < 0)
smallIndex = j;
temp = names[pass]; //swap
names[pass] =names[smallIndex];
names[smallIndex] = temp;
} while (j <= names.length);
//File file = new File("studentData.txt");
This is the output window:
init:
deps-jar:
compile:
run:
Please Enter:
1 to Create a File:
2 to Search a File:
1
Please Enter the File Name to Create:
test
Exception in thread "main" java.lang.NullPointerException
at assignment1.Assignment1.selectionSort(Assignment1.java:134)
at assignment1.Assignment1.main(Assignment1.java:73)
Java Result: 1
BUILD SUCCESSFUL (total time: 9 seconds)

Similar Messages

  • Out of bounds exception although increasing heap space

    Hello,
    In my java application, there is a gif file with the size 6000 X 3500 . This file is 536 KB and i use this file with scroll bar.
    My question is that although I increased heap space to 512, it still keep going to give "out of bounds" exception when i try to set new dimention to the frame bigger than (800, 1000).
    How can I use my gif file with bigger frame?

    There is no such exception.
    Are you talking about ArrayIndexOutOfBoundsException?
    OutOfMemoryError?
    Something else?

  • Please iam getting index out of bound exception can any body solve my probl

    Dear all
    iam doing aproject in swing in that one class iam using the below method. Iam getting index out of bound exception. Actually iam trying to access the more that 50mb file at that time its giving out of memory exception after that iam using this method now its giving index out of bound exception, when it is going second time in the while loop. can any body solve my problem. Please give me the solution . Ill be very thankful to you.
    public Vector getFileContent(File fileObj){
    FileInputStream fis = null;
    DataInputStream dis = null;
    Vector v = new Vector();
    byte[] data = null;
    int pos = 0;
    int chunk = 10000;
    int sizePos = 0;
    try{
    fis = new FileInputStream(fileObj);
    int size = (int)fileObj.length();
    dis = new DataInputStream(fis);
    int k = 1;
    if(size <10000){
    data = new byte[size];
    //v.addElement(dis.readFully(data));
    dis.readFully(data);
    v.addElement(data);
    else {
    while(pos < size){
    sizePos = size - chunk*k;
    if(sizePos > 10000){
    chunk = 10000;
    else{
    chunk = sizePos;
    data = new byte[chunk];
    dis.read(data, pos, chunk);
    v.addElement(data);
    System.gc();
    pos = pos + chunk + 1;
    regards,
    surya

    pos = pos + chunk + 1;Why the +1??

  • Java Index Out Of Bounds Exception error

    In the Query Designer when I choose access type for Result value as Master data, and execute, I get the following java Index Out Of Bounds Exception error:
    com.sap.ip.bi.webapplications.runtime.controller.MessageException: Error while generating HTML
         at com.sap.ip.bi.webapplications.runtime.impl.Page.processRequest(Page.java:2371)
         at com.sap.ip.bi.webapplications.runtime.impl.Page.doServerRedirect(Page.java:2642)
         at com.sap.ip.bi.webapplications.runtime.impl.Page.doProcessRequest(Page.java:2818)
         at com.sap.ip.bi.webapplications.runtime.impl.Page.processRequest(Page.java:2293)
         at com.sap.ip.bi.webapplications.runtime.controller.impl.Controller.doProcessRequest(Controller.java:841)
         at com.sap.ip.bi.webapplications.runtime.controller.impl.Controller.processRequest(Controller.java:775)
         at com.sap.ip.bi.webapplications.runtime.jsp.portal.services.BIRuntimeService.handleRequest(BIRuntimeService.java:412)
         at com.sap.ip.bi.webapplications.runtime.jsp.portal.components.LauncherComponent.doContent(LauncherComponent.java:21)
         at com.sapportals.portal.prt.component.AbstractPortalComponent.serviceDeprecated(AbstractPortalComponent.java:209)
         at com.sapportals.portal.prt.component.AbstractPortalComponent.service(AbstractPortalComponent.java:114)
         at com.sapportals.portal.prt.core.PortalRequestManager.callPortalComponent(PortalRequestManager.java:328)
         at com.sapportals.portal.prt.core.PortalRequestManager.dispatchRequest(PortalRequestManager.java:136)
         at com.sapportals.portal.prt.core.PortalRequestManager.dispatchRequest(PortalRequestManager.java:189)
         at com.sapportals.portal.prt.component.PortalComponentResponse.include(PortalComponentResponse.java:215)
         at com.sapportals.portal.prt.pom.PortalNode.service(PortalNode.java:645)
         at com.sapportals.portal.prt.core.PortalRequestManager.callPortalComponent(PortalRequestManager.java:328)
         at com.sapportals.portal.prt.core.PortalRequestManager.dispatchRequest(PortalRequestManager.java:136)
         at com.sapportals.portal.prt.core.PortalRequestManager.dispatchRequest(PortalRequestManager.java:189)
         at com.sapportals.portal.prt.core.PortalRequestManager.runRequestCycle(PortalRequestManager.java:753)
         at com.sapportals.portal.prt.connection.ServletConnection.handleRequest(ServletConnection.java:240)
         at com.sapportals.portal.prt.dispatcher.Dispatcher$doService.run(Dispatcher.java:522)
         at java.security.AccessController.doPrivileged(Native Method)
         at com.sapportals.portal.prt.dispatcher.Dispatcher.service(Dispatcher.java:405)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
         at com.sap.engine.services.servlets_jsp.server.servlet.InvokerServlet.service(InvokerServlet.java:156)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
         at com.sap.engine.services.servlets_jsp.server.HttpHandlerImpl.runServlet(HttpHandlerImpl.java:401)
         at com.sap.engine.services.servlets_jsp.server.HttpHandlerImpl.handleRequest(HttpHandlerImpl.java:266)
         at com.sap.engine.services.httpserver.server.RequestAnalizer.startServlet(RequestAnalizer.java:387)
         at com.sap.engine.services.httpserver.server.RequestAnalizer.startServlet(RequestAnalizer.java:365)
         at com.sap.engine.services.httpserver.server.RequestAnalizer.invokeWebContainer(RequestAnalizer.java:944)
         at com.sap.engine.services.httpserver.server.RequestAnalizer.handle(RequestAnalizer.java:266)
         at com.sap.engine.services.httpserver.server.Client.handle(Client.java:95)
         at com.sap.engine.services.httpserver.server.Processor.request(Processor.java:160)
         at com.sap.engine.core.service630.context.cluster.session.ApplicationSessionMessageListener.process(ApplicationSessionMessageListener.java:33)
         at com.sap.engine.core.cluster.impl6.session.MessageRunner.run(MessageRunner.java:41)
         at com.sap.engine.core.thread.impl3.ActionObject.run(ActionObject.java:37)
         at java.security.AccessController.doPrivileged(Native Method)
         at com.sap.engine.core.thread.impl3.SingleThread.execute(SingleThread.java:100)
         at com.sap.engine.core.thread.impl3.SingleThread.run(SingleThread.java:170)
    Caused by: com.sap.ip.bi.base.exception.BIBaseRuntimeException: Error while generating HTML
         at com.sap.ip.bi.webapplications.ui.items.UiItem.render(UiItem.java:380)
         at com.sap.ip.bi.webapplications.runtime.rendering.impl.ContainerNode.render(ContainerNode.java:62)
         at com.sap.ip.bi.webapplications.runtime.rendering.impl.PageAssemblerRenderingRoot.processRendering(PageAssemblerRenderingRoot.java:50)
         at com.sap.ip.bi.webapplications.runtime.impl.Page.processRenderingRootNode(Page.java:3188)
         at com.sap.ip.bi.webapplications.runtime.impl.Page.processRendering(Page.java:2923)
         at com.sap.ip.bi.webapplications.runtime.impl.Page.doProcessRequest(Page.java:2877)
         at com.sap.ip.bi.webapplications.runtime.impl.Page.processRequest(Page.java:2293)
         ... 39 more
    Caused by: java.lang.IndexOutOfBoundsException: fromIndex = -7
         at java.util.SubList.<init>(AbstractList.java:702)
         at java.util.RandomAccessSubList.<init>(AbstractList.java:860)
         at java.util.AbstractList.subList(AbstractList.java:569)
         at com.sap.ip.bi.bics.dataaccess.base.impl.ModifiableList.remove(ModifiableList.java:630)
         at com.sap.ip.bi.bics.dataaccess.consumer.impl.queryview.resultset.RsDataCells.removeRows(RsDataCells.java:480)
         at com.sap.ip.bi.bics.dataaccess.consumer.impl.queryview.resultset.RsAxis.removeTuples(RsAxis.java:550)
         at com.sap.ip.bi.bics.dataaccess.consumer.impl.queryview.resultset.RsAxis.applyResultVisibility(RsAxis.java:1312)
         at com.sap.ip.bi.bics.dataaccess.consumer.impl.queryview.resultset.RsAxis.applyResultVisibility(RsAxis.java:1326)
         at com.sap.ip.bi.bics.dataaccess.consumer.impl.queryview.resultset.RsAxis.applyResultVisibility(RsAxis.java:1326)
         at com.sap.ip.bi.bics.dataaccess.consumer.impl.queryview.resultset.RsAxis.applyResultVisibility(RsAxis.java:1326)
         at com.sap.ip.bi.bics.dataaccess.consumer.impl.queryview.resultset.RsAxis.applyResultVisibility(RsAxis.java:1272)
         at com.sap.ip.bi.bics.dataaccess.consumer.impl.queryview.resultset.RsAxis.applyResultVisibility(RsAxis.java:1170)
         at com.sap.ip.bi.bics.dataaccess.consumer.impl.queryview.resultset.ResultSet.applyPostProcessing(ResultSet.java:282)
         at com.sap.ip.bi.bics.dataaccess.consumer.impl.queryview.resultset.ResultSet.refreshData(ResultSet.java:262)
         at com.sap.ip.bi.bics.dataaccess.consumer.impl.queryview.QueryView.getResultSet(QueryView.java:267)
         at com.sap.ip.bi.webapplications.ui.items.analysis.control.AcPivotTableInteractive.checkResultSetState(AcPivotTableInteractive.java:368)
         at com.sap.ip.bi.webapplications.ui.items.analysis.control.AcPivotTableExport.validateDataset(AcPivotTableExport.java:249)
         at com.sap.ip.bi.webapplications.ui.items.analysis.control.AcPivotTableInteractive.buildUrTree(AcPivotTableInteractive.java:282)
         at com.sap.ip.bi.webapplications.ui.framework.base.impl.CompositeBuildUrTreeTrigger.process(CompositeBuildUrTreeTrigger.java:33)
         at com.sap.ip.bi.webapplications.ui.framework.base.composites.UiRootContainer.iterateOverChildren(UiRootContainer.java:40)
         at com.sap.ip.bi.webapplications.ui.framework.base.impl.CompositeBuildUrTreeTrigger.process(CompositeBuildUrTreeTrigger.java:36)
         at com.sap.ip.bi.webapplications.ui.advancedcontrols.bridge.AcItemBridge.iterateOverChildren(AcItemBridge.java:63)
         at com.sap.ip.bi.webapplications.ui.framework.base.impl.CompositeBuildUrTreeTrigger.process(CompositeBuildUrTreeTrigger.java:36)
         at com.sap.ip.bi.webapplications.ui.unifiedrendering.controls.FlowLayoutItem.iterateOverChildren(FlowLayoutItem.java:63)
         at com.sap.ip.bi.webapplications.ui.framework.base.impl.CompositeBuildUrTreeTrigger.process(CompositeBuildUrTreeTrigger.java:36)
         at com.sap.ip.bi.webapplications.ui.unifiedrendering.controls.FlowLayout.iterateOverChildren(FlowLayout.java:69)
         at com.sap.ip.bi.webapplications.ui.framework.base.impl.CompositeBuildUrTreeTrigger.process(CompositeBuildUrTreeTrigger.java:36)
         at com.sap.ip.bi.webapplications.ui.framework.base.composites.UiRootContainer.iterateOverChildren(UiRootContainer.java:40)
         at com.sap.ip.bi.webapplications.ui.framework.base.impl.CompositeBuildUrTreeTrigger.process(CompositeBuildUrTreeTrigger.java:36)
         at com.sap.ip.bi.webapplications.ui.advancedcontrols.bridge.AcItemBridge.iterateOverChildren(AcItemBridge.java:63)
         at com.sap.ip.bi.webapplications.ui.framework.base.impl.CompositeBuildUrTreeTrigger.process(CompositeBuildUrTreeTrigger.java:36)
         at com.sap.ip.bi.webapplications.ui.unifiedrendering.controls.MatrixLayoutCell.iterateOverChildren(MatrixLayoutCell.java:63)
         at com.sap.ip.bi.webapplications.ui.framework.base.impl.CompositeBuildUrTreeTrigger.process(CompositeBuildUrTreeTrigger.java:36)
         at com.sap.ip.bi.webapplications.ui.unifiedrendering.controls.MatrixLayoutRow.iterateOverChildren(MatrixLayoutRow.java:56)
         at com.sap.ip.bi.webapplications.ui.framework.base.impl.CompositeBuildUrTreeTrigger.process(CompositeBuildUrTreeTrigger.java:36)
         at com.sap.ip.bi.webapplications.ui.unifiedrendering.controls.MatrixLayout.iterateOverChildren(MatrixLayout.java:69)
         at com.sap.ip.bi.webapplications.ui.framework.base.impl.CompositeBuildUrTreeTrigger.process(CompositeBuildUrTreeTrigger.java:36)
         at com.sap.ip.bi.webapplications.ui.container.matrixlayout.control.AcMatrixControlGrid.iterateOverChildren(AcMatrixControlGrid.java:40)
         at com.sap.ip.bi.webapplications.ui.framework.base.impl.CompositeBuildUrTreeTrigger.process(CompositeBuildUrTreeTrigger.java:36)
         at com.sap.ip.bi.webapplications.ui.framework.base.composites.UiRootContainer.iterateOverChildren(UiRootContainer.java:40)
         at com.sap.ip.bi.webapplications.ui.framework.base.impl.CompositeBuildUrTreeTrigger.process(CompositeBuildUrTreeTrigger.java:36)
         at com.sap.ip.bi.webapplications.ui.advancedcontrols.bridge.AcItemBridge.iterateOverChildren(AcItemBridge.java:63)
         at com.sap.ip.bi.webapplications.ui.framework.base.impl.CompositeBuildUrTreeTrigger.process(CompositeBuildUrTreeTrigger.java:36)
         at com.sap.ip.bi.webapplications.ui.unifiedrendering.controls.Group.iterateOverChildren(Group.java:63)
         at com.sap.ip.bi.webapplications.ui.framework.base.impl.CompositeBuildUrTreeTrigger.process(CompositeBuildUrTreeTrigger.java:36)
         at com.sap.ip.bi.webapplications.ui.container.group.control.AcGroupControl.iterateOverChildren(AcGroupControl.java:259)
         at com.sap.ip.bi.webapplications.ui.framework.base.impl.CompositeBuildUrTreeTrigger.process(CompositeBuildUrTreeTrigger.java:36)
         at com.sap.ip.bi.webapplications.ui.framework.base.composites.UiRootContainer.iterateOverChildren(UiRootContainer.java:40)
         at com.sap.ip.bi.webapplications.ui.framework.base.impl.CompositeBuildUrTreeTrigger.process(CompositeBuildUrTreeTrigger.java:36)
         at com.sap.ip.bi.webapplications.ui.advancedcontrols.bridge.AcItemBridge.iterateOverChildren(AcItemBridge.java:63)
         at com.sap.ip.bi.webapplications.ui.framework.base.impl.CompositeBuildUrTreeTrigger.process(CompositeBuildUrTreeTrigger.java:36)
         at com.sap.ip.bi.webapplications.ui.unifiedrendering.controls.FlowLayoutItem.iterateOverChildren(FlowLayoutItem.java:63)
         at com.sap.ip.bi.webapplications.ui.framework.base.impl.CompositeBuildUrTreeTrigger.process(CompositeBuildUrTreeTrigger.java:36)
         at com.sap.ip.bi.webapplications.ui.unifiedrendering.controls.FlowLayout.iterateOverChildren(FlowLayout.java:69)
         at com.sap.ip.bi.webapplications.ui.framework.base.impl.CompositeBuildUrTreeTrigger.process(CompositeBuildUrTreeTrigger.java:36)
         at com.sap.ip.bi.webapplications.ui.framework.base.composites.UiRootContainer.iterateOverChildren(UiRootContainer.java:40)
         at com.sap.ip.bi.webapplications.ui.framework.base.impl.CompositeBuildUrTreeTrigger.process(CompositeBuildUrTreeTrigger.java:36)
         at com.sap.ip.bi.webapplications.ui.advancedcontrols.bridge.AcItemBridge.iterateOverChildren(AcItemBridge.java:63)
         at com.sap.ip.bi.webapplications.ui.framework.base.impl.CompositeBuildUrTreeTrigger.process(CompositeBuildUrTreeTrigger.java:36)
         at com.sap.ip.bi.webapplications.ui.unifiedrendering.controls.Group.iterateOverChildren(Group.java:63)
         at com.sap.ip.bi.webapplications.ui.framework.base.impl.CompositeBuildUrTreeTrigger.process(CompositeBuildUrTreeTrigger.java:36)
         at com.sap.ip.bi.webapplications.ui.container.group.control.AcGroupControl.iterateOverChildren(AcGroupControl.java:259)
         at com.sap.ip.bi.webapplications.ui.framework.base.impl.CompositeBuildUrTreeTrigger.process(CompositeBuildUrTreeTrigger.java:36)
         at com.sap.ip.bi.webapplications.ui.framework.base.composites.UiRootContainer.iterateOverChildren(UiRootContainer.java:40)
         at com.sap.ip.bi.webapplications.ui.framework.base.impl.CompositeBuildUrTreeTrigger.process(CompositeBuildUrTreeTrigger.java:36)
         at com.sap.ip.bi.webapplications.ui.framework.base.impl.CompositeBuildUrTreeTrigger.start(CompositeBuildUrTreeTrigger.java:59)
         at com.sap.ip.bi.webapplications.ui.framework.base.impl.ExtendedRenderManager.triggerComposites(ExtendedRenderManager.java:69)
         at com.sap.ip.bi.webapplications.ui.framework.base.impl.BICompositeManager.renderRoot(BICompositeManager.java:79)
         at com.sap.ip.bi.webapplications.ui.items.UiItem.render(UiItem.java:376)
    Any help in solving this error is highly appreciated. Points will be given
    Best Regards,
    Vidyut K Samanta

    Hi.
    Go to line 9 of your code.
    You are trying to use an array there.
    Suppose you have an array x[4] - this array has 4 elements indexed 0..3.
    you are trying to access an element with an index higher than 3.
    Nimo.

  • Trying to do photo "out of bounds" .  When i select the outside parts i get an error..............."

    trying to do photo "out of bounds" .  When i select the outside parts i get an error..............."the object channel "inside photo" is currently not available.  Now what.

    Welcome to the forum.
    However, I think that you might have the wrong one.
    Are you using Photoshop Elements?
    If so, this is the Premiere Elements (video editing) forum.
    Let me know if you want Photoshop Elements, and I will Move the post to that forum.
    Good luck,
    Hunt

  • How to prevent arrayindex out of bounds exception while unziping the files

    hi all ,
    i am new to java.Can any body help me to solve my problem.here is my problem.
    here i am trying to unzip a ziped file. but i am getting arrayindex out of bounds exception at line no 12 (args[0]), my quesion is to how to prevent arrayindex out of bounds exception ? please give me clear explanation.
    public class UnZip2 {
    static final int BUFFER = 2048;
    public static void main (String args[]) {
    try {
    BufferedOutputStream dest = null;
    BufferedInputStream is = null;
    ZipEntry entry;
    ZipFile zipfile = new ZipFile(args[0]);
    Enumeration e = zipfile.entries();
    while(e.hasMoreElements()) {
    entry = (ZipEntry) e.nextElement();
    System.out.println("Extracting: " +entry);
    is = new BufferedInputStream
    (zipfile.getInputStream(entry));
    int count;
    byte data[] = new byte[BUFFER];
    FileOutputStream fos = new
    FileOutputStream(entry.getName());
    dest = new
    BufferedOutputStream(fos, BUFFER);
    while ((count = is.read(data, 0, BUFFER))
    != -1) {
    dest.write(data, 0, count);
    dest.flush();
    dest.close();
    is.close();
    } catch(Exception e) {
    e.printStackTrace();
    }

    how you run it?
    java Unzip2?
    args[0] refer to first parameter in run command, so u should run it by giving a parameter. eg:
    java Unzip2 someFile.zip

  • Array Index out of bound exception

    public Name[] getName() {
              Name[] retVal = new Name[0];
              retVal[0] = this.getNameInstance();
              return retVal;
         public void setName(Name[] theName) {
              theName[0]=this.getNameInstance();
         private Name myNameInstance = new Name();
         public void setNameInstance(Name theNameInstance) {
              if(isValidName(theNameInstance)){
              myNameInstance = theNameInstance;
         public Name getNameInstance() {
              return myNameInstance;
         }I am getting an array Index out of bound eception in the method setName, Can any one tell me where I am doing wrong?

    The array passed in must be empty. I suggest using the debugger for problems like these. If you don't know how to use the debugger, here's a start:
    (Assuming you have a debugger, any IDE you'd be using will)
    1. Set a breakpoint on or before your line of question. In this case, place it on the line of code in your setName() method. Set a breakpoint by either right clicking on that line and selecting "Add breakpoint," or simply click on the far left side of the editor window, right next to the line number. Either way, a little dot will appear to mark the breakpoint.
    2. Execute your code in Debug mode rather than release mode. This might mean clicking on the little bug-looking icon "Debug" rather than "Run."
    3. Your code will execute and you'll enter the debug perspective when that breakpoint is reached. There, in the variables window, you'll see your array and any information about it, particularly its size and contents.

  • Array out of bounds Exception

    this code :
      public void clearAroundTile (int row, int col) {
            //Checks if a tile is visited, has a hint and hintvalue == adjacent flagged tiles
           if(tiles[row][col].isVisited() && tiles[row][col].isHint() && tiles[row][col].getHint()<= getNumFlagsAround(tiles[row][col])){
             if(!tileAt(tiles[row][col], Direction.N).isFlagged()){
                 visitTile(tileAt(tiles[row][col], Direction.N));
             if(!tileAt(tiles[row][col], Direction.NE).isFlagged()){
                 visitTile(tileAt(tiles[row][col], Direction.NE));
             if(!tileAt(tiles[row][col], Direction.E).isFlagged()){
                 visitTile(tileAt(tiles[row][col], Direction.E));visits all the tiles on a board, around a base tile, now the problem is that sometimes, when if checks aorund a tile that is near the edge of a board i get an out of bounds exeption, i know why this happens, but i dont know what type of if statments i should use to correct it, i was thinking.. do if(row-1)>0) then it does not go out of the board, but then how would i do it for the edge of the board that does not relate to zero? any ideas.
    thanks

      if(row > 0 && tiles[row][col].isBlank()  )
                if(!tiles[row-1][col].isVisited()){
                    clearAroundTile(row-1, col);
                    visitTile(tileAt(tiles[row][col], Direction.N));
            if(row -1 > 0 && col + 1 < cols && tiles[row][col].isBlank()  )
                if(!tiles[row-1][col+1].isVisited()){
                    clearAroundTile(row-1, col+1);
                    visitTile(tileAt(tiles[row][col], Direction.NE));
                }i am using this to automatically clear the tiles that are blank, that is only for 2 directions, i did it for all, and for some reason i keep getting a stack overflow, damn

  • Urgent: Out of message Exception when parsing large message with JavaMail

    I am using JavaMail to parse the message. If the size of the message I try to parse exceeds my memory setting, I will got the Out of memory error. I understand that, and it is reasonable.
    The question I have is: At the time I try to parse the message, I only want to know what the displayable text content of the message and some information about the attachement files like the attchment file name, file type, and file size. So I want to parse the message to get only those information without the body of the attachment files. In this case, I can avoid the "Out of memory" exception in most case. Is there anyway to do this with JavaMail 1.2?
    Thanks.

    Hi try to read only the header information of the mail it will give you the details

  • Index out of Bounds Exception in for loop.

    Occasionaly with the code below, i get an index out of bounds error, index 1, size 1, however the for loop should ensure that it never calls the getActorLocation method if the index is the same size as the arrayList size.
    Im having one of those days, and i just cant see what error i have made.
    Perhaps i need coffee? lol
    Cheers
    James
    private void checkMemoryIntegrity(){
            Actor actor = actorList.get(actorIndex);
            ArrayList<Integer> inRangeList = getActorsInMemoryRange(actor, actor.getRange());
            inRangeList.trimToSize();
            for (int i = 0; i < inRangeList.size();i++){
                if (inRangeList.size() != 0){
                    actor = brainState.getActorLocation(i); //<<<<<<<<< problem line
                    if (!actorList.contains(actor)){
                        brainState.actorLocations.remove(i);
    public ArrayList <Integer> getActorsInMemoryRange(Actor actor, int range){
            int i = 0;
            int x = actor.getX();
            int y = actor.getY();
            ArrayList <Integer> inRangeList = new ArrayList <Integer> ();
            Actor compActor;
            while (i< brainState.actorLocations.size())
                compActor = brainState.getActorLocation(i);
                int xDist = x - compActor.getX();
                if ( (xDist >= (-1) * range) && (xDist <= range) ){
                    int yDist = y - compActor.getY();
                    if ( (yDist >= (-1) * range) && (yDist <= range) ){
                        inRangeList.add(i);
                i++;
            return inRangeList;
        }

    I was thinking it might be easier to do it this way:
    Iterator<Actor> i = actorLocations.iterator();
    while(i.hasNext())
        if (!actorList.contains(i.next())) {
            i.remove();
    }It sounds like you have an equals() method which compares the x and y locations of the actor. If not then you will have to enclose the remove in an if block which compares the actor location. Does that make sense?
    Edit: contains uses the equals method.
    Returns true if this list contains the specified element. More formally, returns true if and only if this list contains at least one element e such that
    (o==null ? e==null : o.equals(e)).Edited by: Edward_Kimber on May 23, 2008 11:43 AM

  • Why am i getting an index out of bounds exception

    I just want to read some bytes at the end of an mp3 file.
    File file = new File(fd.getDirectory() + File.separator + fd.getFile());
                try {
                     FileInputStream fileInputStream = new FileInputStream(file);
                     byte[] fileSnippet = new byte[100];
                     int startPosition = (int)file.length() - 500;
                     fileInputStream.read(fileSnippet, startPosition, 100);

    fileInputStream.read(fileSnippet, startPosition, 100);This does not tell it to seek (hint, hint) to startPosition and read 100 bytes. It is telling it to read from the current position into the buffer starting at index "startPosition" in that buffer. If startPosition is >= 100, then that's clearly out of bounds.

  • Out of memory error when Applet transferring a file of size 600 MB

    Hi ,
    I have an Applet which transfer files from client machine to server using streams.
    I have a servlet which reads data sent from Applet.
    This is working fine when i Transfer files of size 10 MB
    when I chose a file of 600 MB the following error is thrown at Applet side after some time.
    java.lang.OutOfMemoryError: Java heap space
         at java.util.Arrays.copyOf(Unknown Source)
         at java.io.ByteArrayOutputStream.write(Unknown Source)
         at sun.net.www.http.PosterOutputStream.write(Unknown Source)
         at java.io.DataOutputStream.write(Unknown Source)
         at Apple.FileUploadApplet.actionPerformed(FileUploadApplet.java:53)Here is my Applet Code
    if(ae.getSource() == jbutton)
         JFileChooser jfc=new JFileChooser();
         jfc.showOpenDialog(null);
    File f=jfc.getSelectedFile();
    try
    FileInputStream in = new FileInputStream(f);
    byte[] buf=new byte[1024];
    int bytesread = 0;
    String toservlet = "http://9.122.18.115:8080/FileTransfer/FileUpload?"
                                  + URLEncoder.encode("name") + "="
                                  + URLEncoder.encode(f.getName());
    URL servleturl = new URL(toservlet);
    URLConnection servletconnection = servleturl.openConnection();
    //servletconnection.setRequestMethod("GET");
    servletconnection.setRequestProperty("Content-type",
                "application/octet-stream");
    servletconnection.setDoInput(true);
    servletconnection.setDoOutput(true);
    servletconnection.setUseCaches(false);
    servletconnection.setDefaultUseCaches(false);
    DataOutputStream out = new DataOutputStream(servletconnection.getOutputStream ());
    while( (bytesread = in.read( buf )) > -1 )
    out.write( buf, 0, bytesread );
    // out.flush(); // tried this to flush the data but didn't work
    System.out.println("writing data");
    out.flush();
    out.close();
    in.close();
    DataInputStream inputFromClient = new DataInputStream(servletconnection.getInputStream() );
    //get what you want from servlet
    inputFromClient.close();
    catch(Exception e)
    e.printStackTrace();
    }My Servlet Code
    public void doPost(HttpServletRequest req,HttpServletResponse res)
    ServletContext sc = this.getServletContext();
    try
    String path = "C:\\Downloads\\";
    String  fileName=req.getParameter("name");
      System.out.println("name="+fileName);
    File yourFile = new File(path+fileName);
      System.out.println("name="+yourFile);
    FileOutputStream toFile = new FileOutputStream( yourFile );
    DataInputStream fromClient = new DataInputStream( req.getInputStream() );
    byte[] buff = new byte[1024];
    int cnt = 0;
    int k=0;
    long st,et;
    st=System.currentTimeMillis();
    while( (cnt = fromClient.read( buff )) > -1 ) {
    toFile.write( buff, 0, cnt );
    //System.out.println("writing data=="+ k++);
    et=System.currentTimeMillis();
    toFile.flush();
    toFile.close();
    fromClient.close();
    int tt=(int) ((et-st)/1000);
    System.out.println("total time for "+fileName+" Download ="+tt+" secs");
    System.out.println("total time for "+fileName+" Download ="+(tt/60)+" mins");
    catch(Exception e)
    e.printStackTrace();
    }Please Help me out...

    yeah its working fine. Thank you very much..
    But it would be better if we provide the chunklength rather than using a zero to upload the file fastly.

  • Array Out of Bounds Exception. Where?

    Hello,
    I am developing an application using Visual Cafe 3.0. The application access a file every minute to read a new line and show data in a MultiList. First the code reads the header of the file to get all options, and then reads a new line avery minute to get results for that options.
    It is something like this:
    Option1, option2, option3,...
    1234, 45, 0, ...
    532, 23, 2, ...
    and so on...
    Code is quite large, and I call a method which is generating the exception (java.lang.ArrayOutofBoundsException). Exception is reached after a random number of calls to that method each time.
    I have some variables declared in the method and some other declared outside of that method because I use them in other part of the code.
    I catch the exception in the method which calls this method (outside following code)
    Here is the method that is failing.
    Please can anyone see where is the code reaching that exception?
    //These are variables used outside the method
    String[] lista_op = new String[100];
    boolean[] lista_bo = new boolean[100];
    String[] lista_va = new String[100];
    int n_opciones = 0;
    int lon = 0;
    char[] resultados;
    //And this is the method
    //Basically I pass a line of text to the method and the length (actually I am not using that variable and some others)
    //Length of all arrays is 100, but number of used items is about 50
         public void results(char[] resultados, int lon)
             int opciones = 0;
             int i = 0;
             int j = 0;
             int n = 0;
             int c = 0;
             int b = 0;
             int z = 0;
             int datoentero = 0;
             int datoanterior = 0;
             char coma = ',';
             String dato = "";
             String vacio = "";
             String datoantes = "";
             String cadena1 = "";
             String cadena2 = "";
             //int[] pos = new int[100];
              multilista.adjustHeadings();
                  //Bucle de busqueda de opciones seleccionadas y
                  //extraccion de datos
                  while (c < n_opciones){
                      if (lista_bo[c] == false){
                          lista_va[b] = lista_op[c];
                          //pos[b] = c;
                          n = c + 3;
                          // Bucle de busqueda de resultados
                          for ( j = 0; i < n; j++){
                              if (resultados[j] == coma){
                                  i++;
                          i = 0;
                          while (resultados[j] != coma){
                              dato = dato + resultados[j];
                              j++;
                          // Fin de bucle de busqueda de resultados
                          cadena1 = lista_va;
              datoentero = Integer.parseInt(dato);
              //textArea1.append(" " + datoentero);
              while (z < Lista_seleccion.getItemCount()){
              cadena2 = Lista_seleccion.getItem(z);
              if (cadena1.equals(cadena2)){
              datoantes = multilista.getCellText(z, 1);
              if (!datoantes.equals(vacio)){
              //textArea1.append("&" + datoantes + "&");
              datoanterior = Integer.parseInt(datoantes);
              datoentero = datoentero + datoanterior;
              multilista.addTextCell(z, 1, Integer.toString(datoentero));
              //grafica(datoentero, z);
              //notificar(datoentero, z);
              z++;
              z = 0;
                   //textArea1.append(" " + dato + " " + c + " " + n);
              b++;
              c++;
              dato = "";
              //Fin de bucle de busqueda de opciones seleccionadas
                   opciones = Lista_seleccion.getItemCount();
                   while (i < opciones){
                   multilista.addTextCell(i, 0, Lista_seleccion.getItem(i));
                   i++;

    The piece of code I showed before works for me when I do
    System.out.println(sw.toString());
    I haven't tried to append it to a text area, but if you say it gives you problem you could try with this:
    // .. keeping the first 3 lines of my previos code
    StringTokenizer st = new StringTokenizer(sw.toString());
    while (st.hasMoreTokens()) {
      textArea.append(st.nextToken());
      textArea.append("\n"); // newline
    }

  • Run TIme Error Message- Array Out of Bounds Exception

    Good evening all,
    I seem to have a run time error with the below segment of code. I've changed the (args[0]) a variety of ways but still get the same message.
    I have a few questions regarding my methodology. First, am I headed down the right path (no spoonfeeding allowed please! I need to grasp and learn this myself). Second, would it be something causing error that is on another line and I'm not seeing it. Third, should I have added the entire class file?
    public static void main(String [] args) throws IOException
       Inventory store = new Inventory ( 15);  // Sets store inventory
       Scanner inFile = new Scanner(new File(args [0])); // _Line 27 in the program_
       PrintWriter outfile = new PrintWriter(args [1]); 
       String temp; .
       double price; 
       int quantity; .
       inFile.next();
       int x = 0; Run time error received:
    java.lang.ArrayIndexOutOfBoundsException: 0
         at StoreBusiness.main(StoreBusiness.java:27)
    Thank you in advance everyone.

    WarriorGeek wrote:
    Thanks Flounder,
    I feel pretty dumb after posting my answer.
    I read the arrays tutorial and understand all that's described there but with what I've learned you have to start your array out at zero like I did. Should I use the variable name that I gave it in lieu of zero?No. The point is that since you didn't provide any arguments when you started your program, there is no arr[0] or arr[anything else]. It doesn't matter if you put an int literal between the brackets or a variable or a method that returns int. You can't access elements that don't exist.
    So instead of java MyClass you need to do java MyClass something The "something" becomes args[0]. If you're using an IDE instead of the command line, there will be a place to configure what arguments you want to pass when you run your program.

  • Array Index out of bounds error when rendering graph

    Hello,
    OBIEE 11.1.1.5 running on RHEL version 5.7
    I'm encountering a strange problem with graph rendering. I have a graph and a table that are tied to a list of values. The graph renders correctly for many of the values in the list, but for certain values the graph does not render while the table does. What is even more odd is that the graph renders correctly using BI mobile on an iPad for all values in the LOV.
    From the Weblogic fusion bipublisher.log, I see this log entry immediately after getting the rendering error:
    Message:     java.lang.ArrayIndexOutOfBoundsException: 124
    The above log entry is followed about a minute later with this:
    Message ID: ADF_FACES-60099
    Component: AdminServer
    Module: oracle.adfinternal.view.faces.renderkit.rich.RegionRenderer
    Message: The region component with id: emTemplate:fmwRegion has detected a page fragment with multiple root components. Fragments with more than one root component may not display correctly in a region and may have a negative impact on performance. It is recommended that you restructure the page fragment to have a single root component.
    Any ideas on how to fix this?

    Hi Ray,
    I cannot find an array.  The only one I see is ResultList.  This one seems to be in all Test Stand sequences.  I am not sure exactly how it's used.
    I have pulled the sub-sequence out of the main sequence and made a new main sequence with all of the same variables.
    Look at it and let me know what you think.
    Thanks
    Attachments:
    Excel - Set Cell Color.seq ‏59 KB

Maybe you are looking for