Results 1 to 5 of 5

Thread: Vector Prob

  1. #1
    wierdal is offline Member
    Join Date
    Oct 2008
    Posts
    6
    Rep Power
    0

    Default Vector Prob

    I think this is a vector prob but cold also be an Object prob.

    Given an Assignment to do for college, but cant get it working

    Sorry if its sloppy

    Java Code:
    class Assignment{
    
    	//Attributes
    	private String carType;
    	private int carYear;
    	private String carReg;
    	private int numDays;
    	private double costDay;
    	double reduction;
    	double cost;
    
    	//Methods and Constructors
    	public Assignment(String regIn, String nameIn, int yearIn, int days, double costIn){
    
    			carType = nameIn;
    			carReg = regIn;
    			carYear = yearIn;
    			costDay = costIn;
    			numDays = days;
    
    	}
    
    	//Methods to read attributes
    	public void display()
    	{
    		System.out.println("Number of days for hire: " + numDays);
    		System.out.println("Car Reg Number: " + carReg);
    		System.out.println("Car Type : " + carType);
    		System.out.println("Car Year: " + carYear);
    		System.out.println("Cost: " + costDay);
    
    	}
    
    	public void display2()
    	{
    
    		System.out.println("\n\t" + carType +"   :   "+ carYear +"   :   "+ carReg +"   :   "+ numDays +"   :   "+ (costDay * numDays) + "\n");
    
    	}
    
    	public String gettypeOfCar()
    	{
    		return carType;
    	}
    	public void settypeOfCar(String type)
    	{
    		carType = type;
    	}
    
    	public String getregOfCar()
    	{
    		return carReg;
    	}
    	public void setregOfCar(String reg)
    	{
    		carReg = reg;
    	}
    
    	public int getyearOfCar()
    	{
    		return carYear;
    	}
    	public void setyearOfCar(int year)
    	{
    		carYear = year;
    	}
    
    	public double getdailyCost()
    	{
    		return costDay;
    	}
    	public void setdailyCost(double daily)
    	{
    		costDay = daily;
    	}
    
    	public double getnoDays()
    	{
    			return numDays;
    	}
    	public void setnoDays(int days)
    	{
    			numDays = days;
    	}
    
    	public void trimToSize()
    	{
    
    	}
    }
    the Tester :

    Java Code:
    import java.io.*;
    import java.util.*;
    
    class AssignmentTester2{
    	public static void main(String[]args){
    
    		Vector data = new Vector();
    		load(data);
    		choice(data);
    
    	}
    	static void choice(Vector data){
    		char choice1;
    
    		do{
    			System.out.println("\n\n****************************************");
    			System.out.println("*\tA. \tHire a Car\t       *");
    			System.out.println("*\tB. \tDelete Transaction     *");
    			System.out.println("*\tC. \tModify\t\t       *");
    			System.out.println("*\tD. \tDisplay All\t       *");
    			System.out.println("*\tE. \tSave\t\t       *");
    			System.out.println("*\tF. \tQuit\t\t       *");
    			System.out.println("****************************************\n\n");
    
    			System.out.print("\nPlease Choose One of the above : ");
    			choice1=Keyboard.readChar();
    			choice1=Character.toUpperCase(choice1);
    			//EasyIn.pause("Press *Enter* To continue");
    
    
    			switch(choice1){
    				case 'A' : type(data);break;
    				case 'B' : delete(data);break;
    				case 'C' : System.out.println("\nNot Yet Available");break;
    				case 'D' : display(data);break;
    				case 'E' : save(data);break;
    				case 'F' : System.out.println("Goodbye");break;
    				default : System.out.println("\n\tERROR Please Enter [A - F]");break;
    			}
    		}while(choice1 != 'F');
    	}
    
    
    	static void load(Vector data){
    
    		String str;
    		StringTokenizer t;
    
    		try
    		{
    			File f1       = new File("Transactions.txt");
    			FileReader fr = new FileReader(f1);
    			BufferedReader in = new BufferedReader(fr);
    
    			str = in.readLine();
    			while(str!=null)
    			{
    				Assignment rental =new Assignment();
    				t = new StringTokenizer(str);
    
    
    				String type = t.nextToken();
    				rental.settypeOfCar(type);
    
    				String reg = t.nextToken();
    				rental.setregOfCar(reg);
    
    				int year = Integer.parseInt(t.nextToken());
    				rental.setyearOfCar(year);
    
    				int day = Integer.parseInt(t.nextToken());
    				rental.setnoDays(day);
    
    				int cost = Integer.parseInt(t.nextToken());
    				rental.setdailyCost(cost);
    
    				Object o = (Object)rental;
    				data.add(rental);
    
    				str = in.readLine();
    			}
    
    			in.close();
    		}
    		catch(IOException e)
    		{
    		   System.out.print("File Doesnt Exist");
    		}
    
    		System.out.println();
    		System.out.print("File Found");
    	 }
    
    	static void type(Vector<Object> data){
    		double reduction=0, cost=0;
    		int choice;
    		String carType;
    		String carReg;
    		int carYear;
    		int numDays;
    		double costDay = 40;
    		double total;
    
    		System.out.print("\n\nCar Reg Number: ");
    		carReg=Keyboard.readString();
    		System.out.print("Car Type : ");
    		carType=Keyboard.readString();
    		System.out.print("Car Year: ");
    		carYear=Keyboard.readInt();
    		do{
    			System.out.print("Number of days for hire: ");
    			numDays=Keyboard.readInt();
    			if(numDays > 10){
    			System.out.print("\n\t\tERROR : Maximum 10 Days Rental\n\n");
    			}
    		}while(numDays>10);
    		System.out.print("\n\n");
    		if(carYear < 2004){
    
    			costDay = 30;
    
    		}
    
    		if(numDays > 5){
    			reduction = costDay - ((costDay/100)*9);
    			System.out.println("Car Cost/Day: $" + reduction);
    		}
    		else{
    			System.out.println("Car Cost/Day: $" + costDay);
    		}
    		if(numDays > 5){
    			cost = reduction * numDays;
    			System.out.println("Price in Total : $" + cost + "\n\n");
    		}
    		else{
    			System.out.println("Price in Total : $" + costDay * numDays + "\n\n");
    		}
    
    		Assignment rental = new Assignment(carReg, carType, carYear, numDays, costDay);
    
    		data.addElement((Object) rental);
    
    		rental = (Assignment) data.elementAt(0);
    
    		//EasyIn.pause("\nPress *Enter* To continue");
    
    	}
    
    	static String delete(Vector<Object> v){
    		String carRegNum;
    
    		for(int i =0;i<v.size();i++)
    		{
    			Assignment rental =(Assignment)v.elementAt(i);
    			rental.display();
    		}
    
    		System.out.print("Please Enter the Reg of the car that you have hired : ");
    		carRegNum=Keyboard.readString();
    
    		System.out.println("\nTransaction has been cancelled.\n\nThank You.");
    
    		return carRegNum;
    
    
    
    	}
    
    	static void display(Vector<Object> data){
    
    
    		for(int i =0;i<data.size();i++){
    		Assignment rental = (Assignment)(data.elementAt(i));
    		rental.display2();
    	}
    
    		/*try
            {
    			File f1       = new File("Transactions.txt");
    			FileReader fr = new FileReader(f1);
    			BufferedReader in = new BufferedReader(fr);
    
    			data = in.readLine();
    		    while(data!=null)
    		    {
    				System.out.println(data);
    				data = in.readLine();
    			}
    		 	in.close();
    		}
    		catch(IOException e)
    		{
    			System.out.print("Non-Existant File");
    		}
    
    		for(int i =0;i<data.size();i++){
    
    			Object o = data.elementAt(i);
    			Assignment rental =(Assignment) o;
    
    			rental.display2();
    
    		}*/
    
    		EasyIn.pause("Press *Enter* To continue");
    	}
    
    	static void save(Vector data){
    
    		System.out.println("***SAVED***");
    		try
    		{
    			FileWriter f1 = new FileWriter("Transactions.txt", true);
    			PrintWriter dataFile = new PrintWriter(f1);
    
    			for(int i=0;i<data.size();i++)
    			{
    				Assignment rent = (Assignment)(data.elementAt(i));
    				dataFile.println(rent.gettypeOfCar() + " " + rent.getyearOfCar()  + " " + rent.getregOfCar() + " " + rent.getnoDays() + " " + (rent.getnoDays() * rent.getdailyCost()));
    			}
    			dataFile.close();
    
    		}
    		catch(IOException e){
    			System.out.print("Non-Existant File");
    		}
    	}
    
    	static void quit(){
    
    		System.out.println("GoodBye");
    
    
    	}
    
    
    
    }
    My prob is in loading the vector.

    We have to load whatever is in the file to the vector to make it easier to print out and modify etc.

    When I compile I get a constructor error :

    Java Code:
    C:\Documents and Settings\Wierdal\My Documents\College\Java Programming 2\Assignment 1(p2)\AssignmentTester2.java:58: cannot find symbol
    symbol  : constructor Assignment()
    location: class Assignment
    				Assignment rental = new Assignment();
                                                                ^
    You can ignore modify and delete for the time being if ya dont mind, just trying to get this part workin first

    oh and the keyboard.readString, and EasyIn are college made programs I believe so I'll post em up for yas

    Java Code:
    // EasyIn.java
    
    import java.io.*;
    
    public abstract class EasyIn
    {
      static String s = new String();
      static byte[] b = new byte[512];
      static int bytesRead = 0;
    
      public static String getString()
      {
         boolean ok = false;
         while(!ok)
         {
            try
            {
               bytesRead = System.in.read(b);
               s = new String(b,0,bytesRead-1);
               s=s.trim();
               ok = true;
            }
            catch(IOException e)
            {
                System.out.println(e.getMessage());
            }
         }
    	return s;
       }
    
       public static int getInt()
       {
          int i = 0;
          boolean ok = false;
          while(!ok)
          {
             try
             {
                 bytesRead = System.in.read(b);
                 s = new String(b,0,bytesRead-1);
                   i = Integer.parseInt(s.trim());
                 ok = true;
             }
             catch(NumberFormatException e)
             {
                System.out.println("Make sure you enter an integer");
             }
             catch(IOException e)
             {
                 System.out.println(e.getMessage());
             }
         }
         return i;
     }
    
     public static byte getByte()
     {
         byte i = 0;
         boolean ok = false;
         while(!ok)
         {
            try
            {
                bytesRead = System.in.read(b);
                s = new String(b,0,bytesRead-1);
                i = Byte.parseByte(s.trim());
                ok = true;
            }
            catch(NumberFormatException e)
            {
                System.out.println("Make sure you enter a byte");
            }
            catch(IOException e)
            {
                 System.out.println(e.getMessage());
            }
         }
         return i;
     }
    
     public static short getShort()
     {
         short i = 0;
         boolean ok = false;
         while(!ok)
         {
            try
            {
                bytesRead = System.in.read(b);
                s = new String(b,0,bytesRead-1);
                i = Short.parseShort(s.trim());
                ok = true;
            }
            catch(NumberFormatException e)
            {
                System.out.println("Make sure you enter a short integer");
            }
            catch(IOException e)
            {
                 System.out.println(e.getMessage());
            }
         }
         return i;
     }
    
    
     public static long getLong()
     {
        long l = 0;
        boolean ok = false;
        while(!ok)
        {
           try
           {
               bytesRead = System.in.read(b);
                 s = new String(b,0,bytesRead-1);
               l = Long.parseLong(s.trim());
               ok = true;
           }
           catch(NumberFormatException e)
           {
               System.out.println("Make surre you enter a long integer");
           }
    
           catch(IOException e)
           {
                System.out.println(e.getMessage());
           }
        }
        return l;
     }
    
    
     public static double getDouble()
     {
        double d = 0;
        boolean ok = false;
        while(!ok)
        {
            try
            {
                 bytesRead = System.in.read(b);
                 s = new String(b,0,bytesRead-1);
                 d = (Double.valueOf(s.trim())).doubleValue();
                 ok = true;
            }
            catch(NumberFormatException e)
            {
                 System.out.println("Make sure you enter a decimal number");
            }
            catch(IOException e)
            {
               System.out.println(e.getMessage());
           }
        }
        return d;
     }
    
     public static float getFloat()
     {
         float f = 0;
         boolean ok = false;
         while(!ok)
         {
            try
            {
                bytesRead = System.in.read(b);
                s = new String(b,0,bytesRead-1);
                f = (Float.valueOf(s.trim())).floatValue();
                ok = true;
            }
            catch(NumberFormatException e)
            {
                System.out.println("Make sure you enter a decimal number");
            }
            catch(IOException e)
            {
                System.out.println(e.getMessage());
            }
         }
    	return f;
      }
    
      public static char getChar()
      {
         char c = ' ';
         boolean ok = false;
         while(!ok)
         {
            try
            {
               bytesRead = System.in.read(b);
               s = new String(b,0,bytesRead-1);
               if(s.trim().length()!=1)
               {
                 System.out.println("Make sure you enter a single character");
               }
               else
               {
                    c = s.trim().charAt(0);
                    ok = true;
               }
            }
            catch(IOException e)
            {
                System.out.println(e.getMessage());
            }
         }
         return c;
      }
    
    
      public static void pause()
      {
         boolean ok = false;
         while(!ok)
         {
             try
             {
                 System.in.read(b);
                 ok = true;
             }
             catch(IOException e)
             {
                  System.out.println(e.getMessage());
             }
         }
      }
    
      public static void pause(String messageIn)
      {
         boolean ok = false;
         while(!ok)
         {
             try
             {
                  System.out.print(messageIn);
                  System.in.read(b);
                  ok = true;
             }
             catch(IOException e)
            {
                  System.out.println(e.getMessage());
            }
        }
      }
    }

    Java Code:
    //********************************************************************
    //  Keyboard.java       Author: Lewis and Loftus
    //
    //  Facilitates keyboard input by abstracting details about input
    //  parsing, conversions, and exception handling.
    //********************************************************************
    
    import java.io.*;
    import java.util.*;
    
    
    public class Keyboard 
    {
        //*************  Error Handling Section  **************************
    
        private static boolean printErrors = true;
        private static int errorCount = 0;
    
        //-----------------------------------------------------------------
        //  Returns the current error count.
        //-----------------------------------------------------------------
        public static int getErrorCount() {
            return errorCount;
        }
    
        //-----------------------------------------------------------------
        //  Resets the current error count to zero.
        //-----------------------------------------------------------------
        public static void resetErrorCount(int count) {
            errorCount = 0;
        }
    
        //-----------------------------------------------------------------
        //  Returns a boolean indicating whether input errors are
        //  currently printed to standard output.
        //-----------------------------------------------------------------
        public static boolean getPrintErrors() {
            return printErrors;
        }
    
        //-----------------------------------------------------------------
        //  Sets a boolean indicating whether input errors are to be
        //  printed to standard output.
        //-----------------------------------------------------------------
        public static void setPrintErrors(boolean flag) {
            printErrors = flag;
        }
    
        //-----------------------------------------------------------------
        //  Increments the error count and prints the error message if
        //  appropriate.
        //-----------------------------------------------------------------
        private static void error(String str)  
        {  
            errorCount++;
            if (printErrors) {
                System.out.println(str);
            }
        }
    
    
        //*************  Tokenized Input Stream Section  ******************
    
        private static String current_token = null;
        private static StringTokenizer reader;
        private static BufferedReader in 
            = new BufferedReader (new InputStreamReader(System.in));
    
        //-----------------------------------------------------------------
        //  Gets the next input token assuming it may be on subsequent
        //  input lines.
        //-----------------------------------------------------------------
        private static String getNextToken() {
            return getNextToken(true);
        }
    
        //-----------------------------------------------------------------
        //  Gets the next input token, which may already have been read.
        //-----------------------------------------------------------------
        private static String getNextToken(boolean skip) 
        {  
            String token;
            if (current_token == null) {  
                token = getNextInputToken(skip);
            }
            else
            {  
                token = current_token;
                current_token = null;
            }
    
            return token;
        }
    
        //-----------------------------------------------------------------
        //  Gets the next token from the input, which may come from the
        //  current input line or a subsequent one. The parameter
        //  determines if subsequent lines are used.
        //-----------------------------------------------------------------
        private static String getNextInputToken(boolean skip) 
        {  
            final String delimiters = " \t\n\r\f";
            String token = null;
            try 
            {  
                if (reader == null) { 
                    reader = new StringTokenizer(in.readLine(), delimiters, true);
                }
    
                while (token == null || ((delimiters.indexOf (token) >= 0) && skip))
                {  
                    while ( !reader.hasMoreTokens() ) {
                        reader = new StringTokenizer(in.readLine(),delimiters,true);
                    }
                    
                    token = reader.nextToken();
                }
            }
            catch (Exception exception) {
                token = null;
            }
    
            return token;
    
        }
    
        //-----------------------------------------------------------------
        //  Returns true if there are no more tokens to read on the
        //  current input line.
        //-----------------------------------------------------------------
        public static boolean endOfLine() {
            return !reader.hasMoreTokens();
        }
    
    
        //*************  Reading Section  *********************************
    
        //-----------------------------------------------------------------
        //  Returns a string read from standard input.
        //-----------------------------------------------------------------
        public static String readString() 
        {  
            String str;
            try 
            {  
                str = getNextToken(false);
                while ( !endOfLine() ) {  
                    str = str + getNextToken(false);
                }
    
            }
            catch (Exception exception) 
            {  
                error("Error reading String data, null value returned.");
                str = null;
            }
    
            return str;
        }
    
        //-----------------------------------------------------------------
        //  Returns a space-delimited substring (a word) read from
        //  standard input.
        //-----------------------------------------------------------------
        public static String readWord() 
        {  
            String token;
            try {  
                token = getNextToken();
            } 
            catch (Exception exception) 
            {  
                error ("Error reading String data, null value returned.");
                token = null;
            }
    
            return token;
        }
    
        //-----------------------------------------------------------------
        //  Returns a boolean read from standard input.
        //-----------------------------------------------------------------
        public static boolean readBoolean() 
        {  
            String token = getNextToken();
            boolean bool;
            try
            {  
                if (token.toLowerCase().equals("true")) {
                    bool = true;
                }
                else if (token.toLowerCase().equals("false")) {
                    bool = false;
                }
                else 
                {  
                    error ("Error reading boolean data, false value returned.");
                    bool = false;
                }
            }
            catch (Exception exception)
            {  
                error ("Error reading boolean data, false value returned.");
                bool = false;
            }
    
            return bool;
        }
    
        //-----------------------------------------------------------------
        //  Returns a character read from standard input.
        //-----------------------------------------------------------------
        public static char readChar() 
        {  
            String token = getNextToken(false);
            char value;
            try 
            {  
                if (token.length() > 1) {   
                    current_token = token.substring (1, token.length());
                }   
                else { 
                    current_token = null;
                }
                
                value = token.charAt (0);
            } 
            catch (Exception exception) 
            {  
                error ("Error reading char data, MIN_VALUE value returned.");
                value = Character.MIN_VALUE;
            }
    
            return value;
        }
    
        //-----------------------------------------------------------------
        //  Returns an integer read from standard input.
        //-----------------------------------------------------------------
        public static int readInt() 
        {  
            String token = getNextToken();
            int value;
            try {  
                value = Integer.parseInt (token);
            } 
            catch (Exception exception) 
            {  
                error ("Error reading int data, MIN_VALUE value returned.");
                value = Integer.MIN_VALUE;
            }
    
            return value;
        }
    
        //-----------------------------------------------------------------
        //  Returns a long integer read from standard input.
        //-----------------------------------------------------------------
        public static long readLong() 
        {  
            String token = getNextToken();
            long value;
            try {  
                value = Long.parseLong (token);
            } 
            catch (Exception exception) 
            {  
                error ("Error reading long data, MIN_VALUE value returned.");
                value = Long.MIN_VALUE;
            }
    
            return value;
        }
    
        //-----------------------------------------------------------------
        //  Returns a float read from standard input.
        //-----------------------------------------------------------------
        public static float readFloat() 
        {  
            String token = getNextToken();
            float value;
            try {  
                value = (new Float(token)).floatValue();
            } 
            catch (Exception exception) 
            {  
                error ("Error reading float data, NaN value returned.");
                value = Float.NaN;
            }
    
            return value;
        }
    
        //-----------------------------------------------------------------
        //  Returns a double read from standard input.
        //-----------------------------------------------------------------
        public static double readDouble() 
        {  
            String token = getNextToken();
            double value;
    
            try {  
                value = (new Double(token)).doubleValue();
            } 
            catch (Exception exception) 
            {  
                error ("Error reading double data, NaN value returned.");
                value = Double.NaN;
            }
    
            return value;
        }
    
    } // end class
    Using Textpad if that makes any difference.

    Cheers

    Wierdal

  2. #2
    Supamagier is offline Senior Member
    Join Date
    Aug 2008
    Posts
    384
    Rep Power
    6

    Default

    That constructor error is really easy to fix. Tbh, I think you should be able to do that - since you have been able to make it so far.

    Anyway, the only constructor in your assignment class is
    Java Code:
    public Assignment(String regIn, String nameIn, int yearIn, int days, double costIn){
    
    			carType = nameIn;
    			carReg = regIn;
    			carYear = yearIn;
    			costDay = costIn;
    			numDays = days;
    
    	}
    While you're trying to call
    Java Code:
    new Assignment();
    You should pass the parameters to the Assignment constructor, so that would be:
    Java Code:
    new Assignment(String, String, int, int, double);
    Got it? ;)
    I die a little on the inside...
    Every time I get shot.

  3. #3
    wierdal is offline Member
    Join Date
    Oct 2008
    Posts
    6
    Rep Power
    0

    Default

    didnt work.

    The compiler tells me they arent initialized, so I initialize them.

    I compile and alls good.

    I rn first time, cant find transactions.txt cause hasnt been created, but continues on anyway.

    I put in 2 cars and save them to file, close the command prompt, compile and run again, then the prog doesnt work lol.

    Cheers for help all the same

  4. #4
    wierdal is offline Member
    Join Date
    Oct 2008
    Posts
    6
    Rep Power
    0

    Default

    k fixed my prob, but one other little prob, Moved onto my delete part, the stuff in the file goes into the Vector no prob, I run the program no prob, then when I try delete stuff, it detes from the vector but not from the txt file

    any ideas ??

  5. #5
    xcallmejudasx's Avatar
    xcallmejudasx is offline Senior Member
    Join Date
    Oct 2008
    Location
    Houston, TX & Flint, MI
    Posts
    609
    Rep Power
    6

    Default

    I havn't looked through the code but I'm assuming your text file is similar to this

    carType, carReg, carYear, costDay, numDays
    carType, carReg, carYear, costDay, numDays
    carType, carReg, carYear, costDay, numDays
    carType, carReg, carYear, costDay, numDays

    for each car within your vector. You can search through your text file and delete one line that matches what you want deleted before you remove it from the vector. Or you could just rewrite the entire vector to the file any time it's changed.
    Liberty has never come from the government.
    Liberty has always come from the subjects of government.
    The history of liberty is the history of resistance.
    The history of liberty is a history of the limitation of governmental power, not the increase of it.

Similar Threads

  1. for each prob
    By kusumathatavarthi in forum New To Java
    Replies: 7
    Last Post: 05-21-2008, 01:00 PM
  2. Prob with an exercise
    By jhetfield18 in forum New To Java
    Replies: 4
    Last Post: 02-15-2008, 06:11 PM
  3. Threading prob..
    By banie in forum Java Applets
    Replies: 0
    Last Post: 02-05-2008, 06:30 AM
  4. having prob with Exception
    By eva in forum New To Java
    Replies: 1
    Last Post: 01-04-2008, 05:44 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •