Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

readString problem!! could anyone help me take a look

807606Jun 10 2007 — edited Jun 11 2007
hi... i am doing a music Cd list program. there are two operation i need to do 1) insertion and 2) deletion. i have implemented my own sortList to do it... i work fine when i do the insertion to the list but it can`t perform well on deletion.. However, i am sure that my list deletion algoritm is totally correct... i perform two test as following to ensure my deletion is correct..but i think the problem is on my readString fucntoon ...could anyone help me take a look!!
public class SortedListTesting
{
	SortedList musicCdList = new SortedList();
	ReadOperation theRo = new ReadOperation();
	//ErrorCheckingOperation theEco = new ErrorCheckingOperation();
	MusicCd temp;
	
	public void insertCdWithReadStringFunction()
	{
		String musicCdsTitle;
	
		//try to prompt the user `s cd `s title for insertion to our List
		musicCdsTitle = theRo.readString("Please enter your CD`s title : ");
		musicCdList.insert(new MusicCd(musicCdsTitle));
		System.out.println("Number of items in the list: " 
		                           + musicCdList.getNumberOfItems() + "\n" + musicCdList.toString() );
 
	}
	
	
	public void deleteCdWithReadStringFunction()
	{
		
		try 
		{
			//try to prompt the user `s delected cd `s title
			String keyword = theRo.readString("Please enter CD `s title to be delected from SMOA : ") ;
			// System.out.println("The CD that you just deleted is " + keyword);
			temp = musicCdList.delete(keyword);
			System.out.println("Number of items in the list: " 
						+ musicCdList.getNumberOfItems() + "\n" + temp );
				      
		}
			      
		catch ( InvalidDataException errorMsg )
		{
			System.out.println( errorMsg.getMessage() + "\n" );
		}
			
			System.out.println("Now, We have " + musicCdList.getNumberOfItems() + " items in the list, and the items as following  :\n" + musicCdList.toString() );
				
		
	}

	public void insertCd()
	{
		String musicCdsTitle;
	
		
		//try to input the string directly to our list
		musicCdsTitle = "ann";//theRo.readString("Please enter your CD`s title : ");
				   
		musicCdList.insert(new MusicCd(musicCdsTitle));
				    
		System.out.println("Now, the number of items in the list: " 
                 		+ musicCdList.getNumberOfItems() + "\n" + musicCdList.toString() );
			
	
	}
	
	
	public void deleteCd()
	{
		              try 
			      {
				      //try to input the String directly
				      String keyword = "ann"; //theRo.readString("Please enter CD `s title to be delected from SMOA : ") ;
				      System.out.println("The CD that you just deleted is " + keyword);
				      temp = musicCdList.delete(keyword);
			              //System.out.println("Number of items in the list: " 
			              //                     + musicCdList.getNumberOfItems() + "\n" + temp );
				      
			      }
			      
			      catch ( InvalidDataException errorMsg )
			      {
				      System.out.println( errorMsg.getMessage() + "\n" );
			      }
			     System.out.println("Now, We have " + musicCdList.getNumberOfItems() + " items in the list, and the items as following  :\n" + musicCdList.toString() );
	
	}
	
	
	public static void main(String[] args)
	{
		SortedListTesting st = new SortedListTesting();
		//These two testing i am trying to show that my list is working fine for inseting and deleting
		//i try to input the cd `s title name " ivan " by my readString function, it work fine for insertion 
		//but it is fail in delete fuction..it shows that "ivan not found: cannot be deleted" ...At first, 
		//i think it is my delete function problem..but it is not my delete function problem...cos it work fine if 
		//input the string directly from the function...i think the issues works on my readString fucntion
		//i try a milllion of time but i still got the same problem ...pls help....
		System.out.println("\t...Testing for input from readString fuction...\t");
		st.insertCdWithReadStringFunction();
		st.deleteCdWithReadStringFunction();
		//it work fine for input the string directly in the function, it show as following...
		System.out.println("\t...Testing for input the string directly ...\t");
		st.insertCd();
		st.deleteCd();
	}
}

/*
javac SortedListTesting.java
Exit code: 0
java SortedListTesting
...Testing for input from readString fuction... Please enter your CD`s title : ivan <<-inserting the cd`s title to our list Number of items in the list: 1 <<- sucessfully insert to our list Title: ivan Please enter CD `s title to be delected from SMOA : ivan <<- try to delete from our list, i type "ivan" here ivan not found: cannot be deleted <<- problem occur , it should be fine in there Now, We have 1 items in the list, and the items as following : Title: ivan <<- it should not be shown ...Testing for input the string directly ... Now, the number of items in the list: 2 Title: ann <<- i pass "ann" String directly to insertion function Title: ivan <<- it is the left over from the preivous process The CD that you just deleted is ann <<- i pass " ann" String directly to my deletion Now, We have 1 items in the list, and the items as following : <<- it successfully delete .... it prove that my deletion function is working properly....i think it is on readString problem.. Title: ivan
Exit code: 0
*/ //it seems that the readString function read the string //at the first time does not match the second time //reading, it makes it can`t find the stuff from the list ..
import java.util.*;

