Help on a C program....

i'm trying to write an appendString function to stick two strings together, and I'm lost....
it's supposed to be a combination of a C & pascal string with values at the beginning to signify length & a terminating null
typedef char* String;
int lengthString(String self) {
     int k = -1; // start at self[-1] and keep going left from there
     int length = 0;
     while (self[k] == MAX_CHAR) {
          length += MAX_CHAR;
          k = k - 1;
     return self[k] + length;
void appendString(String* self, String suffix) {
     int k = 0;
     int length = lengthString(*self) + lengthString(suffix);
     int offset = 1 + (length / MAX_CHAR);
     String combo = (String) malloc(offset + length + 1);
     combo[0] = length % MAX_CHAR;
     combo = combo + offset;
     if (offset > 1)
          for (int i = 1; i < offset; i++)
               combo[0-i] = MAX_CHAR;
     for (k = 0; (*self)[k] != 0; k++)
          combo[k] = (*self)[k];
     for (int i = 0; suffix[i] != 0; i++, k++)
          combo[k] = suffix;
     combo[k] = 0;
     destroyString(*self);
     destroyString(suffix);
     *self = combo;
void destroyString(String self) {
     int offset = -1;
     while (self[offset] == MAX_CHAR)
          offset--;
     self = self + (char)offset;
     free(self);

weel try this, sorry if I wrong, i don't use C a long time
char* strcat(char *str1, char *str2)
    char *result;
    while(*str1){
       (*result) = (*str1);
       result++;
       str1++;
     while(*str2){
       (*result) = (*str2);
        result++;
        str2++;
     return result;
}

Similar Messages

  • PLEASE   CAN SOMEOME HELP ME INSTALL THIS PROGRAM????

    PLease  can someone help me install this program??  I am not computer literate.

    What program specifically are you struggling with? What operating system are you using? What happens when you try?

  • Help with a java program

    Hello. I'm posting in these forums because I really don't know where else to go. I have been trying for the past several days to figure out how to go about writing my program but to no avail. The project requires reading many lines each containing several different elements from a datafile named "DATA". A few examples of some lines from that file:
    Department number/Number of units received/Date on which the shipment arrived/Expiration date/Name of Object
    0 78 02/03/2001 02/12/2001 apples
    0 26 06/03/2001 06/10/2001 lemons
    3 62 03/06/2001 03/14/2001 hamburger
    What we have to do with this data is read all of it from the file, separate all the different elements, and based on input from the user, sort everything and print it out to the screen. If the user enters 03, the program will show everything that arrived and expired within the month of March, sorted by date.
    It is a pretty basic program, but my problem is that I have no idea how to go about reading in this data, putting it into a vector (probably the easiest method) or separating the different elements. I've gone to websites and looked through my textbooks but they didn't help much. If anyone has any resources that could help for writing such a program, or if anyone could offer help in writing the program, I would really appreciate it. I can also show what I've managed to write so far, or more details on how the program should work. Thanks in advance.
    Matt

    since im not a pro like some of the guys on here :),
    and believe me thiers people here, who could write your whole app in a hour.
    anyways my advice , would be to do a search on the forums for useing.bufferReader()
    i think you would need to read the file in with bufferreader then split up each line useing the stringTokenizer and then use some algorithm to compare
    the values and split them up into your vector arrays as needed.
    thier is also fileinputStream i think you can use that too.

  • Need help for writing extract program

    hi
    i need help for writing extract program to retriew data from legacy system.
    i already developed bdc programs for me31k and me21.
    my requirement is to write extract program s for those t.codes.
    to retriew data from legacy system and stored in flat file.

    i need help with a java program. it is a program that allows the user to enter a student's GPA, number of extracurricular activities, and number of service activities. The user can not enter a gpa above 4.0 or below 0. The user can not enter a negative number for the number of both activities. If the student meets the following criteria: 1) GPA of 3.8 or above and at least one extracurricular activity and one service activity, 2) GPA below 3.8 but at least 3.4 and a total of at least three extracurricular and service activities, 3) GPA below 3.4 but at least 3.0 and at least two extracurricular activities and three service activities, the message "Scholarship candidate" should display. If the student does not meet the criteria above, then the message"not a candidate" should display. Can you help me, please?
    You haven't posted ANY 'java program' for us to help with.
    The forum is NOT a coding service. It is to help you with YOUR code.
    Post the code you have written and SHOW us (don't just tell us) how you compile it and execute it and the results you get. Then we can help you with any problems you are are having.
    If you need help understanding just what the program should be doing you need to ask your instructor to clarify the assignment.

  • How we can use help & maintain view in program

    hi Gurus,
           how we can use help & maintain view in program?
            is it able to use in program?
    thanks in advance,
    Regards,
    Arun.

    Hi
    maintain view can be used in program using the function module 'VIEW_GET_DATA'.
    and help view is for search help.
    check this link below.
    [http://help.sap.com/saphelp_nw2004s/helpdata/en/cf/21ecd2446011d189700000e8322d00/content.htm]
    Regards,
    Sakthi.

  • Help. Installed the program from adobe in the trial under the same ID.

    Help. Installed the program from adobe in the trial under the same ID. After the expiration of 30 days, our company has registered for acquisition programs. We have introduced a new ID for a trial test, and adobe programs from running. Test time is exhausted. How to run the program under the new ID in a trial.
    Помогите. Установил пакет програм от адобе в триал под одним ID. После истечения 30 дней наша компания зарегистрировалась для приобретения программ. Мы ввели новый ИД для триал теста, а адоб программы не запускаются. Пробное время исчерпано. Как запустить программы под новым ИД в триале.

    Perhaps extend trial adobe product if 30 days is exhausted? If I go under a different ID that shows 0 days.
    Возможно продлить триал продукта адобе если 30 дней исчерпано? Если я захожу под другим ИД то показывает 0 дней.

  • I need help instantly on this program please

    import java.util.*;
    public class D3
              private static int[] z = new int[100000];
    private static int first=z[0];
              private static int last=z[n-1];
              private static int n=100000;
    public static void main(String args[])
    Scanner input=new Scanner(System.in);
    for(int i=0;i<z.length;i++)
              z=2*i;
    int seqSearch(z;50000;n); //method call 4 key where key=mid
              int binSearch(z;first;last;50000);
              int seqSearch(z;35467;n); //method call 4 key where key in the left half
              int binSearch(z;first;last;35467);
              int seqSearch(z;89703;n); //method call 4 key where key in the right half
              int binSearch(z;first;last;89703);
              public int seqSearch(int z[];int key;int n)
         long start = System.currentTimeMillis();
    int count=0;
    int ans=-1;
    for(int i=0;i<n;i++)
    if z[i]=key
    count++
    {ans=i
    break;}
    return ans;
    long elapsed = System.currentTimeMillis() - start;
    System.out.print("Execution Time:" + elapsed);
    System.out.print("# of Basic Operations:" + count);
         public int binSearch(int z[];int first;int last;int key)
         long start = System.currentTimeMillis();
         int count=0;
         if(last<first){
         count++;
         index=-1;
         else
         count++;
         int mid=(first+last)/2
         if(ket=z[mid]{
         index=mid;
         else
         if(key<z[mid]){
         index = binSearch(z[];first;mid-1;key);
         else
         index=binSearch(z[];mid+1;last;key);
         return index;
         long elapsed = System.currentTimeMillis() - start;
         System.out.print("Execution Time:" + elapsed);
         System.out.print("# of Basic Operations:" + count);
    // if anyone could tell me whats wrong with my code i'd be greatful...the program is supposed to perform binary and sequential search on a sorted array of 100000 numbers.once on an item in the middle of the array once on the right side of it and once on the left side...i also need to count the number of basic operations for the same number in both sequential and binary to see whats better.and i need to check the time...plz i need help now,,,

    "Guide to a first-time poster"
    you need to add exclamation marks to signify how urgent it is
    e.g.
    i need help instantly on this program please!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    capital letters is better
    I NEED HELP INSTANTLY ON THIS PROGRAM PLEASE!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    starting the italics on line 1, better again
    import java.util.*;
    public class D3
    private static int[] z = new int[100000];
    private static int first=z[0];
    private static int last=z[n-1];
    private static int n=100000;
    public static void main(String args[])
    Scanner input=new Scanner(System.in);
    for(int i=0;i<z.length;i++)
    z=2*i;
    int seqSearch(z;50000;n); //method call 4 key where key=mid
    int binSearch(z;first;last;50000);
    int seqSearch(z;35467;n); //method call 4 key where key in the left half
    int binSearch(z;first;last;35467);
    int seqSearch(z;89703;n); //method call 4 key where key in the right half
    int binSearch(z;first;last;89703);
    public int seqSearch(int z[];int key;int n)
    long start = System.currentTimeMillis();
    int count=0;
    int ans=-1;
    for(int i=0;i<n;i++)
    if z=key
    count++
    {ans=i
    break;}
    return ans;
    long elapsed = System.currentTimeMillis() - start;
    System.out.print("Execution Time:" + elapsed);
    System.out.print("# of Basic Operations:" + count);
    public int binSearch(int z[];int first;int last;int key)
    long start = System.currentTimeMillis();
    int count=0;
    if(last><first){
    count++;
    index=-1;
    else
    count++;
    int mid=(first+last)/2
    if(ket=z[mid]{
    index=mid;
    else
    if(key><z[mid]){
    index = binSearch(z[];first;mid-1;key);
    else
    index=binSearch(z[];mid+1;last;key);
    return index;
    long elapsed = System.currentTimeMillis() - start;
    System.out.print("Execution Time:" + elapsed);
    System.out.print("# of Basic Operations:" + count);
    and what about the dukes, offer 10 (never to be awarded, of course)
    do this, then sit back and watch the replies roll in.

  • Help with a simple program.

    I need some help writing a simple program. Can anybody help??
    thanks to all.
    2. HTML Java Source Code Reserved Word Highlighter
    Write a program that inputs a Java source code file and outputs a copy of that file with Java keywords surrounded with HTML tags for bold type. For example this input:
    public class JavaSource
    public static void main ( String[] args )
    if ( args.length == 3 )
    new BigObject();
    else
    System.out.println("Too few arguments.");
    will be transformed into:
    <B>public</B> <B>class</B> JavaSource
    <B>public</B> <B>static</B> <B>void</B> main ( String[] args )
    <B>if</B> ( args.length == 3 )
    <B>new</B> BigObject();
    <B>else</B>
    System.out.println("Too few arguments.");
    In a browser the code will look like this:
    public class JavaSource
    public static void main ( String[] args )
    if ( args.length == 3 )
    new BigObject();
    else
    System.out.println("Too few arguments.");

    Here is something that may get you started...
    import java.io.*; 
    import java.util.*; 
    public class HtmlJava{
         public static void main(String arg[]){
              if(arg.length!=1){
                   System.out.println("Usage java HtmlJava sourceFile");       
              else
                   new HtmlJava(arg[0]);
         HtmlJava(String source){
              try{
                   BufferedReader sourceReader=new BufferedReader(new InputStreamReader(new FileInputStream(source)));
                   BufferedWriter writer=new BufferedWriter(new OutputStreamWriter(new FileOutputStream(source+"Html.txt")));  
                   Vector keywords=new Vector();
                   addKeywords(keywords);
                   String line;
                   StringTokenizer tokenizer=null;
                   String word;
                   while((line=sourceReader.readLine () )!=null){
                        tokenizer=new StringTokenizer(line);
                        while(tokenizer.hasMoreTokens()){
                             word=tokenizer.nextToken();
                             if(keywords.contains(word)){
                                  writer.write(""+word+" ");
                             else{
                                  writer.write(word+" ");
                        writer.write("\r\n");
                   writer.close();
                   sourceReader.close(); 
                   System.out.println("Output File written to "+source+"Html.txt"); 
              catch(Exception ex){
                   ex.printStackTrace();      
         private void addKeywords(Vector keywords){
              keywords.addElement ( "abstract");
              keywords.addElement( "boolean");
              keywords.addElement( "break");
              keywords.addElement( "byte");
              keywords.addElement( "byvalue");
              keywords.addElement( "case");
              keywords.addElement( "cast");
              keywords.addElement( "catch");
              keywords.addElement( "char");
              keywords.addElement( "class");
              keywords.addElement( "const");
              keywords.addElement( "continue");
              keywords.addElement( "default");
              keywords.addElement( "do");
              keywords.addElement( "double");
              keywords.addElement( "else");
              keywords.addElement( "extends");
              keywords.addElement( "false");
              keywords.addElement( "final");
              keywords.addElement( "finally");
              keywords.addElement( "float");
              keywords.addElement( "for");
              keywords.addElement( "future");
              keywords.addElement( "generic");
              keywords.addElement( "goto");
              keywords.addElement( "if");
              keywords.addElement( "implements");
              keywords.addElement( "import");
              keywords.addElement( "inner");
              keywords.addElement( "instanceof");
              keywords.addElement( "int");
              keywords.addElement( "interface");
              keywords.addElement( "long");
              keywords.addElement( "native");
              keywords.addElement( "new");
              keywords.addElement( "null");
              keywords.addElement( "operator");
              keywords.addElement( "outer");
              keywords.addElement( "package");
              keywords.addElement( "private");
              keywords.addElement( "protected");
              keywords.addElement( "public");
              keywords.addElement( "rest");
              keywords.addElement( "return");
              keywords.addElement( "short");
              keywords.addElement( "static");
              keywords.addElement( "super");
              keywords.addElement( "switch");
              keywords.addElement( "synchronized");
              keywords.addElement( "this");
              keywords.addElement( "throw");
              keywords.addElement( "throws");
              keywords.addElement( "transient");
              keywords.addElement( "true");
              keywords.addElement( "try");
              keywords.addElement( "var");
              keywords.addElement( "void");
              keywords.addElement( "volatile");
              keywords.addElement( "while");
    }Hope it helped

  • Spotlight + help menu -- crashes any programs

    Has anyone else had a program crash when opening/typing into the Leopard help menu? I figured out the other day that if you accidentally open Spotlight when you have the help menu open, whatever program you're currently using will crash. It's very annoying bug. Anyone had this happen before?
    ~cm

    Thanks, Ian, for your helpful link! I treid all teh suggested solutions on that page, and finally wound up using the excellent Pacifist, found at http://www.charlessoft.com/
    With the help of Pacifist, I was able to get HelpViewer reinstalled and all my mac help menus are available again.
    Again, thanks for your help. I'm very grateful.
    Best,
    Zina

  • Help! All CS3 programs continuously crash!!

    I need help - all my CS3 programs have begun crashing! It's happened more frequently since installing Lepoard - but now its unbearably happening.
    I've called Adobe and was told that I can't get tech support because CS4 is now live - though Max was cool and suggested that I reset preferences (Ctrl+Option+Apple+Shift).
    Despite that quick fix - these programs continue to crash! NEED HELP PLEASE!

    Neil,
    Adobe called me on Wednesday stiil couls not figure out the problem, told me to go to Apple. So , I went to apple, upgraded my Ram to 4GB, full diagnostics, and did an archive reinstall.
    Worked great for 2 days. Thought I was in the clear, then today, I opened photoshop to open a few very small jpgs. (I had firefox open) Then all of a sudden Adobe installer show up in my dashboard and shows percentage numbers like it is installing something or getting ready to, and photoshop crashes. The adobe updater asks me if I want to install updates, I said no and cancelled out. All along I have been telling adobe that I think the problem has something to do with my registration. On all of my console crashes reports, adobe crashes right after all of theses notes about registration. I have had to re-register my adobe at least 3 times. The 1st time this all happened a technician told me I somehow had an educational copy, made me uninstall and then install a volume license with a new serial number. I told him none of this made sense as I bought a factory sealed CS3 Design Premiun form the apple store. I also told him I didn't want a volume license, I wanted what I purchased. He told me I had to do it. So I did and it didn't work. So the next technician I got, said that was crazy and she can't believe he made me do that, and that my original copy of CS# and serial number were fine and then had me uninstall that and reinstall mine. Naturally, every time I uninstall and reinstall adobe prompts me to register, which I do. But I feel like either adobe has some conflict and kicks me off because it thinks my registration is invalid or Adobe is conflicting with something on my computer. Which no- one can figure out- mean while I sill can't get any work done. Everyone who has looked at my computer said this is crazy, my computer is fine and can easily handle what i do, I don't have anything crazy on here that is supposed to conflict and I triple checked before I bought everything and have multiple times since. I still can not get any work done and am desparate!! Adobe is closed over the weekend and I have to be able to work on Monday.

  • Help with an array program

    I can't see how to calculate the lowest hours, highest hours, and average hours worked.
    These three values should be outputted each on a seperate line.
    I just can't figure this out.
    Any help please.
    This program will show the employees
    hours. It will have one
    class.It will use an array to keep
    track of the number of hours the employee
    has worked with the output to the monitor
    of the employees highest, lowest, and the
    average of all hours entered. */
    import java.util.*;
    import java.text.DecimalFormat;
    /*** Import Decimal Formating hours to format hours average. ***/
    public class cs219Arrays
         public static void main(String[] args)
              Scanner scannerObject = new Scanner(System.in);
              int[] employees ={20, 35, 40};
              int employeesHighest = 40;
              int employeesLowest = 20;
              double employeesAverage = 35;
              int[] firstEmployee = new int[1];
              int[] secondEmployee = new int[2];
              int[] thirdEmployee = new int[3];
              System.out.println("This program will accept hours worked for 3 employees.");
              System.out.println("Enter hours worked for employee #: ");
              System.out.println(".\n");
              employeesAverage = scannerObject.nextInt();
              for(int count =20; count <= 40; count++)
                             DecimalFormat df = new DecimalFormat("0.00");
                             System.out.println("pay: " employeesAverage " lowest " employeesHighest " Highest hours " employeesLowest " Lowest hours "+df.format(employeesAverage));
                             System.out.print("\n");
                             employeesAverage++;
    }/* end of body of first for loop */
              for(int count =20; count <= 40; count++)
                                       employeesAverage = employeesAverage + employeesHighest + employeesLowest;
                                       DecimalFormat df = new DecimalFormat("0.00");
                                       System.out.println("pay: $" employeesAverage " lowest " employeesHighest " Highest hours $" +df.format(employeesAverage));
                                       System.out.print("\n");
                                       employeesAverage++;
    }/* end of body of second for loop */
              for(int count =20; count <= 40; count++)
                                       employeesAverage = employeesAverage + employeesHighest + employeesLowest;
                                       DecimalFormat df = new DecimalFormat("0.00");
                                       System.out.println("pay: $" employeesAverage " lowest " employeesHighest " Highest hours $" +df.format(employeesAverage));
                                       System.out.print("\n");
                                       employeesAverage++;
    }/* end of body of third for loop */
              System.out.println("\n");
              DecimalFormat twoDigits = new DecimalFormat("0.00");
              /*** Create new DecimalFormat object named twoDigits ***/
              /*Displays number of hours, employees hours and average hours.*/
              System.out.println("You entered " + employeesAverage + " number of hours.");
              System.out.println("Your number of hours are " + twoDigits.format(employeesAverage));
              System.out.println("\n\n");
    }     /*End of method for data.*/
    {     /*Main method.*/
    }     /*End of main method.*/
    }     /*End of class cs219Arrays.*/

    Want help?
    Use the code formatting tags for starters. http://forum.java.sun.com/help.jspa?sec=formatting

  • Since downloading maverick, finder is not responsive; a safe restart did not help;  dock still works; programs can be accessed

    since downloading maverick, finder is not responsive; a safe restart did not help;  dock still works; programs can be accessed

    The startup disk may need repairing ...
    Launch Disk Utility located in HD > Applications > Utillities
    Select the startup disk on the left then select the First Aid tab.
    Click:  Verify Disk  (not Verify Disk Permissions)
    If DU reports errors, restart your Mac while holding down the Command + R keys. From there you should be able to acces the built in utilities in  OS X Recovery
    Make sure to back up all important files first before using OS X Recovery.
    OS X Recover does require a broadband high speed internet connection.

  • Can I get help downloading already purchased programs Adobe Creative Suite5 Design Premium and Adobe Acrobat X Pro onto my new mac computer?

    Can I get help downloading already purchased programs Adobe Creative Suite5 Design Premium and Adobe Acrobat X Pro onto my new mac computer?

    Downloadable installation files available:
    Suites and Programs:  CC 2014 | CC | CS6 | CS5.5 | CS5 | CS4, CS4 Web Standard | CS3
    Acrobat:  XI, X | 9,8 | 9 standard
    Premiere Elements:  13 |12 | 11, 10 | 9, 8, 7
    Photoshop Elements:  13 |12 | 11, 10 | 9,8,7
    Lightroom:  5.7.1| 5 | 4 | 3 | 2.7(win),2.7(mac)
    Captivate:  8 | 7 | 6 | 5
    Contribute:  CS5 | CS4, CS3
    Download and installation help for Adobe links
    Download and installation help for Prodesigntools links are listed on most linked pages.  They are critical; especially steps 1, 2 and 3.  If you click a link that does not have those steps listed, open a second window using the Lightroom 3 link to see those 'Important Instructions'.window using the Lightroom 3 link to see those 'Important Instructions'.

  • Help needed in report programming

    Hi All
    I am processing some data on first screen of a report transaction and an output is displayed on second screen. My requirement is that when I press back, I have to come to SAP initial screen.
    I have tried all options with 'LEAVE'. Problem is that control doesnt come even once in report, it goes into some standard code so I am unable to make changes..
    Kindly help.
    Thanks
    Dinesh
    <LOCKED BY MODERATOR - USE APPROPRIATE TITLES>
    <LOCKED BY MODERATOR - URGENT, PLEASE HELP OR SIMILAR ARE FORBIDDEN>
    Edited by: Alvaro Tejada Galindo on Aug 18, 2008 5:17 PM

    Hi,
    Since it is a report program. U have to set PF status in ur output page (either ALV or any other output format).
    In GUI status, triger the function code for BACK.
    Then, inside the event AT USER-COMMAND, code LEAVE PROGRAM for the BACK function.
    If it is an ALV output, the PF-status and User-command event should be called in the ALV function module.
    Regards,
    Prem

  • Need Help in Writing a program using a two-dimensional Array

    I need to write a program that takes 16 integers as inputs and determine whether the square is a magic square(sum of each row, column, and diagonal is the same constant) and display the result in a message Box. Please Help!!!!!

    stick the 16 ints in an int[4][4] and then just write the methods. i guess thats the hard part though. the most cumbersome and longest possible way to do it is just write everything out. ie if(int[1][1] + int[2][1] + int[3][1] etc...). a better way would be to use a bunch or for loops, but you'll have to figure that out yourself.

  • Can you help me with my program please?

    hi all,
    I have a problem with the sellMilk function at the Milk class I don't know how to write it right I've tried everything so I need you to help me.
    this function should check the expiry date of the milk and sell the required amount if it is not expired. if it was expired just delete the milkbox.
    I have cases like if the first box has 5 kg and not expired , second box has 10 kg and expired, third box has 8 kg and not expired .. and if the required amount to sell is 6 kg for example it should work like this: first box should become zero because 5 kg has been sold and remainder is 1 .. so it should check the expiry date of the second box and it is expired so delete it. and then check the third box's expiry date and it is not expired so 8-1 = 7 .. and by that way 6 kg has been sold.
    my program it just delete the expired box if it was the first element.
    my code doesn't work well like that! here is the full program so you can check the code to help me please ..
    the problem is just with SellMilk() at the Milk Class
    Thank you
    import java.io.*;
    import java.text.*;
    import java.util.*;
    public class Market
        public static void main(String args[ ])
        { System.out.print("Enter the Market name: " );
            String name1 = Stdin.readLine();
            Market_Store mymarketstore = new Market_Store(name1);
       System.out.println("Welcome To " +name1+" Market ");
       System.out.println("");
            System.out.println("1-Stock new Milk");
            System.out.println("2-Stock new Milk Box");
            System.out.println("3-Sell");
            System.out.println("4- Display");
            System.out.println("");
            System.out.print("Enter your choice: ");
            int choice = Stdin.readInteger();
            while (choice != 5)
                switch (choice)
                case 1:
                 mymarketstore.stockNewMilk();
                    break;
                case 2:
                    mymarketstore.stockMilkBox();
                    break;
                    case 3:
             mymarketstore.sell();
                break;
                case 4:
               mymarketstore.display();
                            break;
                            case 5:
                default:
                    System.out.println("wrong Number");
                    System.out.println("Enter a number between 1 to 4 ");
                    System.out.println("Enter 5 to Exit");
                    break;
                System.out.println("");
              System.out.println("Welcome To " +name1+" Market ");
       System.out.println("");
            System.out.println("1-Stock new Milk");
            System.out.println("2-Stock new Milk Box");
            System.out.println("3-Sell");
            System.out.println("4-Display");
            System.out.println("");
             System.out.print("Enter your choice: ");
                choice = Stdin.readInteger();
    class Market_Store
            private String name;
            private Vector mymilk;
            public Market_Store(String n)
                    name=n;
                    mymilk = new Vector();
            public void stockNewMilk()
                    String N;//milk type
                    System.out.print("Enter the type of the milk: ");
                    N=Stdin.readLine();
                    Milk  m1 = new Milk (N);
                    mymilk.addElement(m1);
            public void stockMilkBox()
            System.out.println("Milk Available in stock : ");
            for (int i=0; i<mymilk.size(); i++){
            Milk m2 = (Milk)mymilk.elementAt(i);
            System.out.print(i+1+")");
            System.out.println(m2.getMilkType());  }
                    System.out.print("Enter the number of the milk to stock new box: ");
            int     ii = Stdin.readInteger();
            ((Milk)(mymilk.elementAt(ii-1))).addNewBox();
            }//end stockMilkBox
            public void sell()
                    //sell specific type of milk
                   System.out.println("Milk Available in stock : ");
            for (int i=0; i<mymilk.size(); i++){
            Milk m2 = (Milk)mymilk.elementAt(i);
            System.out.print(i+1+")");
            System.out.println(m2.getMilkType());
                                   System.out.print("Enter the number of the milk to sell:  ");
            int     ii = Stdin.readInteger();
    System.out.print("Enter the amount required in Kg:  ");
    double amount = Stdin.readDouble();
            ((Milk)(mymilk.elementAt(ii-1))).sellMilk(amount);
            public void display()
            {      System.out.println("Milk Available in stock : ");
            for (int i=0; i<mymilk.size(); i++){
            Milk m2 = (Milk)mymilk.elementAt(i);
            System.out.print(i+1+")");
            System.out.println(m2.getMilkType());
                    System.out.print("Enter the number of the milk to display:  ");
            int     ii = Stdin.readInteger();
                    ((Milk)(mymilk.elementAt(ii-1))).display();
    class MilkBox
            private Date expiredate;
            private Date date;
            private double stock;
            public MilkBox(double stck, Date ed)
                     date = new Date();
                    expiredate = ed;
            public double getStock()
             return stock;     }
            public Date getDate()
                     return date;
    public void setStock(double st)
    { stock = st;}
    public void setExDate(Date dd)
    {expiredate = dd;}
            public Date getExDate()
                     return expiredate;
      public   double sellMilkBox(double amount)
            double excessAmount = 0;
            if (amount < stock)
                double newAmount = stock - amount;
                setStock(newAmount);
            else  
                excessAmount = amount - stock;
                setStock(0);
            return excessAmount;
    public     void display()
                            System.out.println("The box of "+date+" has " +stock+" KG");
    class Milk
            private String Mtype;//milk type
            private Vector mybox;//vector of batches
            public Milk (String n)
                    Mtype =n;
            mybox = new Vector();
      public  void addNewBox()
    double stook;
    System.out.print("Enter the weight of the box: ");
    stook = Stdin.readDouble();
         Date exdate;//expirey date
    System.out.println("Enter the expirey date of the milk box:");
           int d; int m1; int y;
              System.out.println("Enter Year:" );
              y = Stdin.readInteger();
              System.out.println("Enter Month:" );
              m1 = Stdin.readInteger();
              System.out.println("Enter Day:" );
              d = Stdin.readInteger();
                   Calendar r=new GregorianCalendar(y,m1,d);
                    exdate= r.getTime();
                    //send the attributes to Box constructor
                   MilkBox newBox = new MilkBox(stook,exdate);
                    newBox.setStock(stook);
                    newBox.setExDate(exdate);
                    mybox.addElement(newBox);
       public void display()
                    System.out.println("Milk "+Mtype);
                            for (int i=0; i<mybox.size(); i++){
                    MilkBox b= (MilkBox)mybox.elementAt(i);
                    b.display();
    public double sellMilk (double amount)
       for(int i=0;i<mybox.size();i++)
               MilkBox b = (MilkBox)mybox.elementAt(i);
                double stock = b.sellMilkBox(amount);
                double value = b.getStock();
                Date ExpireyDate = b.getExDate();
      if ( ExpireyDate.before(new Date()))
    {  mybox.removeElementAt(i);
            System.out.println("it has expired date");
    if (stock >1|| value  ==  0 && ExpireyDate.after(new Date()))
    {       mybox.remove(b);  
    amount = stock;
    if ( ExpireyDate.before(new Date()))
    {  mybox.removeElementAt(i);
            System.out.println("it has expired date");
      if(amount != 0)
      System.out.println("The extra amount is "+amount+ " KG");
    return amount;}
    public String getMilkType()
    { return Mtype;}
    //set method
    void setMilkType(String n)
    { Mtype = n;}
    }//end class milk
    //STDIN FILE
    final class Stdin
       public static BufferedReader reader=new BufferedReader
        (new InputStreamReader(System.in));
       public static String readLine()
       while(true)
       try{
           return reader.readLine();
           catch(IOException ioe)
             reportError(ioe);
           catch(NumberFormatException nfe)
            reportError(nfe);
       public static int readInteger()
        while(true)
        try{
        return Integer.parseInt(reader.readLine());
        catch(IOException ioe)
        reportError(ioe);
        catch(NumberFormatException nfe)
        reportError(nfe);
       public static double readDouble()
        while(true)
        try{
        return Double.parseDouble(reader.readLine());
        catch(IOException ioe)
        reportError(ioe);
        catch(NumberFormatException nfe)
        reportError(nfe);
        public static void reportError (Exception e)
        System.err.println("Error input:");
        System.err.println("please re-enter data");
        }Edited by: mshadows on Dec 22, 2007 12:06 AM

    ok here is the code that has the problem .. what's wrong with it?
    public double sellMilk (double amount)
       for(int i=0;i<mybox.size();i++)
               MilkBox b = (MilkBox)mybox.elementAt(i);
                double stock = b.sellMilkBox(amount);
                double value = b.getStock();
                Date ExpireyDate = b.getExDate();
      if ( ExpireyDate.before(new Date()))
    {  mybox.removeElementAt(i);
            System.out.println("it has expired date");
    if (stock >1|| value  ==  0 && ExpireyDate.after(new Date()))
    {       mybox.remove(b);  
    amount = stock;
    if ( ExpireyDate.before(new Date()))
    {  mybox.removeElementAt(i);
            System.out.println("it has expired date");
      if(amount != 0)
      System.out.println("The extra amount is "+amount+ " KG");
    return amount;}

Maybe you are looking for

  • Row and column headings-how to print without them

    Currently Epson C64 and appleworks 6.2 How can I print the spreadsheet without the row and column headings as there doesnt seem to be a place to choose whether to how or not Thanks for replies Whilst writing, too many instances of the coloured wheel

  • Error Starting OIM Weblogic

    Hi, I am not able to start OIM Weblogic.Getting following error in the log ERROR,01 Apr 2010 18:58:50,285,[org.apache.beehive.netui.pageflow.internal.AdapterManager],ServletContainerAdapter manager not initialized correctly. ERROR,01 Apr 2010 18:58:5

  • Possible fix for car unit Bluetooth connectivity problems (it fixed mine)

    Ok, I understand this only fixed my particular problem, so it may not work with every Bluetooth head unit. I have a Pioneer deh-p7000bt and it worked beautifully with my iPhone 3GS. Once I got my iPhone 4 I restored it from a backup of my 3GS. I had

  • Help please- Upgrading to Leopard and bootcamp

    I have an iMac with Tiger and a Windows partition. I want to upgrade to Leopard but not go through the Windows install process again. What I'd like to know is, does the upgrade to Leopard automatically detect the Windows partition, upgrade the Bootca

  • Muiltiple menu items and unwanted square

    I'm not sure what happed but all of a sudden i have multiple menu items on the main apple menu and there is a square box either on the desktop or various applications such as entourage or word etc. I'm not sure if it has something to do with user pre