Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 6 of 6

Thread: java.land.IndexOutOfBoundsException: Index -1 out-of-bounds for length 0

  1. #1
    Junior Member
    Join Date
    Sep 2021
    Posts
    11
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default java.land.IndexOutOfBoundsException: Index -1 out-of-bounds for length 0

    SOLVED

    My Exception is thrown at Main.java:42 and I have racked my brain trying to figure out how to fix it


    Output

    null
    Strong Ordered: true
    Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 0 out-of-bounds for length 0
    	at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:64)
    	at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:70)
    	at java.base/jdk.internal.util.Preconditions.checkIndex(Preconditions.java:248)
    	at java.base/java.util.Objects.checkIndex(Objects.java:372)
    	at java.base/java.util.ArrayList.get(ArrayList.java:440)
    	at Main.checkWeakOrder(Main.java:42)
    	at Main.processPolyList(Main.java:64)
    	at Main.main(Main.java:10)


    PolyFile.txt


    4.0 3 2.5 1 8.0
    5.0 4 5.0
    4.0 4 5.7 2 8.6



    Main.java

    import javax.swing.*;
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.util.*;
     
    public class Main {
    	private static List<Polynomial> polyList = new ArrayList<>();
     
    	public static void main(String[] args) {
    		processPolyList();
    	}
     
    	public static ArrayList<String> fromFile(){
    		ArrayList<String> expressionList = new ArrayList<String>();
    		JFileChooser chooser = new JFileChooser();
    		chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
    		chooser.setCurrentDirectory(new File(System.getProperty("user.dir")));
    		int response = chooser.showOpenDialog(null);
    		if (response == JFileChooser.APPROVE_OPTION) {
    			File file = chooser.getSelectedFile();
    			try {
    				Scanner fileIn = new Scanner(file);
    				if (file.isFile()) {
    					while (fileIn.hasNext()) {
    						String expression = fileIn.nextLine();
    						expressionList.add(expression);
    					}
    				}
    			}
    			catch (NoSuchElementException nse) {
    				JOptionPane.showMessageDialog(JOptionPane.getRootFrame(), "File is empty");
    			}
    			catch (FileNotFoundException fne) {
    				JOptionPane.showMessageDialog(JOptionPane.getRootFrame(), "File not found");
    			}
    		}
    		return expressionList;
    	}
     
    	public static boolean checkWeakOrder(List<Polynomial> polyList) {
    		boolean isWeakOrder = true;
    		Polynomial previous = polyList.get(polyList.size()-1);
    		for(int i = polyList.size()-2; i > 0; i--) {
    			if (previous.compareExponents(polyList.get(i)) < 0) {
    				isWeakOrder = false;
    			}
    		}
    		return isWeakOrder;
    	}
     
    	public static void processPolyList() {
    		try {
    			ArrayList<String> a = fromFile();
    			for(String element :a) {
    				Polynomial p = new Polynomial(element);
    				System.out.println(p);
    				polyList.add(p);
    			}
    		}
    		catch (InvalidPolynomialSyntax ex) {
    			JOptionPane.showMessageDialog(JOptionPane.getRootFrame(), ex.getMessage());
    		}
    		System.out.println("Strong Ordered: " + OrderedList.checkSorted(polyList));
    		System.out.println("Weak Ordered: " + checkWeakOrder(polyList));
    	}
     
    }


    Polynomial.java

    import java.util.*;
     
    public class Polynomial implements Iterable<Polynomial.Term>, Comparable<Polynomial> {
    	Comparator<Polynomial> compare;
    	private Term head;
     
    	public Polynomial(String fromFile) {
    		head = null;
    		Scanner termScanner = new Scanner(fromFile);
    		try {
    			while(termScanner.hasNext()) {
    				addTerm(termScanner.nextDouble(), termScanner.nextInt());
    			}
    		}
    		catch(Exception ex) {
    			System.out.println(ex.getLocalizedMessage());
    			throw new InvalidPolynomialSyntax("Incorrect Syntax, please check inputs!");
    		}
    	}
     
    	public void addTerm(double coefficient, int exponent) {
    		if(exponent < 0) {
    			throw new InvalidPolynomialSyntax("No negative exponents, please check inputs!");
    		}
    		Term current = head;
    		if(current == null) {
    			head = new Term(coefficient, exponent);
    			head.next = null;
    		}
    		else {
    			while(current.next != null) {
    				current = current.next;
    			}
    			current.next = new Term(coefficient, exponent);
    		}
    	}
     
    	public int compareTo(Polynomial otherPoly) {
    		Term thisCurrent = this.head;
    		Term otherCurrent = otherPoly.head;
    		while(thisCurrent != null && otherCurrent != null) {
    			if(thisCurrent.getExponent() != otherCurrent.getExponent()) {
    				return thisCurrent.getExponent() - otherCurrent.getExponent();
    			}
    			else if(thisCurrent.getCoefficient() != otherCurrent.getCoefficient()) {
    				if(otherCurrent.getCoefficient() > thisCurrent.getCoefficient()) {
    					return -1;
    				}
    				else if(otherCurrent.getCoefficient() < thisCurrent.getCoefficient()) {
    					return 1;
    				}
    			}
    			thisCurrent = thisCurrent.getNext();
    			otherCurrent = otherCurrent.getNext();
    		}
    		if(thisCurrent == null && otherCurrent == null) {
    			return 0;
    		}
    		if(thisCurrent == null) {
    			return -1;
    		}
    		else {
    			return 1;
    		}
    	}
     
    	public int compareExponents(Polynomial poly2) {
    		Term thisPolyTerm = this.head;
    		Term otherPolyTerm = poly2.head;
    		while(thisPolyTerm != null && otherPolyTerm != null) {
    			if(thisPolyTerm.getExponent() != otherPolyTerm.getExponent()) {
    				return thisPolyTerm.getExponent() - otherPolyTerm.getExponent();
    			}
    			else {
    				thisPolyTerm = thisPolyTerm.getNext();
    				otherPolyTerm = otherPolyTerm.getNext();
    			}
     
    		}
    		if(thisPolyTerm == null && otherPolyTerm == null) {
    			return 0;
    		}
    		if(otherPolyTerm == null) {
    			return 1;
    		}
    		else {
    			return -1;
    		}
     
    	}
    	public Polynomial() { 
    		compare = (Polynomial poly1, Polynomial poly2) -> poly1.compareExponents(poly2);
    	}
    	public Polynomial(Comparator<Polynomial> compare) {
    		this.compare = compare;
    	}
    	public Iterator<Term> iterator(){
    		return new Iterator<Term>() {
    			private Term current = getHead();
     
    			public boolean hasNext() {
    				return current != null && current.getNext() != null;
    			}
    			public Term next() {
    				Term data = current;
    				current = current.next;
    				return data;
    			}
    		};
    	}
     
     
     
    	public String toString() {
    		StringBuilder expressionBuilder = new StringBuilder();
    		if(head.coefficient > 0) {
    			expressionBuilder.append(head.toString());
    		}
    		else {
    			expressionBuilder.append(" - ").append(head.toString());
    		}
    		for (Term tmp = head.next; tmp != null; tmp = tmp.next) {
    			if(tmp.coefficient < 0) {
    				expressionBuilder.append(" - ").append(tmp.toString());
    			}
    			else {
    				expressionBuilder.append(" + ").append(tmp.toString());
    			}
    		}
    		return expressionBuilder.toString();
    	}
     
    	static class Term {
    		private double coefficient;
    		private int exponent;
    		private Term next;
    		private Term(double c, int e) {
    			coefficient = c;
    			exponent = e;
    			next = null;
    		}
     
    		private int getExponent() {
    			return this.exponent;
    		}
    		private double getCoefficient() {
    			return this.coefficient;
    		}
    		private Term getNext() {
    			return next;
    		}
    		public String toString() {
    			String termString = String.format("%.1f",  Math.abs(coefficient));
    			if(exponent == 0) {
    				return termString;
    			}
    			else if(exponent == 1) {
    				return termString + "x";
    			}
    			else {
    				return termString + "x^" + exponent;
    			}
    		}
    	}
    	private Term getHead() {
    		return head;
    	}
     
    }


    OrderedList.java

    import java.util.*;
     
    public class OrderedList {
    	public static <T extends Comparable<? super T>> boolean checkSorted(List<T> list) {
    		boolean isSorted = true;
    		for(int i = list.size()-1; i > 0; i--) {
    			T current = list.get(i);
    			if(!checkSorted(list, current)) {
    				isSorted = false;
    			}
    		}
    		return isSorted;
    	}
     
    	private static <T extends Comparable<? super T>> boolean checkSorted(List<T> list, T current){
    		T currentValue = list.get(list.indexOf(current));
    		T nextValue = list.get(list.indexOf(current)- 1);
    		if(nextValue != null) {
    			return currentValue.compareTo(nextValue) >= 0;
    		}
    		return true;
    	}
    }


    InvalidPolynomialSyntax.java

    public class InvalidPolynomialSyntax extends RuntimeException {
    	InvalidPolynomialSyntax(String msg){
    		super(msg);
    	}
    }
    Last edited by EasyE; September 14th, 2021 at 03:27 PM.

  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: java.land.IndexOutOfBoundsException: Index -1 out-of-bounds for length 0

    how to fix it
    Basically make sure there is an element at index 0 before trying to access it.

    How are you debugging the code to see what it is doing?
    I use print statements. Add lots of print statements to show where the code is executing and what the values of the variables are as the code executes.

    What statement prints out null?
    If you don't understand my answer, don't ignore it, ask a question.

  3. #3
    Junior Member
    Join Date
    Sep 2021
    Posts
    11
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: java.land.IndexOutOfBoundsException: Index -1 out-of-bounds for length 0

    null is printing at Main.java:56 inside the processPolyList(). I think the problem is with Main.java:54

    public static void processPolyList() {
    		try {
    			ArrayList<String> a = fromFile();
                            //the for statement doesn't seem to be working. How do I fix that?
    			for(String element :a) {
    				Polynomial p = new Polynomial(element);
    				System.out.println(p);
    				polyList.add(p);
    			}
    		}
    		catch (InvalidPolynomialSyntax ex) {
    			JOptionPane.showMessageDialog(JOptionPane.getRootFrame(), ex.getMessage());
    		}
    		System.out.println("Strong Ordered: " + OrderedList.checkSorted(polyList));
    		System.out.println("Weak Ordered: " + checkWeakOrder(polyList));
    	}

  4. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: java.land.IndexOutOfBoundsException: Index -1 out-of-bounds for length 0

    To see what print statement is printing the null, add unique ids with each print statement. For example:
       System.out.println("p="+p);
        ...
       System.out.println("a="+a);

    I think the problem is with Main.java:54
    Why? What is happening there?

    Have you added any print statements for debugging? What do they show? Why is the list empty?
    If you don't understand my answer, don't ignore it, ask a question.

  5. #5
    Junior Member
    Join Date
    Sep 2021
    Posts
    11
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: java.land.IndexOutOfBoundsException: Index -1 out-of-bounds for length 0

    The problem was with with PolyFile.txt and the addTerm() inside the class Polynomial.java.

    so the original PolyFile.txt I had was:
    4.0 3 2.5 1 8.0
    5.0 4 5.0
    4.0 4 5.7 2 8.6

    and the addTerm() needs to read in double, int repeating as follows:
    4.0, 3 next term
    2.5, 1 next term
    8.0, 5.0 **Exception thrown because it read two doubles instead of double, int

    the new PolyFile.txt looks like this:
    4.0 3 2.5 1 8.0 0
    5.0 4 5.0 0
    4.0 4 5.7 2 8.6 0

    with the added 0's the code works perfectly

  6. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: java.land.IndexOutOfBoundsException: Index -1 out-of-bounds for length 0

    problem was with with PolyFile.txt and the addTerm()
    The code would be better if that method threw an exception when there is a problem with the input instead of ignoring the problems and returning bad data.

    Also comments in the code re the expected layout of the input records would be good.
    If you don't understand my answer, don't ignore it, ask a question.

Similar Threads

  1. Replies: 3
    Last Post: February 9th, 2019, 02:37 PM
  2. Index out of bounds exception. Need help.
    By chernorizec in forum What's Wrong With My Code?
    Replies: 5
    Last Post: July 13th, 2014, 05:03 PM
  3. Replies: 1
    Last Post: November 10th, 2013, 08:39 PM
  4. Array index out of bounds
    By fortune2k in forum Collections and Generics
    Replies: 1
    Last Post: November 30th, 2010, 07:11 AM
  5. Index Out Of Bounds
    By chronoz13 in forum Collections and Generics
    Replies: 1
    Last Post: December 28th, 2009, 12:19 PM