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 13 of 13

Thread: Casting error using String with generics

  1. #1
    Junior Member
    Join Date
    Apr 2012
    Posts
    28
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Casting error using String with generics

    I'm getting a bug with this program I am writing for my CS class. Pretty much got it nailed down to a casting error. It happens when I try to retrieve a value from a node in an existing list (MovieQueueMain: System.out.println("Added " + tempList.get(toAdd) + " to queue."); ). Wondering if anyone more capable than myself can help me figure out how to fix this error. The actual error message I am getting is as follows:

    Exception in thread "main" java.lang.ClassCastException: Project2.ListNode cannot be cast to java.lang.String
    at Project2.MovieQueueMain.main(MovieQueueMain.java:8 7)

    MovieQueueMain:
    ////////////////////////////////////////\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
     
    package Project2;
     
    import java.util.*;
    import java.io.File;
    import java.io.FileNotFoundException;
     
    public class MovieQueueMain {
     
    	/* You may create additional private static
          variables or methods as needed */
     
    	public static void main(String args[]) {
    		int toAdd;
    		int toRemove;
    		String temp;
    		LinkedList<String> movieQueue = new LinkedList<String>();
     
    		LinkedList<String> comedy = new LinkedList<String>("comedy");
    		LinkedList<String> drama = new LinkedList<String>("drama");
    		LinkedList<String> action = new LinkedList<String>("action");
    		LinkedList<String> horror = new LinkedList<String>("horror");
    		LinkedList<String> family = new LinkedList<String>("family");
     
     
     
    		//** You may also add additional variables as needed **//
     
    		Scanner stdin = new Scanner(System.in);  // for reading console input
     
     
     
     
    		boolean done = false;
    		while (!done) {
    			System.out.print("Enter option - a, c, l, m, p, r, s, w or x: ");
    			String input = stdin.nextLine();
     
    			if (input.length() > 0) {
    				char choice = input.charAt(0);  // strip off option character
    				String remainder;  // used to hold the remainder of input
    				// trim off any leading or trailing spaces
    				remainder = input.substring(1).trim();
     
    				switch (choice) {
     
    				case 'a' :
     
    					//** Add your code here for option a **//
    					//add movie to queue
    					//if statement to select genre
    					LinkedList<String> tempList = new LinkedList();
    					if (remainder.equals("comedy")){
    						tempList = comedy;
    					}
    					if (remainder.equals("drama")){
    						tempList = drama;
    					}
    					if (remainder.equals("action")){
    						tempList = action;
    					}
    					if (remainder.equals("horror")){
    						tempList = horror;
    					}
    					if (remainder.equals("family")){
    						tempList = family;
    					}
     
    					//genre.print();
    					System.out.println(tempList.print(true));
    					toAdd = 0;
    					boolean goodInput = false;
    					while (goodInput == false){
    						//prompt user for selection
    						System.out.println("Please enter a number between 1 and "
    								+ tempList.size());
     
    						//add check to make sure input is a valid character
    						toAdd = Integer.parseInt(stdin.nextLine()); 
    						if (0 < toAdd && toAdd < tempList.size() + 1) goodInput = true;
    						else System.out.println("Invalid input. Please try again.");
    					}
     
    					//String tempString = String.valueOf(tempList.get(toAdd));
    					//movieQueue.add(tempString);
    					System.out.println("Added " + tempList.get(toAdd) + " to queue.");
     
    					movieQueue.add(tempList.get(toAdd));
     
     
    					/**Add a movie to the movie queue from a database of movies of the given genre.
    					 * The genre will be one of the following: comedy, drama, action, horror, family.
    					 * Your program will then open and read from the file with the name genre.txt (e.g.,
    					 * horror.txt or action.txt), which will be a list of movie titles in that genre, one
    					 * per line. Each movie title should be printed, one per line, in the following format:
     
                           1 MovieTitle1
                           2 MovieTitle2
                           ...
                           N MovieTitleN
     
                          After the movie titles have been printed in order, print "Please enter a number between
                          1 and N", where N is the number of movies in the genre. Read the number entered by the user.
                          If it is an invalid number (not an integer, or an integer less than 1 or greater than N),
                          repeat the prompt until a valid number is received. The movie corresponding to this number
                          should then be added to the end of the movie queue. Once added, print: "Added title to queue."
                          where title is the title of the movie added to the queue.
     
                          If the file specified by genre.txt does not exist or is not readable, print "Cannot find the specified file."
    					 **/      
    					break;
     
    				case 'c' :
     
    					//** Add your code here for option c **//
    					//copy to end of queue
    					//prompt user for selection
    					toAdd = Integer.parseInt(stdin.nextLine());
     
    					//movieQueue.add(temp)
    					movieQueue.add(movieQueue.get(toAdd));
     
    					/**Copies the line at line# to the end of the movie queue, and print "Copied title to end of queue.",
    					 * where title is the title of the copied movie. This does not remove the line at line#. If an
    					 * InvalidListPositionException is thrown, or if the argument is not an int, print "Invalid line number."
    					 **/
    					break;
     
    				case 'l' :
     
    					//** Add your code here for option l **//
    					//load new queue from text file
    					//prompt user for file name to load
    					String toLoad = stdin.nextLine();    
    					//load list
    					movieQueue = new LinkedList<String>(toLoad);
     
    					/**Load the movie queue from the given file. First empty your old movie queue (or create a new one).
    					 * Then read in from the file line by line until the end of the file is reached. Each of these lines
    					 * should be stored as one movie in your queue. If the file cannot be found, display "Cannot find the
    					 * specified file." Once the file is successfully stored in the queue, print the queue with line numbers.
    					 *
    					 */
    					break;
     
    				case 'm' :
     
    					//** Add your code here for option m **//
     
    					//prompt user for selection
    					toAdd = Integer.parseInt(stdin.nextLine());     
    					//movieQueue.add(temp)
    					movieQueue.add(movieQueue.size(), movieQueue.get(toAdd));
     
    					/** Move the movie at position line# to the front of the movie queue, and print "Moved title to front
    					 * of queue.", where title is the title of the movie that was moved. This does remove the movie from
    					 * its original position. If an InvalidListPositionException is thrown, or if the argument is not an int,
    					 * print "Invalid line number."
    					 *
    					 */
    					break;
     
    				case 'p' :
     
    					//** Add your code here for option p *//
    					if (movieQueue.size() == 0){
    						System.out.println("Empty.");
    					}
    					else{
    						System.out.print(movieQueue.print(true));
    					}
     
    					/**Print the movie queue in the format specified by the LinkedList's print() method. You should print
    					 * line numbers (set the lineNumbers flag to true). If the queue is empty, print "Empty."
    					 *
    					 */
    					break;
     
    				case 'r' :
     
    					//** Add your code here for option r **//
    					toRemove = Integer.parseInt(remainder);    
    					temp = movieQueue.get(toRemove);
    					movieQueue.remove(toRemove);
    					System.out.println("Removed " + temp + " from queue.");
     
    					/**Remove the specified movie from the list, and print "Removed title from queue.", where title is the
    					 * title of the movie that was removed. If an InvalidListPositionException is thrown, or if the argument
    					 * is not an int, print "Invalid line number."
    					 *
    					 */
    					break;
     
    				case 's' :
     
    					//** Add your code here for option s **//
     
     
    					//	FileUtils.writeStringToFile(new File("queue.txt"), movieQueue.print(false));
     
     
     
    					/**Save the movie queue to the specified fileName. This file should be saved in the format returned by
    					 * the print method in the LinkedList class. You should not save line numbers (set the lineNumbers flag
    					 * to false). If the specified file cannot be written to, print, "Cannot write to the specified file."
    					 * If the movie queue is currently empty, print, "Cannot write to file, movie queue is empty."
    					 *
    					 */
    					break;
     
    				case 'w' :
     
    					//** Add your code here for option w **//
    					toRemove = Integer.parseInt(remainder);    
    					if (toRemove > 0){
    						for (int i = 0; i < toRemove; i++){
    							movieQueue.remove(1);
    						}
    						System.out.println("Removed first " + toRemove + 
    										   " from queue.");
     
    					}
    					else {
    						System.out.println("Invalid number of movies.");
    					}   
     
    					/**Mark the first amount movies in the list as watched (i.e., remove them from the queue). If amount is
    					 * greater than the number of movies currently in the queue, remove all movies in the queue. Print "Removed
    					 * first numMovies from queue.", where numMovies is the number of movies that were actually removed from
    					 * the queue. If amount is not an integer or is less than or equal to zero, print "Invalid number of movies."
    					 *
    					 */
    					break;
     
    				case 'x' :
    					//Exit the program. This command is already implemented.
    					done = true;
    					System.out.println("exit");
    					break;
     
    				default :
    					System.out.println("Unknown Command");
    					break;
    				}
    			}
    		}
    	}
    	//static void writeStringToFile(File file, String data) {
    	//	FileUtils.writeStringToFile(new File("queue.txt"), movieQueue.print(false));
    	//}
    }

    LinkedList:
    ////////////////////////////////////////\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
     
    package Project2;
     
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.util.Scanner;
     
    public class LinkedList<E> {
     
    	ListNode<E> head;		//class variables
    	ListNode<E> tail;
    	int listSize;
     
    	public LinkedList(){	//construct empty linkedList
    		head = tail = new ListNode<E>(null); //create dummy node
    		listSize = 0;
    	}
     
    	public LinkedList(String file){		//load a list from a text file
    		head = tail = new ListNode<E>(null); //create dummy node
    		listSize = 0;
    		getList(file);		//loads LinkedList via getList method
    	}
     
    	public void add(E data){	//adds LinkNode to LinkedList
     
    		tail.setNext(new ListNode<E>(data));
    		tail = tail.getNext();
    		listSize++;
    		//ListNode<E> temp = new ListNode(data);		//constructs new node
    		//tail.setNext(temp);		//setNext of tail node to new node
    		//tail = temp;	//sets tail pointer to new node
    		//listSize++;		//increases listSize
    		return;
    	}
     
    	public void add(int pos, E item){	//add a LinkNode to specific location
     
     
    		// check for bad position
    		if (pos < 0 || pos > listSize) {
    			throw new IndexOutOfBoundsException();
    		}
     
    		// if asked to add to end, let the other add method do the work
    		if (pos == listSize) {
    			add(item);
    			return;
    		}
     
    		// find the node n after which to add a new node and add the new node
    		ListNode<E> n = head;
    		for (int k = 0; k < pos; k++) {
    			n = n.getNext();
    		}
    		n.setNext(new ListNode<E>(item, n.getNext()));
    		listSize++;
    		return;
    	}
    	//ListNode<E> temp = new ListNode(item);		//constructs new node
    	//ListNode<E> curr = head.getNext();		//creates a curr pointer
    	//if (pos == listSize + 1) { //checks if added last in list
    	//    add(item);	//adds last in list
    	//    return;
    	//}
    	//for (int i = 1; i < pos; i++){    //cycle to find place in chain
    	//   curr = curr.getNext();	
    	//}
    	//temp.setNext(curr.getNext());		//setNext for new node in chain
    	//curr.setNext(temp);		//setNext for previous node to new node
    	//listSize++;		//increase listSize
    	//return;
    	//}
     
    	public E get(int pos){	//get data from node in pos
    		ListNode<E> curr = new ListNode(head.getNext());//creates a curr pointer
    		for (int i = 1; i < pos; i++){	//cycle to find node to retrieve data
    			curr = curr.getNext();
     
    		}
    		return curr.getData();		//return data of specified value
    	}
     
    	public E remove(int pos){	//remove a node from a specified place in chain
    		ListNode<E> curr = head.getNext();		//create a curr pointer
    		for (int i = 1; i < pos; i++){ //cycle to find previous node in line
    			curr = curr.getNext();
    		}
    		ListNode<E> temp2 = curr.getNext();		//create a temp node to bypass 
    		curr.setNext(temp2.getNext());		//setNext of curr to bypass node
    		listSize--; 	//decrease listSize
    		return temp2.getData();	//return removed item
    	}
     
    	String print(boolean lineNumbers){	//return string of items in linkedlist
    		ListNode<E> curr = head.getNext();		//create a curr pointer
    		String temp2 = "";		//create a string to hold values
    		if (lineNumbers == true){	//if true print numbered list
    			for (int i = 1; i <= listSize ; i++){  //write line to string
    				temp2 = temp2 + i + " " + curr.getData()+ "\n";
    				curr = curr.getNext();	//move curr to next position
    			}
    		}
    		else{	//if lineNumbers = false, print line without numbers
    			for (int i = 1; i <= listSize ; i++){
    				temp2 = temp2 + "\n" + curr.getData();	//write line to string
    				curr = curr.getNext();	//move curr to next position
    			}
    		}
    		return temp2;	//return string
    	}
     
    	private void getList(String listName){	//load list from text file
    		try{	//load file location
    			String fileName = "/Users/zerosdamnation/Documents/workspace/" +
    					"CS367/src/Project2/" + listName + ".txt";
    			File srcFile = new File(fileName);		//load file
    			Scanner fileIn = new Scanner(srcFile);	//for reading file
    			while (fileIn.hasNextLine()){	//loop while file has data
    				String inLine = fileIn.nextLine();	//create new string 
    				add((E)inLine);  //add new LinkNode with String data
    			}
    		}
    		catch (FileNotFoundException e){	//catch if file does not exist
    			System.out.println("Cannot find the specified file.");
    		}        
    	}    
     
    	public int size(){	//return listSize
    		return listSize;
    	}
     
    	public boolean isEmpty(){	//checks if list is empty
    		if (listSize == 0) return true;
    		return false;
    	}
    }

    ListNode:
    package Project2;
     
    /**
     * Generic singly linked list node. It serves as the basic building block for 
     * storing data in singly linked chains of nodes.
     * 
     * <b>Do not modify this file in any way!</b>
     */
    class ListNode<E> {
    	private E data;                // data to be stored 
    	private ListNode<E> next;   // connnection to next node
     
    	/**
    	 * Constructs a new list node with no link to next node.
    	 * @param data the data to be stored in this node
    	 */
    	ListNode(E data) {
    		this(data, null);
    	}
     
    	/**
    	 * Constructs a new list node with a link to next node.
    	 * @param data the data to be stored in this node
    	 * @param next the node after this one
    	 */
    	ListNode(E data, ListNode<E> next) {
    		this.data = data;
    		this.next = next;
    	}
     
    	/**
    	 * Returns the current data.
    	 * @return the current data
    	 */
    	E getData() {
    		return data;
    	}
     
    	/**
    	 * Returns the current next node.
    	 * @return the current next node
    	 */
    	ListNode<E> getNext() {
    		return next;
    	}
     
    	/**
    	 * Sets the data to the given new value.
    	 * @param data the new data
    	 */
    	void setData(E data) {
    		this.data = data;
    	}
     
    	/**
    	 * Sets the next node to the given new value.
    	 * @param next the new next node
    	 */
    	void setNext(ListNode<E> next) {
    		this.next = next;
    	}
    }


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Casting error using String with generics

    ClassCastException: Project2.ListNode cannot be cast to java.lang.String
    at Project2.MovieQueueMain.main(MovieQueueMain.java:8 7)
    That makes sense. How can an object of type: Project2.ListNode be cast to a String at line on line 87?

    What input does the program need to execute and get the error?
    If you don't understand my answer, don't ignore it, ask a question.

  3. #3
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,895
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: Casting error using String with generics

    		ListNode<E> curr = new ListNode(head.getNext());//creates a curr pointer

    This line is not doing what you want it to. You're trying to create a new ListNode<ListNode<E>> which has a data element which happens to be head.getNext().

    See if you can't come up with an appropriate fix (it's probably a lot simpler than you think it is).

  4. #4
    Junior Member
    Join Date
    Apr 2012
    Posts
    28
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Casting error using String with generics

    Quote Originally Posted by helloworld922 View Post
    		ListNode<E> curr = new ListNode(head.getNext());//creates a curr pointer

    This line is not doing what you want it to. You're trying to create a new ListNode<ListNode<E>> which has a data element which happens to be head.getNext().

    See if you can't come up with an appropriate fix (it's probably a lot simpler than you think it is).
    I think I get what you are saying. In situations where there are no items in the list, it will try to getNext() when there is no item to get. I will see about how I can fix this.

    @Norm: Here is the console output (note that the String values have a number at the beginning of each line for testing purposes in addition to the number added from the print() method):

    Enter option - a, c, l, m, p, r, s, w or x: a comedy
    1 1 Comedy
    2 2 for
    3 3 the 
    4 4 money
    5 5 equals
    6 6 win
     
    Please enter a number between 1 and 6
    1
    Exception in thread "main" java.lang.ClassCastException: Project2.ListNode cannot be cast to java.lang.String
    	at Project2.MovieQueueMain.main(MovieQueueMain.java:87)

  5. #5
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Casting error using String with generics

    If all that has to be entered to test the program, it is way too much.
    The Scanner class has a constructor that takes a String. Can you code the String in the Scanner's constructor with all the answers needed for testing? For example:
    		Scanner stdin = new Scanner("a\ncomedy\n1\nx\n"); //System.in);  // for reading console input
    If you don't understand my answer, don't ignore it, ask a question.

  6. #6
    Junior Member
    Join Date
    Apr 2012
    Posts
    28
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Casting error using String with generics

    All that I have entered for user input is "a comedy" and "1". The rest is output from the program.

    Should I modify the following line to match what you typed in?

    Scanner stdin = new Scanner(System.in);  // for reading console input

  7. #7
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Casting error using String with generics

    modify the following line to match what you typed in?
    Yes.
    If you don't understand my answer, don't ignore it, ask a question.

  8. #8
    Junior Member
    Join Date
    Apr 2012
    Posts
    28
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Casting error using String with generics

    I tried running the line you wrote for the scanner and got an error when I tried to compile the program. I am fairly certain that the initial error that is causing me problems has to do with trying to cast a generic object as a String, such as in the following line of code:

    System.out.println("Added " + tempList.get(toAdd) + " to queue.");

    When I invoke tempList.get(toAdd), I am invoking the get() method from LinkedList, which invokes the getData() method from ListNode. However, the data is not being read as a String, even if it was cast as a String to begin with. The data field in ListNode is generic data type E, and I can cast a String to it. I can even read the String data from LinkedList methods as print(). But when I run into problems when I try to pass that String along to MovieQueueMain with the get() method in LinkedList. I have even tried casting the object I am receiving as a String, with the following code:

    String tempString = String.valueOf(tempList.get(toAdd));

    But then the value tempString only represents the name of the data node, and not the actual data being held within the node.

  9. #9
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Casting error using String with generics

    got an error when I tried to compile
    Please copy the full text of the compiler error message and paste it here.


    I need the input to test the program. Here's what I get when I execute it:
    Running: java -cp . MovieQueueMain

    Enter option - a, c, l, m, p, r, s, w or x: 1 1 Title

    Please enter a number between 1 and 1
    Added null to queue.
    Enter option - a, c, l, m, p, r, s, w or x: exit

    0 error(s)
    If you don't understand my answer, don't ignore it, ask a question.

  10. #10
    Junior Member
    Join Date
    Apr 2012
    Posts
    28
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Casting error using String with generics

    Exception in thread "main" java.lang.NumberFormatException: For input string: "comedy"
    	at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
    	at java.lang.Integer.parseInt(Integer.java:449)
    	at java.lang.Integer.parseInt(Integer.java:499)
    	at Project2.MovieQueueMain.main(MovieQueueMain.java:80)

    The files for comedy, drama, family, horror, action are all simple text files with multiple lines.

  11. #11
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Casting error using String with generics

    got an error when I tried to compile
    That is not a compiler error. It's from when the program is executed.

    What is the input you are passing to the program via the Scanner class's constructor?
    Does it match what you type in when you execute the program when it reads input from the keyboard?
    If you don't understand my answer, don't ignore it, ask a question.

  12. #12
    Junior Member
    Join Date
    Apr 2012
    Posts
    28
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Casting error using String with generics

    I found another way to get around the problem I had. It's more of a bandaid fix as I still have an issue with casting, but I can at least get the String value I want now and create a new ListNode with it. Thanks for your input.

  13. #13
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Casting error using String with generics

    Ok, if you've solved the problem, mark this thread as solved.
    If you don't understand my answer, don't ignore it, ask a question.

Similar Threads

  1. Casting java.lang.String to a custom class
    By Tyluur in forum What's Wrong With My Code?
    Replies: 14
    Last Post: July 29th, 2012, 08:51 PM
  2. error when comparing 2 string objects
    By amr in forum What's Wrong With My Code?
    Replies: 5
    Last Post: February 9th, 2011, 07:36 PM
  3. [SOLVED] why casting int to String is not possible through brackets method
    By voltaire in forum Java Theory & Questions
    Replies: 2
    Last Post: May 2nd, 2010, 04:00 PM
  4. reading string input then casting it to an int?
    By etidd in forum Java Theory & Questions
    Replies: 2
    Last Post: March 27th, 2010, 11:49 PM
  5. Replies: 2
    Last Post: November 3rd, 2009, 06:28 AM