public class ReadOperation{
	//pls help check here....thx
	public String readString(String userInstruction) 
	{
		String aString = null;

		try
		{
	                Scanner scan = new Scanner(System.in);
			System.out.print(userInstruction);
			aString = scan.nextLine();
		
		} 
		
		catch (NoSuchElementException e) 
		{
			//if no line was found
			System.out.println("\nNoSuchElementException error occurred (no line was found) " + e);
		} 
		catch (IllegalStateException e) 
		{
			// if this scanner is closed
			System.out.println("\nIllegalStateException error occurred (scanner is closed)" + e);
		}
		
		return aString;
	}
	
	
	public char readTheFirstChar(String userInstruction) 
	{
		char aChar = ' ';
		String strSelection = null;
		try
		{
			
			//char charSelection;
	                Scanner scan = new Scanner(System.in);
			System.out.print(userInstruction);
			strSelection = scan.next();
			aChar =  strSelection.charAt(0);
		} 
		
		catch (NoSuchElementException e) 
		{
			//if no line was found
			System.out.println("\nNoSuchElementException error occurred (no line was found) " + e);
		} 
		catch (IllegalStateException e) 
		{
			// if this scanner is closed
			System.out.println("\nIllegalStateException error occurred (scanner is closed)" + e);
		}
		
		return aChar;
	}
	
	public int readInt(String userInstruction) {

		int aInt = 0;

		try {
			Scanner scan = new Scanner(System.in);
			System.out.print(userInstruction);
			aInt = scan.nextInt();
		} catch (InputMismatchException e) {
			System.out.println("\nInputMismatchException error occurred (the next token does not match the Integer regular expression, or is out of range) " + e);
		} catch (NoSuchElementException e) {
			System.out.println("\nNoSuchElementException error occurred (input is exhausted)" + e);
		} catch (IllegalStateException e) {
			System.out.println("\nIllegalStateException error occurred (scanner is closed)" + e);
		}

		return aInt;

	}

}
public class SortedList extends ShellSortedList implements SortedListInterface<MusicCd>
{
	public SortedList()
	{
		super();
	}
	
	public void insert( MusicCd aCd )
	{
		MusicCdNode cdNode = new MusicCdNode( aCd );
		cdNode.setNext( head );
		head = cdNode;
		numberOfItems++;
	}
	
	public MusicCd delete(String aCdsTitle)
	                                       throws InvalidDataException
	{
		MusicCdNode current = head;
		MusicCdNode previous = null;
		while( current != null 
			 && current.getMusicCd().getCdTitle() != aCdsTitle)
		{
			previous = current;
			current = current.getNext();
		}
		
		if (current == null ) //not found 
			throw new InvalidDataException(aCdsTitle
					    + " not found: cannot be deleted" );
		else
		{
			if( current == head )
				head = head.getNext(); //delete head
			else
				previous.setNext( current.getNext() );
			
			numberOfItems--;
			return current.getMusicCd();
		}
	}
	
	public MusicCd modify(String anExistedCdsTitle, String aModifyCdsTitle)
						 throws InvalidDataException
	{
		
		MusicCdNode current = head;
		while( current != null 
			 && current.getMusicCd().getCdTitle() !=  anExistedCdsTitle)
		{
			current = current.getNext();
		}
		
		if ( current == null )
			throw new InvalidDataException( anExistedCdsTitle
					    + " not found: cannot be deleted" );
		
		else
		{
			MusicCd tempCd = new MusicCd();
			tempCd.setCdTitle(aModifyCdsTitle);
			current.setMusicCd(tempCd);
			return current.getMusicCd();
		}
	}
        
	 
	
}
//for better understand of my program
public interface SortedListInterface<T>
{
	//public SortedList();

	public void insert( T anElement );
	
	public T delete(String searchKey) 
                                     throws InvalidDataException;
	
	public T modify(String searchKey, String aModifyTitle) 
				     throws InvalidDataException;
	
	
}
	
public abstract class ShellSortedList
{
	protected MusicCdNode head;
	protected int numberOfItems;
	
	public ShellSortedList()
	{
		head = null;
		numberOfItems = 0;
	}
	
	public int getNumberOfItems()
	{
		return numberOfItems;
	}

	public boolean isEmpty()
	{
		return( numberOfItems == 0 );
	}
	
