I am writing a program that inputs data and creates a graph represented by two adjacency matricies. One matricie contains one weight, and the other a different weight, ie distance and time between nodes. I am recieving the Double cannot be cast to Integer at a point where no Doubles are even involved let alone casting. I am very confused by this error. Here is my code:

 public static void main(String args[]){
        ArrayList<Integer> node1 = new ArrayList();
        ArrayList<Integer> node2 = new ArrayList();
        ArrayList<Integer> time = new ArrayList();
        ArrayList<Double> distance = new ArrayList();
        String file = "distanceAndTime.dat";

        // Input data from file to ArrayLists
        inputData(file, node1, node2, time, distance);

        int numNodes = howManyNodes(node1,node2);// get number of distinct nodes
        graph g = new graph(numNodes);           // create graph of correct size

        //Label all nodes
        for(int j = 0; j<numNodes; j++){
            g.setLabel(j, "v"+j);
        }

        // add edge w/time weight
        for(int i=0; i<node1.size(); i++){
                g.addTimeEdge(node1.get(i), node2.get(i), time.get(i));  //This is where error occurs
        }
        /*
        // add edge w/distance weight
        for(int i=0; i<node1.size(); i++){
                g.addDistanceEdge(node1.get(i).intValue(), node2.get(i).intValue(), distance.get(i).doubleValue());
        }*/


        g.printTime();
        g.printDistance();

    }





public class graph {

   private int[][] timeEdge;  // adjacency matrix w/time traveled node to node
   private double[][] distanceEdge; // adjacency matrix w/distance between nodes
   private Object[] labels;

   public graph(int n) {
      timeEdge  = new int [n][n];
      distanceEdge = new double[n][n];
      labels = new Object[n];
   }

   public int size(){ 
       return labels.length; 
   }

   public void setLabel(int vertex, Object label){ 
       labels[vertex]=label; 
   }
   public Object getLabel(int vertex){ 
       return labels[vertex]; 
   }

   public void addTimeEdge(int source, int target, int w){ 
       timeEdge[source][target] = w; 
   }

   public void addDistanceEdge(int source, int target, double w){ 
       distanceEdge[source][target] = w; 
   }
   ...

Thanks to anyone that can help me with this error.

Please post the full text of the error message.
What line in the code has the error?

Edited 4 Years Ago by NormR1

Exception in thread "main" java.lang.ClassCastException: java.lang.Double cannot be cast to java.lang.Integer at finalProject.finalProject.main(finalProject.java:32)

ABOVE ERROR IS AT LINE 21. If line 26 is un-commented it receives this error as well.

public class graph {

   private int[][] timeEdge;  // adjacency matrix w/time traveled node to node
   private double[][] distanceEdge; // adjacency matrix w/distance between nodes
   private Object[] labels;

   public graph(int n) {
      timeEdge  = new int [n][n];
      distanceEdge = new double[n][n];
      labels = new Object[n];
   }

   public int size(){ 
       return labels.length; 
   }

   public void setLabel(int vertex, Object label){ 
       labels[vertex]=label; 
   }
   public Object getLabel(int vertex){ 
       return labels[vertex]; 
   }
   public void addTimeEdge(int source, int target, int w){ 
       timeEdge[source][target] = w; 
   }

   public void addDistanceEdge(int source, int target, double w){ 
       distanceEdge[source][target] = w; 
   }

   public boolean isEdge (int source, int target){ 
       return timeEdge[source][target]>0; 
   }


   public int getTime (int source, int target){ 
       return timeEdge[source][target]; 
   }

   public double getDistance (int source, int target){ 
       return distanceEdge[source][target]; 
   }

   public void printTime() {
      for (int j=0; j<timeEdge.length; j++) {
     System.out.print (labels[j]+": ");
     for (int i=0; i<timeEdge[j].length; i++) {
        if (timeEdge[j][i]>0) System.out.print (labels[i]+":"+timeEdge[j][i]+" ");
     }
     System.out.println ();
      }
   }

   public void printDistance() {
      for (int j=0; j<distanceEdge.length; j++) {
     System.out.print (labels[j]+": ");
     for (int i=0; i<distanceEdge[j].length; i++) {
        if (distanceEdge[j][i]>0) System.out.print (labels[i]+":"+distanceEdge[j][i]+" ");
     }
     System.out.println ();
      }
   }
}




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

public class finalProject {
    public static void main(String args[]){
        ArrayList<Integer> node1 = new ArrayList();
        ArrayList<Integer> node2 = new ArrayList();
        ArrayList<Integer> time = new ArrayList();
        ArrayList<Double> distance = new ArrayList();
        String file = "distanceAndTime.dat";

        // Input data from file to ArrayLists
        inputData(file, node1, node2, time, distance);

        int numNodes = howManyNodes(node1,node2);// get number of distinct nodes
        graph g = new graph(numNodes);           // create graph of correct size

        //Label all nodes
        for(int j = 0; j<numNodes; j++){
            g.setLabel(j, "v"+j);
        }

        // add edge w/time weight
        for(int i=0; i<node1.size(); i++){
                g.addTimeEdge(node1.get(i), node2.get(i), time.get(i));
        }
        /*
        // add edge w/distance weight
        for(int i=0; i<node1.size(); i++){
                g.addDistanceEdge(node1.get(i).intValue(), node2.get(i).intValue(), distance.get(i).doubleValue());
        }*/


        g.printTime();
        g.printDistance();

    }

