Split array list

I asked this question yesterday and I guess I wasn't explicit in my problem as I received answers on formatting, but not in how to solve the Java/Ingres date descrepancy.
I have this arrayList, with these values:
2007-6-15
2006-6-15
2005-6-15
This list should show 2007-7-15, not 2007-6-15, which is how it looks.
Do you know how to cut the arrayList up, change the month string to an int so I can add one and put it back together so I can tick through it with the iterator. I've been trying many different things, but nothing seems to work.
ArrayList datesList = DAO.findPtoDatesList(request.getRemoteUser().toString());
ArrayList showYearList = new ArrayList();
List temp1 = new ArrayList();
List temp2 = new ArrayList();
List temp3 = new ArrayList();
for (int i = 0; i < historyDatesList.size(); i++){
temp1 = historyDatesList.subList(0,historyDatesList.indexOf("-"));
System.out.println("temp1="+temp1);
**it chokes right there - doesn't return my temp1, let alone try parsing anything..
showYearList.add(temp1+"-"+temp2+"-"+temp3);
Any suggestions would be wonderful.

Do you actually understand what List#indexOf() and List#subList() does? It is certainly not the same as String#indexOf() and String#substring(). Those codings makes really no sense in your problem.
I highly recommend you to learn to find, read and understand the API documentations. Here they are.
java.lang.String: http://java.sun.com/javase/6/docs/api/java/lang/String.html
java.util.List: http://java.sun.com/javase/6/docs/api/java/util/List.html
And optionally:
java.text.SimpleDateFormat: http://java.sun.com/javase/6/docs/api/java/text/SimpleDateFormat.html
java.util.Date: http://java.sun.com/javase/6/docs/api/java/util/Date.html
java.util.Calendar: http://java.sun.com/javase/6/docs/api/java/util/Calendar.html

Similar Messages

  • Accessing Array and Iterating Array list

    Hi,
    I want some advice on how to iterate through a Array list which has an array of tasks/processes and make calls to the corresponding subprocess for each element in the list using BPM 11g
    We are looking for a BPMN approach.
    Any example or ideas would be of great help.
    My requirement states that i will get a list of tasks from a Rules Engine and i have to use BPM to iterate through the tasks and make calls to each tasks(which is a subprocess call).
    In Oracle BPM 11g I would like to use a multi-instance subprocess to send a task to a user for each item in an array. There are an unknown number of rows in the array. Does anyone have a good example of how to do this?
    I am using BPM Oracle 11g but any help 10 will also help us.
    I am reposting again this question , hoping that someone will help us
    Thanks

    Others probably are getting it, but I'm not really sure what it is that you're tyring to do with the list of instances.
    I'm getting lost in two areas. First, you mentioned you have a rules engine returning a list of instances. Mostly out of curiosity - why do you have an array of instances being created by a rules engine? What is the use case? Asking because I'm sure to learn something new from you on this - I'm used to seeing a lot of things coming back from an invoked rule, but never an array of instances before.
    Second (sure you know this), in both 10g and 11g there is a Split-N activity that you can use to parse (as the name implies) "N" number of instances. This "N" is discoverable at runtime. If you have 14 instances in your array at runtime, it would go into a Split-N activity and 14 instances would automatically be spawned. The 14 instances would flow from the Split-N to its corresponding Join activity in the process.
    Dan

  • PowerShell - Start-Job - Synchronised Array list

    Hi all,
    I am trying to write a script using start-job against a list of machines. The script is to query a target machine event log using get-winevent cmdlet. I supply the whole code that queries the eventlog in a scriptblock. In order to capture the output (one
    psobject for each of the scriptblock jobs) I am trying to use a synchronised arraylist. I do not know the full details of how to use the synchronised arraylist but I have put together the below script (by referring to some of the online articles). But the
    script does not work as intended. The individual scriptblocks do not seem to be referring to the global arraylist variable while appending the results.
    Would any of you be able to shed any light on it?
    Please note, the script without the PowerShell Jobs works fine(that is linear execution which is really time-consuming). Also, even with using psJobs, the script works when I try to dump the result of each job into a csv from within the job itself. But I
    want to avoid this situation because due to the asynchronous execution there might be contention for the csv by more than one jobs at the same time. Hence I want to use the synchronised array list.
    $InputCSV = "$(Split-Path $SCRIPT:MyInvocation.MyCommand.Path -parent)\backupexec.csv"
    $OutputCSV = "$(Split-Path $SCRIPT:MyInvocation.MyCommand.Path -parent)\Reports\BackupExec_Output_$(Get-Date -format "ddMMyyyy")_$((Get-Date).DayOfWeek).csv"
    $OutputArray = [System.Collections.ArrayList]::Synchronized((New-Object System.Collections.ArrayList))
    $counter=1
    $jobs=@{};
    $jobcounter=0;
    Import-CSV $InputCSV | ForEach {
    $Comp_Name=$_.ServerName;
    $Counter+=1;
    $Scriptblock={
    Try {
    $IsthereAnyResult= @()
    $IsthereAnyResult= Get-WinEvent -ComputerName $Using:Comp_Name -ErrorAction SilentlyContinue -FilterHashTable @{LogName='application';ProviderName='Backup Exec';ID=57755; StartTime=(Get-Date).AddDays(-1)}
    $props = @{
    "Server Name" = ($event.MachineName -split '\.')[0];
    "Event ID" = $event.ID;
    "Time Logged" = $event.TimeCreated;
    "Backup Result" = Switch ($event.ID) { '57755' {"Success - Skipped"}
    '34113' {"Failed"}
    '34112' {"Success"} };
    "Message" = $event.Properties[0].value -replace '\n' -replace '\r';
    $OutputArray += New-Object PSObject -Property $props
    } #end try get-winevent
    Catch { } #end Catch
    } #end scriptblock
    $jobs[$jobcounter]= Start-job -name $("Job_$jobcounter") -ScriptBlock $Scriptblock
    $jobcounter+=1;
    While((Get-Job -State 'Running').Count -ge 10) {
    Start-Sleep -Milliseconds 10
    } # end main foreach
    Get-Job | Wait-Job
    $OutputArray | Select-Object "Server Name","Event ID","Time Logged","Backup Result","Message" | Export-CSV -force -Path $OutputCSV -NoTypeInformation -Append

    How about this?
    I use wmi win32_ntlogevent which i prefer ..  Timeservice is just for example ...
    Change the scriptblock to your needs and report the result :]
    Param ([int]$BatchSize=2)
    #list of servers
    [array]$source = (get-adcomputer -filter {name -like "server*"}) |select -expandproperty dnshostname
    $blok = {
    get-wmiobject Win32_NTLogEvent -Filter "(Logfile='System') and (SourceName = 'Microsoft-Windows-Time-Service')" |select -first 10 |select __server,@{n="EventCode";e={switch($_.EventCode){37{"37 - Receiving"}35{"35 - Synchronizing"}129{"129 - NTP Fail"}default{"Other EventCode"}}}},@{n="Date";e={$_.ConvertToDateTime($_.TimeGenerated)}},message
    $elapsedTime = [system.diagnostics.stopwatch]::StartNew()
    $result = @()
    $itemCount = 0
    ## checking running jobs
    if (get-job|? {$_.name -like "Script*"}){
    write-host "ERROR: There are pending background jobs in this session:" -back red -fore white
    get-job |? {$_.name -like "Script*"} | out-host
    write-host "REQUIRED ACTION: Remove the jobs and restart this script" -back black -fore yellow
    $yn = read-host "Automatically remove jobs now?"
    if ($yn -eq "y"){
    get-job|? {$_.name -like "Script*"}|% {remove-job $_}
    write-host "jobs have been removed; please restart the script" -back black -fore green
    exit
    $i = 0
    $itemCount = $source.count
    Write-Host "Script will run against $itemcount servers!"
    ## Script start time mark
    write-host "Script started at $(get-date -uFormat "%Y/%m/%d %H:%M:%S")".padright(60) -back darkgreen -fore white
    write-host " (contains $itemCount unique entries)" -back black -fore green
    $activeJobCount = 0
    $totalJobCount = 0
    write-host "Submitting background jobs..." -back black -fore yellow
    for ($i=0; $i -lt $itemCount;$i += $batchSize){
    $activeJobCount += 1; $totalJobCount += 1; $HostList = @()
    $HostList += $source |select -skip $i -first $batchsize
    $j = invoke-command -computername $Hostlist -scriptblock $blok -asjob
    $j.name = "Script`:$totalJobCount`:$($i+1)`:$($getHostList.count)"
    write-host "+" -back black -fore cyan -nonewline
    write-host "`n$totaljobCount jobs submitted, checking for completed jobs..." -back black -fore yellow
    while (get-job |? {$_.name -like "Script*"}){
    foreach ($j in get-job | ? {$_.name -like "Script*"}){
    $temp = @()
    if ($j.state -eq "completed"){
    $temp = @()
    $temp += receive-job $j
    $result += $temp
    remove-job $j
    $ActiveJobCount -= 1
    write-host "-" -back black -fore cyan -nonewline
    elseif ($j.state -eq "failed"){
    $temp = $j.name.split(":")
    if ($temp[1] -eq "R"){
    $temp = @()
    $temp += receive-job $j
    $result += $temp
    remove-job $j
    $ActiveJobCount -= 1
    write-host "-" -back black -fore cyan -nonewline
    else{
    write-host "`nFailure detected in job: $($j.name)" -back black -fore red
    $temp = @()
    $temp += receive-job $j
    $result += $temp
    remove-job $j
    $ActiveJobCount -= 1
    if ($result.count -lt $itemCount){
    sleep 3
    write-host " "
    write-host "Script finished at $(get-date -uFormat "%Y/%m/%d %H:%M:%S")".padright(60) -back darkgreen -fore white
    write-host (" Elapsed Time : {0}" -f $($ElapsedTime.Elapsed.ToString())) -back black -fore green
    $result |select __server,eventcode,Date,message |ft -auto
    write-host " Script completed all requested operations at $(get-date -uFormat "%Y/%m/%d %H:%M:%S")".padright(60) -back darkgreen -fore white
    write-host (" Elapsed Time : {0}" -f $($ElapsedTime.Elapsed.ToString())) -back black -fore green

  • Problem passing multiple array lists to a single method

    Hi, all:
    I have written a generic averaging method that takes an array list full of doubles, adds them all up, divides by the size of the array list, and spits out a double variable. I want to pass it several array lists from another method, and I can't quite figure out how to do it. Here's the averager method:
         public double averagerMethod (ArrayList <Double> arrayList) {
              ArrayList <Double> x = new ArrayList <Double> (arrayList); //the array list of integers being fed into this method.
              double total = 0;//the total of the integers in that array list.
              for (int i = 0; i < x.size(); i++) {//for every element in the array list,
                   double addition = x.get(i);//get each element,
                   total = total + addition; //add it to the total,
              double arrayListSize = x.size();//get the total number of elements in that array list,
              double average = total/arrayListSize;//divide the sum of the elements by the number of elements,
              return average;//return the average.
         }And here's the method that sends several array lists to that method:
         public boolean sameParameterSweep (ArrayList <Double> arrayList) {
              sameParameterSweep = false;//automatically sets the boolean to false.
              arrayList = new ArrayList <Double> (checker);//instantiate an array list that's the same as checker.
              double same = arrayList.get(2); //gets the third value from the array list and casts it to double.
              if (same == before) {//if the third value is the same as the previous row's third value,
                   processARowIntoArrayLists(checker);//send this row to the parseAParameterSweep method.
                   sameParameterSweep = true;//set the parameter sweep to true.
              if (same != before) {//if the third value is NOT the same,
                   averagerMethod(totalTicks);//go average the values in the array lists that have been stored.
                   averagerMethod(totalNumGreens);
                   averagerMethod(totalNumMagentas);
                   sameParameterSweep = false;
              before = same; //problematic!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
         return sameParameterSweep;
         }Obviously, the problem is that I'm not passing the array lists from this method to the averager method the right way. What am I doing wrong?

    Encephalopathic wrote:
    There are several issues that I see, but the main one is that you are calculating average results but then just discarding them. You never assign the result to a variable.
    In other words you're doing this:
    averagerMethod(myArrayList);  // this discards the resultinstead of this:
    someDoubleVariable = averagerMethod(myArrayList); // this stores the resultAlso, do you wish to check for zero-sized array lists before calculating? And what would you return if the array list size were zero?So in solving that problem, I've come up with another one that I can't figure out, and I can't fix this problem until I fix that.
    I have several thousand lines of data. They consist of parameter sweeps of given variables. What I'm trying to do is to store pieces of
    data in array lists until the next parameter adjustment happens. When that parameter adjustment happens, I want to take the arraylists
    I've been storing data in, do my averaging thing, and clear the arraylists for the next set of runs under a given parameter set.
    Here's the issue: I'm having the devil of a time telling my application that a given parameter run is over. Imagine me doing stuff to several variables (number of solders, number of greens, number of magentas) and getting columns of output. My data will hold constant the number of soldiers, and for, say, ten runs at 100 soldiers, I'll get varying numbers of greens and magentas at the end of each of those ten runs. When I switch to 150 soldiers to generate data for ten more runs, and so forth, I need to average the number of greens and magentas at the end of the previous set of ten runs. My problem is that I can't figure out how to tell my app that a given parameter run is over.
    I have it set up so that I take my data file of, say, ten thousand lines, and read each line into a scanner to do stuff with. I need to check a given line's third value, and compare it to the previous line's third value (that's the number of soldiers). If this line has a third value that is the same as the previous line's third value, send this line to the other methods that break it up and store it. If this line has a third value that is NOT the same as the previous line's third value, go calculate the averages, clear those array lists, and begin a new chunk of data by sending this line to the other methods that break it up and store it.
    This is not as trivial a problem as it would seem at first: I can't figure out how to check the previous line's third value. I've written a lot of torturous code, but I just deleted it because I kept getting myself in deeper and deeper with added methods. How can I check the previous value of an array list that's NOT the one I'm fiddling with right now? Here's the method I use to create the array lists of lines of doubles:
         public void parseMyFileLineByLine() {
              totalNumGreens = new ArrayList <Double>();//the total number of greens for a given parameter sweep
              totalNumMagentas = new ArrayList <Double>();//the total number of magentas for a given parameter sweep.
              totalTicks = new ArrayList <Double>();//the total number of ticks it took to settle for a given parameter sweep.
              for (int i = 8; i < rowStorer.size() - 2; i++) {//for each line,
                   checker = new ArrayList <Double>();//instantiates an array list to store each piece in that row.
                   String nextLine = rowStorer.get(i); //instantiate a string that contains all the information in that line.
                   try {
                        Scanner rowScanner = new Scanner (nextLine); //instantiates a scanner for the row under analysis.
                        rowScanner.useDelimiter(",\\s*");//that scanner can use whitespace or commas as the delimiter between information.
                        while (rowScanner.hasNext()) {//while there's still information in that scanner,
                             String piece = rowScanner.next(); //gets each piece of information from the row scanner.
                             double x = Double.valueOf(piece);//casts that stringed piece to a double.
                             checker.add(x);//adds those doubles to the array list checker.
                   catch (NoSuchElementException nsee) {
                        nsee.printStackTrace();
                   //System.out.println("checker contains: " + checker);
                   processARowIntoArrayLists(checker);//sends checker to the method that splits it up into its columns.
         }

  • Is possible to pass array/list as parameter in TopLink StoredProcedureCall?

    Hi, We need to pass an array/List/Vector of values (each value is a 10 character string) into TopLink's StoredProcedureCall. The maximum number of elements on the list is 3,000 (3,000 * 10 = 30,000 characters).
    This exposed two questions:
    1. Is it possible to pass a Vector as a parameter in TopLink's StoredProcedureCall, such as
    StoredProcedureCall call = new StoredProcedureCall();
    call.setProcedureName("STORED_PROCEDURE_NAME");
    call.addNamedArgument("PERSON_CODE");
    Vector strVect = new Vector(3000);
    strVect.add(“ab-gthhjko”);
    strVect.add(“cd-gthhjko”);
    strVect.add(“ef-gthhjko”);
    Vector parameters = new Vector();
    parameters.addElement(strVect);
    session.executeQuery(query,parameters);
    2. If the answer on previous question is yes:
    - How this parameter has to be defined in Oracle’s Stored Procedure?
    - What is the maximum number of elements/bytes that can be passed into the vector?
    The best way that we have found so far was to use single string as a parameter. The individual values would be delimited by comma, such as "ab-gthhjko,cd-gthhjko,ef-gthhjko..."
    However, in this case concern is the size that can be 3,000 * 11 = 33, 000 characters. The maximum size of VARCHAR2 is 4000, so we would need to break calls in chunks (max 9 chunks).
    Is there any other/more optimal way to do this?
    Thanks for your help!
    Zoran

    Hello,
    No, you cannot currently pass a vector of objects as a parameter to a stored procedure. JDBC will not take a vector as an argument unless you want it to serialize it (ie a blob) .
    The Oracle database though does have support for struct types and varray types. So you could define a stored procedure to take a VARRAY of strings/varchar, and use that stored procedure through TopLink. For instance:
    StoredProcedureCall call = new StoredProcedureCall();
    call.setProcedureName("STORED_PROCEDURE_NAME");
    call.addNamedArgument("PERSON_CODE");
    oracle.sql.ArrayDescriptor descriptor = new oracle.sql.ArrayDescriptor("ARRAYTYPE_NAME", dbconnection);
    oracle.sql.ARRAY dbarray = new oracle.sql.ARRAY(descriptor, dbconnection, dataArray);
    Vector parameters = new Vector();
    parameters.addElement(dbarray);
    session.executeQuery(query,parameters);This will work for any values as long as you are not going to pass in null as a value as the driver can determine the type from the object.
    dataArray is an Object array consisting of your String objects.
    For output or inoutput parameters you need to set the type and typename as well:
      sqlcall.addUnamedInOutputArgument("PERSON_CODE", "PERSON_CODE", Types.ARRAY, "ARRAYTYPE_NAME"); which will take a VARRAY and return a VARRAY type object.
    The next major release of TopLink will support taking in a vector of strings and performing the conversion to a VARRAY for you, as well as returning a vector instead of a VARRAY for out arguments.
    Check out thread
    Using VARRAYs as parameters to a Stored Procedure
    showing an example on how to get the conection to create the varray, as well as
    http://www.oracle.com/technology/sample_code/tech/java/codesnippet/jdbc/varray/index.html on using Varrays in Oracle, though I'm sure the database docs might have more information.
    Best Regards,
    Chris

  • Adding two array lists together and a text file to an array list

    I'm having problems coding these two methods... Could someone explain how to do this? I can't find information on it anywhere... :(
    "MagazineList" is the class I'm coding in right now, and I already declared "list" as an array list of another class called "Magazine".
    public boolean addAll(MagazineList magazines)
           if (list == magazines) {
               return false;
            else {
                list.addAll(magazines);
           return true;
       public boolean addAll(String filename)
           Scanner in = ResourceUtil.openFileScanner(filename);
            if (in == null) {
               return false;
            String line = source.nextLine();
            while (!line.equals("")) {
              list.add(Magazine(source));
           in.close();
       }

    I assume "addAll(MagazineList magazines)" is defined in the MagazineList class?
    Then,
    list.addAll(magazines);probably needs to be something like:
    list.addAll(magazines.list);This uses the private variable ( should be private) list from the input MagazineList, and adds all of those Magazine objects to the list in the current MagazineList.
    But, yes, describe your problems more clearly, and you'll get better answers more quickly (because people will be able to understand you and give you a suggestion without asking you another question first).

  • How do I extract the length of an element in an Array List

    Hello there,
    I am facing this problem with an Array List of elements. I am trying to extract the individual length of a particular element in the array list . Now if I know the element is a String is this valid?
    int lengthOfElement = 0;
    lengthOfElement = ((String)parms.get(i)).length();
    Your answer is much appreciated
    Regards

    Snap!I don't know how many times I've seen people post
    saying that they have a list where each element is a
    String, but they keep on getting ClassCastException :)Damn those Integers!
    � {�                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Accessing Array and Iterating Array list - Need Oracle Pro Assistance

    Hi,
    This is the third time i am posting the question, :( .
    I want some advice on how to iterate through a Array list which has an array of tasks/processes and make calls to the corresponding subprocess for each element in the list.
    We are looking for a BPMN approach.
    Any example or ideas would be of great help.
    My requirement states that i will get a list of tasks from a Rules Engine and i have to use BPM to iterate through the tasks and make calls to each tasks(which is a subprocess call).
    In Oracle BPM 11g I would like to use a multi-instance subprocess to send a task to a user for each item in an array. There are an unknown number of rows in the array. Does anyone have a good example of how to do this?
    I am using BPM Oracle 11g but any help 10 will also help us.
    I am reposting again this question , hoping that someone will help us
    Thanks
    Edited by: user9083699 on Aug 28, 2010 4:03 AM

    I am not the expert on 11g, however, in 10g, if I understand correctly... it sounds like you should be able to use PAPI to notify instances/sub processes, etc....
    With a list of Instances, you can search for that instance and notify it...
    If you have a list of processes, that need to be started, you can create an instance within that process....
    user9083699 wrote:
    My requirement states that i will get a list of tasks from a Rules Engine and i have to use BPM to iterate through the tasks and make calls to each tasks(which is a subprocess call).If you are just trying to initiate a sub-process, (btw, why would they have to be subprocesses?), It sounds like you should be able to create a global in the process, and just call it with PAPI...
    I'm still a little fuzzy, on how this business requirement turned up... however, maybe this helps a little?
    -Kevin

  • Object in array list

    Is it possible that object can be store in array list.
    package{
    // Importing object from flash libary
        import flash.text.TextField;
        import flash.display.Sprite;
    // Creating class
         public class Show extends Sprite {
         //Attribute
        private var txt:Array = new Array();
         // Constructor 
           function Show()
                   txt[0]:TextField =  new TextField();
                     addChild(txt[0]);
                     txt[0].width=320;
                     txt[0].height=25;
                     txt[0].x=0;
                     txt[0].y=0;
                     txt[0].border=true;
                   txt[0].text="nepalikto";
    Error
    Description : Label must be a simple identifier
    Location : Above orange textcolor line

    Not sure if this all is 100% technically correct but:
    You only use datatyping if you actually create a variable. Like:
    var myArray:Array = new Array();
    if you do not declare the var with the var keyword, you can't use datatyping either.
    // this is wrong
    myArray:Array = new Array()
    It is good practice to use datatyping whenever possible since it can help you debug an application:
    Flash finds the possible errors in code where one variable contains different datatypes at different times which can be confusing
    Flash helps with the codecompletion feature once a variable is typed so there's less chance of typos.
    The items in the array, unlike CS4's new Vector datatype aren't typed. Probably has some memory usage reason in the onderlying C++ code but I'm not sure. If you have CS4 you could possibly use:
    var txt:Vector.<TextField> = new Vector.<TextField>();
    To tell you the truth I haven't used the CS4 Vector Datatype so I'm not sure if aside from faster code execution there's errorcheckings on it's contents like mentioned above.
    Hope this helps some

  • Cant add to the end of the array list

    Hey everyone
             for(String word : dictionary){
                 if(word.equalsIgnoreCase(newWord) == false && word.compareToIgnoreCase(newWord) >= 0){
                     dictionary.add(dictionary.indexOf(word), newWord);
                     save();
                     break;
        }i am struggling to see the bug in my code, why will it not allow me to enter anything to the end of the array list, but anywehere other is fine?
    thanks very much

    Try posting a SSCCEE. Your code could be better written:
    1. You are using the enhanced for loop, then you have to turn around and use indexOf to see where you are in the list. Think about that.
    2. Are you sure you have to use both equalsIgnoreCase and compareIgnoreCase to get the result you need?

  • How can i check to see if an object is already in the array list?

    while (res.next()) {
                    Schedule schedule = new Schedule();
                    customerName = res.getString("CUSTOMERNAME");
                    schedule.setCustomerName(customerName);
                    magName = res.getString("MAGNAME");
                    schedule.setMagName(magName);
                    System.out.println("NAME: " + customerName);
                    System.out.println("MAGNAME: " + magName);
                    if(!scheduleListH.contains(schedule))  //this won't work
                        scheduleListH.add(schedule);
                }schedule object has 2 fields, customerName and MagName;
    Basically i want to say, IF the scheudleList (which is an array list) contains an object schedule that has the same customerName and MagName as any of the objects in the array list, don't readd the object.
    ANy help would be great!

    Thanks!
    Oops I forogt I could use the .contains, i also tried that but still no luck.
    There is no compiler error but here is an example of the output:
    Populating scheudle list for HOLIDAY selection data structure: 
    NAME: Cory
    MAGNAME: Merlin
    NAME: Brandon
    MAGNAME: Gondorf
    NAME: Chris
    MAGNAME: Houdini
    NAME: Lokie
    MAGNAME: Blaine
    Sample SCHEDUEL H [Cory          Merlin, Brandon          Gondorf, Chris          Houdini, Lokie          Blaine]As you can see, There are 4 objects in the array list:
    Cory Merlin
    Brandon Gondorf
    Chris Houdini
    Lokie BLaine
    Now this function is called everytime the user choses a new item in a combo box.
    So if they go back to the previous selection, Holiday's, it shouldn't read add all the orginal things.
    But if I go up and select the same item in the combo box it changes whats in the array list to the following:
    Populating scheudle list for HOLIDAY selection data structure: 
    NAME: Cory
    MAGNAME: Merlin
    NAME: Brandon
    MAGNAME: Gondorf
    NAME: Chris
    MAGNAME: Houdini
    NAME: Lokie
    MAGNAME: Blaine
    Sample SCHEDUEL H [Cory          Merlin, Brandon          Gondorf, Chris          Houdini, Lokie          Blaine, Cory          Merlin, Brandon          Gondorf, Chris          Houdini, Lokie          Blaine]Here's my whole function if your interested and where I call it:
        void populateSchedule(String holiday) {
            Statement sta = null;
            Connection connection6 = null;
            try {
                connection6 = DriverManager.getConnection(URL, USERNAME, PASSWORD);
                sta = connection6.createStatement();
                //getting the list of magicians from the selected holiday to see if any are free
                ResultSet res = sta.executeQuery(
                        "SELECT CUSTOMERNAME, MAGNAME FROM SCHEDULE WHERE HOLIDAYNAME = '" + holiday + "'");
                String customerName = " ";
                String magName = " ";
                System.out.println("Populating scheudle list for HOLIDAY selection data structure:  ");
                //this is where I add the waiting list objects to the array that will later be used
                //to print out and shown to the user when they select the waiting list status
                while (res.next()) {
                    Schedule schedule = new Schedule();
                    customerName = res.getString("CUSTOMERNAME");
                    schedule.setCustomerName(customerName);
                    magName = res.getString("MAGNAME");
                    schedule.setMagName(magName);
                    System.out.println("NAME: " + customerName);
                    System.out.println("MAGNAME: " + magName);
                   if(!scheduleListH.contains(schedule))
                       scheduleListH.add(schedule);
                System.out.println("Sample SCHEDUEL H " +   scheduleListH);
            } catch (SQLException ex) {
                System.out.println(ex);
                ex.printStackTrace();
            } finally {
                try {
                    sta.close();
                    connection6.close();
                } catch (SQLException ex) {
                    Logger.getLogger(Database.class.getName()).log(Level.SEVERE, null, ex);
    //this is where i call in the GUI
        private void specStatusComboBoxActionPerformed(java.awt.event.ActionEvent evt) {                                                  
            // TODO add your handling code here:
            String selectedItem = (String)specStatusComboBox.getSelectedItem();
            String groupSelectedItem = (String) groupStatusComboBox.getSelectedItem();
            if(groupSelectedItem.equals("Holidays"))
                //get customer name and magician name from the Scheduel table
                //use selectedItem (it will be a holiday name)
                //magicDB.clearScheduleHList();
                magicDB.populateSchedule(selectedItem);
                ArrayList<Schedule> tempScheduleList = magicDB.getScheduleHListCopy();
                outputTextArea.setText(" ");
                outputTextArea.setText("CUSTOMER NAME" +"\t\t" + "MAGICIAN NAME" + "\n");
                for(int i = 0; i < tempScheduleList.size(); i++)
                    outputTextArea.append(tempScheduleList.get(i).toString() + "\n");
        }   I'll reward the duke stars anyways because you have been a great help either way!

  • How to get keep one column as a key and the other columns as a array list

    Hello,
    I am really new to Java...I am trying to read a text file containing different columns separated by comma and then create a hash map for the first column (key) and then rest as a array list for the key.I am not able to create the hash map and the corresponding key.Could someone help me in this regard.
    The text document is :
    AcctNo,AcctMngr,AcctType,ProdList,Volume,AcctPrice,Returns
    12345,Vikram,2,MSFS:IBM:XYZ:MAN,28000,4500,1.25
    53278,Anand,1,PLYS:AIX:YET:WON,85000,8500,2.32
    94005,Vincent,3,UTIL:FLY:YEL:WIN,67000,5600,3.21
    45000,Abhishek,2,WENS:KYL:MEN:ABS,34000,9800,4.21
    76000,Chris,3,MENS:IBM:ROC:QUE,25000,2500,2.15
    67000,Kiran,4,FORS:ITI:MOC:REM,32000,3500,1.54
    87000,Rohit,2,MSNF:IIT:HOT:ROC,54000,5400,4,23
    45600,Sathyan,3,HELP:FOR:PRO:GRA,65000,3400,2,1.98
    84600,Vinay,4,PLZE:TES:ROC:WEN,76000,7300,3,4.32
    65000,Venkat,2,HETT:WEL:SEE:RED,89000,9800,1,3.23
    and the code which i have so far is
    import java.io.*;
    import java.util.*;
    class SearchHash {
    public static void main (String args[]) {
    int i=0;
    int j=0;
    Object newKey = new Object();
    Object newValue = new Object();
    Map map1 = new HashMap();
    ArrayList a1 = new ArrayList();
    String val;
    try {
    BufferedReader br1 = new BufferedReader ( new FileReader ( new File ("progress.txt")));
    String s="";
    s = br1.readLine();
    while (s!=null) {
    StringTokenizer st = new StringTokenizer (s ,",");
    int k=0;
    while (st.hasMoreTokens()) {
    while (k<=6) {
    val= st.nextToken();
    if (k==0) {
    newKey = val;
    else{
    newValue = val;
    a1.add(newValue);
    k = k+ 1;
    map1.put(newKey,a1);
    map1.put(newKey,a1);
    a1.clear();
    s = br1.readLine();
    // System.out.println(map1);
    }catch (Exception e) {
    System.out.println("Exception Raised : " + e);
    Thanks.,...

    Array? Don't live in object denial. Define a class (Account?) and parse each line as an Account object. Then you put them into a Map<Integer, Account> by their account number.

  • Bank account array list

    I'm very lost and need a push in the right direction. I am trying to get the balance of a bank account which is an array list of accounts and balances. The class I am working on is the Bank class. There is also a BankAccount class and a BankTester class.
    //deposit funds
         public void deposit(int accountNumber, double amount)
              double bal = (accountNumber).getBalance();
              double newBalance = bal + amount;
              balance = newBalance;
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    This is the error I am getting that I do not understand.
    C:\Users\matthew\Documents\FLCC\CSC190\Exercise7_1\Bank.java:34: int cannot be dereferenced
              double bal = (accountNumber).getBalance();
              ^
    C:\Users\matthew\Documents\FLCC\CSC190\Exercise7_1\Bank.java:36: cannot find symbol
    symbol : variable balance
    location: class Bank
              balance = newBalance;
              ^

    mgp wrote:
    I'm very lost and need a push in the right direction. I am trying to get the balance of a bank account which is an array list of accounts and balances. The class I am working on is the Bank class. There is also a BankAccount class and a BankTester class.
    //deposit funds
         public void deposit(int accountNumber, double amount)
              double bal = (accountNumber).getBalance();
              double newBalance = bal + amount;
              balance = newBalance;
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    This is the error I am getting that I do not understand.
    C:\Users\matthew\Documents\FLCC\CSC190\Exercise7_1\Bank.java:34: int cannot be dereferenced
              double bal = (accountNumber).getBalance();
    OK, here is what I think is happening. I do not see a definition of accountNumber anyplace that would override the int definition in the parameter list, and you are trying to access it as a object with a method getBalance()--that is what the dereference error is saying--when you put the parentesis around the variable and then attaching a method to it you are trying to access the enclosed variable as an object. In any case it is not an object and it does not contain the method getBalance().
              ^
    C:\Users\matthew\Documents\FLCC\CSC190\Exercise7_1\Bank.java:36: cannot find symbol
    symbol : variable balance
    location: class Bank
              balance = newBalance;
              ^balance is undefined in your Bank class.

  • Previous element in array list

    hello ppl..
    i hope u guys can help me here.. i am developing a program that sort an amount of strings and output to a file..and i place them inside an array list..i use Collections.sort to sort it..
    now the problem is..i want to handle duplicate strings meaning deleting the duplicate strings..however my code doesnt seem to work..here it is
    Iterator check = c.iterator();
    while (check.hasNext() == true)
    if (check.previous() == check.next())
    check.remove();
    br.write(check.next() + "\r\n");
    c is my arraylist name. JDK's error is they cannot resolve symbol previous () method but i found it inside util and i imported the whole util..by import java.util.*;
    Please help..thank you

    Good catch. It's very rare that you use == to compare objects. You only do that when you want to see if the two references are both aimed at the same object. Normally what you want to do (and what should be done here) is to use equals to see if the two objects' "contents" or "values" are the same.
    >
    if (check.previous() == check.next())Did you use this piece in the program?
    If so could this be the problem?
    I think that when you use the "==" operator it checks
    to see if the two objects share the same memory
    location.
    Like when you are comparing Strings you must use the
    String.equals(String s) method they they will never
    match with "==".
    Maybe this is not the problem but I like to
    ramble...
    -- Ian

  • How to find and display the posistion in an array list

    hi all,
    i know this is proballly simple but i have an arraylist where every time someone connects to my system it adds them to an arraylist, how can i post back somelike like hi user "1" thanks for connecting and so on. i just dont understand how to find their unique posistion in the array list and display it as a number.
    any help would be great

    So to be clear...
    You have an arraylist of connections .... for example
    ArrayList<ConnectedPeople> connPplArr = new ArrayList();And then each time someone connects you would add a connected people object to the arraylist.
    ConnectedPeople, migh contain username etc etc.
    You could then do:
    ConnectedPeople newConnection..... ;
    int index = connPplArr.indexOf( newConnection );
    if(int == -1){
        add them to your array
        index = connPplArr.size();
    return "Hello user "+ index;That what you mean?
    I know some of it is sudo code, but have I understood your problem?
    Edited by: Azzer_Mac on Apr 29, 2008 2:20 AM
    Edited by: Azzer_Mac on Apr 29, 2008 2:20 AM

Maybe you are looking for