	public boolean isDuplicate(String newCD)
	{
	       boolean found = false;
	       MusicCdNode current = head; 
	       for( int i=0; i < numberOfItems; i++)
	        {
			                    
		     if(current.getMusicCd().getCdTitle().equals(newCD))
		     {
			System.out.println("Duplicate Cd is found !!");
	                   found = true;
		     }
		     current = current.getNext();
		}
                return found;
	
	}
	
	public String toString()
	{
		String listString = " ";
		MusicCdNode current = head; 
		for( int i=0; i < numberOfItems; i++)
		{
			listString += current.getMusicCd().toString() + "\n";
			current = current.getNext();
		}
		
		return listString;
	}
	
	
	
}
public class MusicCdNode
{
	private MusicCd cd;
	private MusicCdNode next;
	
	// Default constructor
	public MusicCdNode()
	// Description: Initialize the reference for the cd object and the value of next to null.
	// Postcondition: cd = null; next = null;
	{
		cd = null;
		next = null;
	}
	// Parameterized constructor
	public MusicCdNode(MusicCd aCd)
	// Description: Set the reference for the cd object according to the parameters and value of next to null.
	// Postcondition: cd = aCd; next = null;
	{
		cd = aCd;
		next = null;
	}
	
	
       public MusicCd getMusicCd()
	{
		return new MusicCd(cd.getCdTitle());
	}
	
	public MusicCdNode getNext()
	{
		return next;
	}
	
	public void setMusicCd(MusicCd aCd)
	{
		cd = new MusicCd(aCd.getCdTitle());
	}
	
	public void setNext(MusicCdNode aCd)
	{
		next = aCd;
	}
	
}
// File: MusicCd.java
// Author: Chi Lun To (Ivan To)
// Created on: June 5, 2007

// Class Description
// The MusicCd class defines a music cd object that contain the CD`s title, CD`s artist/GroupName,
//  CD`s yearOfRelease , Cd`s music genre, and any comment of the Cd`s. This class provides functions 
//  to access the musicCdsTitle, artistOrGroupName, yearOfRelease, musicGenre, and aComment variable.
   
//  Class Invariant: All MusicCd objects have a  string musicCdsTitle, string artistOrGroupName, integer yearOfRelease
//  String musicGenre, and String aComment. A string type musicCdsTitle,artistOrGroupName, musicGenre,or aComment of "None" 
//  indicates no real name specified yet. A integer yearOfRelease of 1000 indicates no real years specific yet.
   
public class MusicCd
{
	String theCdTitle;// the CD`s Title
	
	// Default constructor 
	public MusicCd()
	// Description: Initialize theCdTitle to empty string
	// Postcondition: theCdTitle = " ";
	{
		theCdTitle = " ";
	}//end constructor
	
	// Parameterized constructor
	public MusicCd(String aCdTitle)
	// Description: Set theCdTitle according to the parameters
	// Postcondition: theCdTitle = aCdTitle;
	{
		theCdTitle = aCdTitle;
	} // end constructor
	
	// Accessor function : getCdTitle( ) function
	public String getCdTitle()
	// Description: Method to return the theCdTitle
	// Postcondition: the value of theCdTitle is returned
	{
		return theCdTitle;
	}// end  getCdTitle( ) function
	
	
	// Mutator function: setCdTitle( ) function
	public void setCdTitle(String aCdTitle)
	// Description: Method to set theCdTitle according to the parameter
	// Postcondition: theCdTitle = aCdTitle;
	{
		theCdTitle = aCdTitle;
	}// end setCdTitle( ) function
	
	
	// toString( ) function
	public String toString()
	// Description: Method to return the theCdTitle
	// Postcondition: the value of theCdTitle is returned as String
	{
		
	          return("Title: " + theCdTitle );
	}// end  toString( ) function
	
}
// File: InvalidDataException.java
// Author: Chi Lun To (Ivan To)
// Created on: June 5, 2007


// Class Description
// The InvalidDataException class is a self- defined exception class which handles
// the issues that may arise with return value of the deleted and modify function.
// For example,  the issue will occurs if the user try to delete the music cd from a empty list
// or deleting a music cd that does not exist on the list. it would return null to the user. But, the user
// expected to return an obeject reference of the music cd.Therefore, we instantiate InvalidDataException
// class to handle this issue.
// 
//  Class Invariant: 
//  InvalidDataException class is a self-defining exceptional class which 
//  inherits the existing functionality of the Exception class. 
// 

public class InvalidDataException extends Exception
{      
	//Parameterized constructor
	public InvalidDataException( String s )
	{
		super( s ); //inherits the existing functionality of the Exception class. 
	}
}
Message was edited by:
Ivan1238

Message was edited by:
Ivan1238
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Jul 9 2007
Added on Jun 10 2007
5 comments
234 views