    public static void inputData(String fileName, ArrayList n1, ArrayList n2, ArrayList d, ArrayList t){
        try{
            Scanner Input = new Scanner(new File(fileName));

            while (Input.hasNextLine()){
                // Each line in file is formatted with 4 values that corespond
                // to an edge with two different weights( distance & time)
                n1.add(Integer.parseInt(Input.next()));   // Add edge starting node to list
                n2.add(Integer.parseInt(Input.next()));   // Add edge ending node to list
                d.add(Double.parseDouble(Input.next()));    // Add edge distance to list
                t.add(Integer.parseInt(Input.next()));    // Add edge time of travel to list
            }

            // Print data
            for(int i = 0; i<n1.size();i++){
                System.out.println(n1.get(i) + " " + n2.get(i) + " " + d.get(i) + " " + t.get(i));
            }            
        }catch(Exception e){
            System.err.println("Error: " + e.getMessage());
        } 
    }

    public static int howManyNodes(ArrayList n1, ArrayList n2){
        ArrayList nodes = new ArrayList();

        //Only Add Distinct Nodes to nodes list (NO DUPLICATES)
        for(int i=0; i<(n1.size()+n2.size()); i++){
            if(i<n1.size()){
                if(!(nodes.contains(n1.get(i))))
                    nodes.add(n1.get(i));
            }else{
                if(!(nodes.contains(n2.get(i-n1.size()))))
                    nodes.add(n2.get(i-n1.size()));
            }
        }

        return nodes.size();    // Return # of distinct nodes in graph      
    }
}

Part of file distanceAndTime.dat Input:

1 2 1.5 380
1 3 0.7 190
2 5 3.1 360
3 2 1.4 210
3 4 0.7 200
4 6 3.6 380
4 7 1.1 230
5 6 0.9 120
5 8 1.6 140

I get 10 warnings when I compile the code. I bet if you fix the code so there are no warnings it will fix your problem.

This is a classic example of why you should use classes rather than parallel arrays .
(spoiler follows)

inputData(file, node1, node2, time, distance);
public static void inputData(String fileName, ArrayList n1, ArrayList n2, ArrayList d, ArrayList t)

... and that's how you get Double values in the time array.

If you had initialised your ArryLists properly and declared the parameters fully for the method you would have found this error immediatley.

Edited 4 Years Ago by JamesCherrill: Removed inaccurate statement

new ArrayList();           //  an arraylist that accepts any kind of data
new ArrayList<Integer>();  // an arraylist for Integers only
new ArrayList<>();         // short version (needs Java 7)

similarly:

public static void inputData(String fileName, ArrayList<Integer> n1 ...
// prevents you passing an ArrayList<Double> as parameter

Do you have warnings turned on for the compiler? It will flag all the places where the code needs to be fixed.

So the following would be a more "correct" way of doing this?

public class problem {
    private ArrayList<Integer> node1 = new ArrayList<Integer>();
    private ArrayList<Integer> node2 = new ArrayList<Integer>();
    private ArrayList<Integer> time = new ArrayList<Integer>();
    private ArrayList<Double> distance = new ArrayList<Double>();

    public problem(String fileName){
        try{
            Scanner Input = new Scanner(new File(fileName));

            while (Input.hasNextLine()){
                // Each line in file is formatted with 4 values that corespond
                // to an edge with two different weights( distance & time)
                node1.add(Integer.parseInt(Input.next()));   // Add edge starting node to list
                node2.add(Integer.parseInt(Input.next()));   // Add edge ending node to list
                distance.add(Double.parseDouble(Input.next()));    // Add edge distance to list
                time.add(Integer.parseInt(Input.next()));    // Add edge time of travel to list
            }

            // Print data
            for(int i = 0; i<node1.size();i++){
                System.out.println(node1.get(i) + " " + node2.get(i) + " " + distance.get(i) + " " + time.get(i));
            }            
        }catch(Exception e){
            System.err.println("Error: " + e.getMessage());
        }
    }

    public int getNumberNodes(){
        ArrayList nodes = new ArrayList();
        //Only Add Distinct Nodes to nodes list (NO DUPLICATES)
        for(int i=0; i<(node1.size()+node2.size()); i++){
            if(i<node1.size()){
                if(!(nodes.contains(node1.get(i))))
                    nodes.add(node1.get(i));
            }else{
                if(!(nodes.contains(node2.get(i-node1.size()))))
                    nodes.add(node2.get(i-node1.size()));
            }
        }
        return nodes.size();    // Return # of distinct nodes in graph
    }

    public static void main(String Args[]){
        problem one = new problem("distanceAndTime.dat");
        System.out.println(one.getNumberNodes());
    }

Edited 4 Years Ago by crazymidget01

That's a lot better - the compiler has a much better chance of picking up any mistakes. Best of all is to have a class rather than those parallel arrays:

class Edge {
  public final int node1, node2, time; // I assume it's immutable
  public final double distance;
  public Edge (int node1, int node2.....
     this.node1 = node1; 
     .....

Then when you read the file create new Edge objects and add them to an ArrayList<Edge>

This article has been dead for over six months. Start a new discussion instead.