Simple conditional array question

Hi -
I need to create an array, but how big it is depends on some other influences. Here's a simplified version:
if (dataRequest.equals("elves")){
String[] arrayLoader={"tinky","winky","pinky","stinky"};
} else if (dataRequest.equals("reindeer")){
String[] arrayLoader={"dasher","dancer","rudolph"};
} else if (dataRequest.equals("villians")){
String[] arrayLoader={"snowmiser","heatmiser"};
out.println(arrayLoader.length);When I run this, I get "arrayLoader.length cannot be resolved to a type", but if I put the arrayLoader.length statement within each of the conditional parts, a length is returned. For some reason, the value seems to be "forgotten" by the time I leave the conditional part of the code.
What am I missing?

Variables only exist within the block they are declared in. So each of those String arrays only has scope within its own curly braces.
What you want is an ArrayList.
http://java.sun.com/javase/6/docs/api/java/util/ArrayList.html
It's an array that is automatically sized as you add members to it.

Similar Messages

  • Simple Java Array Question

    // This is how I was taught to make a simple array. You have to define the size first.
    String [] test1 = new String[4];
    test1[0] = "1";
    test1[1] = "2";
    test1[2] = "3";
    test1[3] = "4";
    out.println(test1[0]);
    out.println(test1[1]);
    out.println(test1[2]);
    out.println(test1[3]);
    //If the size is not defined in this second example, why does it still work?
    String [] test2 = {"1","2","3","4"};
    out.println(test2[0]);
    out.println(test2[1]);
    out.println(test2[2]);
    out.println(test2[3]);
    They both produce the same results.

    // This is how I was taught to make a simple array.
    You have to define the size first.
    String [] test1 = new String[4];
    test1[0] = "1";
    test1[1] = "2";
    test1[2] = "3";
    test1[3] = "4";
    out.println(test1[0]);
    out.println(test1[1]);
    out.println(test1[2]);
    out.println(test1[3]);
    //If the size is not defined in this second example,
    why does it still work?
    String [] test2 = {"1","2","3","4"};
    out.println(test2[0]);
    out.println(test2[1]);
    out.println(test2[2]);
    out.println(test2[3]);
    They both produce the same results.Umm..the size is just as well defined in your second as in your first...it is a four element array.
    The second way is akin to the first...also
    String[] s = new String[]{"Hello","I","contain","five","elements"};
    System.out.println(s[5]); Will compile..you will get a run-time ArrayIndexOutOfBoundsException (it is a 5 element array, 0-4, but java will not assume that the variable s is not changed between those two lines of code)..
    Array index/boundary checking is done at run-time, not compile-time.
    In fact:
    String[] s;
    //let's say up in the program
    //and
    public void printS(int i)
    System.out.println(s);
    Will also compile...and if something else happens to set s as a 10 element String array:
    printS(9);would work
    ~David

  • Simple X-fi Question, Please Help

    !Simple X-fi Question, Please HelpL I've been looking for an external sound card that is similar to the 2002 Creative Extigy and think I may found it in the Creative X-Fi. I have some questions about the X-fi though. Can the X-fi:
    1. Input sound from an optical port
    2. Output that sound to 5. surround- Front, surround, center/sub
    3. Is the X-Fi stand-alone, external, and powered by a USB or a wall outlet (you do not need a computer hooked up to it)
    Basically I want to connect a TosLink optical cable from my Xbox to the X-Fi. That will deli'ver the sound to the X-Fi. Then I want that sound to go to a 5. headset that is connected to the X-fi via 5. front, surround, and center/sub wires. The X-Fi has to be stand-alone and cannot be connected to a PC to do this.
    Thank you for your help.

    The connector must match, and the connector polarity (plus and minus voltage) must match.  Sorry, I don't know if the positive voltage goes on the inside of the connector or the outside.    Any wattage of 12 or more should be adequate.
    Message Edited by toomanydonuts on 01-10-2008 01:29 AM

  • Simple Crop tool question... how do I save the crop section?

    Hi,
    I have a very simple crop tool question. I'm a photoshop girl usually... so Illustrator is new to me. When I select the crop section I want... how do I save it?... if I select another tool in the tool panel, the crop section disappears and I can't get it back when I re-select Crop tool. If I select Save as... it saves the whole document...and not just my crop section.
    Like I said, simple question...but I just don't know the secret to the Illustrator crop tool.
    Thanks!
    Yzza

    Either press the Tab key or F key.

  • A Simpler, More Direct Question About Merge Joins

    This thread is related to Merge Joins Should Be Faster and Merge Join but asks a simpler, more direct question:
    Why does merge sort join choose to sort data that is already sorted? Here are some Explain query plans to illustrate my point.
    SQL> EXPLAIN PLAN FOR
      2  SELECT * FROM spoTriples ORDER BY s;
    PLAN_TABLE_OUTPUT
    |   0 | SELECT STATEMENT |              |   998K|    35M|  5311   (1)| 00:01:04|
    |   1 |  INDEX FULL SCAN | PKSPOTRIPLES |   998K|    35M|  5311   (1)| 00:01:04|
    ---------------------------------------------------------------------------------Notice that the plan does not involve a SORT operation. This is because spoTriples is an Index-Organized Table on the primary key index of (s,p,o), which contains all of the columns in the table. This means the table is already sorted on s, which is the column in the ORDER BY clause. The optimizer is taking advantage of the fact that the table is already sorted, which it should.
    Now look at this plan:
    SQL> EXPLAIN PLAN FOR
      2  SELECT /*+ USE_MERGE(t1 t2) */ t1.s, t2.s
      3  FROM spoTriples t1, spoTriples t2
      4  WHERE t1.s = t2.s;
    Explained.
    PLAN_TABLE_OUTPUT
    |   0 | SELECT STATEMENT       |              |    11M|   297M|       | 13019 (6)| 00:02:37 |
    |   1 |  MERGE JOIN            |              |    11M|   297M|       | 13019 (6)| 00:02:37 |
    |   2 |   SORT JOIN            |              |   998K|    12M|    38M|  6389 (4)| 00:01:17 |
    |   3 |    INDEX FAST FULL SCAN| PKSPOTRIPLES |   998K|    12M|       |  1460 (3)| 00:00:18 |
    |*  4 |   SORT JOIN            |              |   998K|    12M|    38M|  6389 (4)| 00:01:17 |
    |   5 |    INDEX FAST FULL SCAN| PKSPOTRIPLES |   998K|    12M|       |  1460 (3)| 00:00:18 |
    Predicate Information (identified by operation id):
       4 - access("T1"."S"="T2"."S")
           filter("T1"."S"="T2"."S")I'm doing a self join on the column by which the table is sorted. I'm using a hint to force a merge join, but despite the data already being sorted, the optimizer insists on sorting each instance of spoTriples before doing the merge join. The sort should be unnecessary for the same reason that it is unnecessary in the case with the ORDER BY above.
    Is there anyway to make Oracle be aware of and take advantage of the fact that it doesn't have to sort this data before merge joining it?

    Licensing questions are best addressed by visiting the Oracle store, or contacting a salesrep in your area
    But I doubt you can redistribute the product if you aren't licensed yourself.
    Question 3 and 4 have obvious answers
    3: Even if you could this is illegal
    4: if tnsping is not included in the client, tnsping is not included in the client, and there will be no replacement.
    Tnsping only establishes whether a listener is running and shouldn't be called from an application
    Sybrand Bakker
    Senior Oracle DBA

  • Very simple and quick question about Arrays

    Hi,
    I have the following code to produce a student grades provessing system. I have got it to store data in the array, i just cant figure out how to add the integers from the row to produce a total. Thats all I want to do create a total from the 6 marks and add a percentage.
    Any help would be greatly appreciated.
    -------------CODE BELOW----------------------
    import java.util.*;
    public class newstudent1_2
    public static void main (String[]args)
    System.out.println ("-----------------------------------------------"); //Decorative border to make the welcome message stand out
    System.out.println (" Welcome to Student Exam Mark Software 1.2"); //Simple welcome message
    System.out.println ("-----------------------------------------------");
    int [][] mark;
    int total_mark;
    int num_students;
    int num_questions = 9;
    Scanner kybd = new Scanner(System.in);
    System.out.println("How many students?");
    num_students =kybd.nextInt();
    mark = new int[num_students][num_questions] ;
    for (int i=0; i<num_students; i++)
    System.out.println("Enter the Students ID");
    String student_id;
    student_id =kybd.next();
    System.out.println("Student "+i);
    for( int j=1; j<num_questions; j++)
    System.out.println("Please enter a mark for question "+j);
    mark[i][j]=kybd.nextInt();
    System.out.print("id mark1 mark2 mark3 mark4 mark5 mark6 mark7 mark8");
    //This section prints the array data into a table
    System.out.println();
    for (int i=0; i<num_students; i++)
    for( int j=0; j<num_questions; j++)
    System.out.print(mark[i][j]+"\t"); //the \t is used to add spaces inbetween the output table
    System.out.println();
    --------------END OF CODE---------------
    Thanks.

    I had to do this same sort of thing for a school assignment but i didnt use an array.
    import java.text.DecimalFormat;
    import TurtleGraphics.KeyboardReader;
    public class grade_avg
         public static void main(String[] args)
              int grade, total = 0, count = 0;
              double avg = 0.0;
              KeyboardReader reader = new KeyboardReader();
              DecimalFormat df = new DecimalFormat("0.00");
         for (;;)
                   grade = reader.readInt("Please enter a grade: ");
              if (grade > 0)
                        total = total + grade;
                        count ++;
              if (grade == 0)
                        avg = total / count;
                        System.out.println("The average is: " + df.format(avg));
                        System.exit(0);
    }output looks like:
    Please enter a grade: 100
    Please enter a grade: 50
    Please enter a grade: 0
    The average is: 75.00

  • Simple c array in struct pointer question

    i have a two struct like so:
    typedef struct {
           uint8_t data[256];
    } foo1;
    typedef struct {
           uint32_t data_ptr;
    } foo2;
    foo1 * ctx;
    foo2    ply;
    if i want to get the pointer to the data array in ctx and assigned to data_ptr would i do it like so:
    ply.data_ptr = &(ctx->data);

    &(ctx->data) returns a pointer to an array of 256 integers. This type will look something like uint8_t (*data_ptr)[256]. Instead you should do what falconindy suggested above:
    ply.data_ptr = ctx->data
    To avoid gcc warnings (which you should always avoid), data_ptr needs to be declared the correct type of pointer. Since ctx->data by itself is nothing more than a pointer to an 8-bit wide integer you want (uint8_t *). ((void *) also works)

  • Simple Array Question - Help Needed!

    Hey people,
    I need a line of code that gets the maximum value out of an array.
    the array is called LEVELS and contains values [1, 3, 4, 17, 3, 2, 4]. I need a line of code that creates a new variable called MAXLEVEL and finds the largest value within the array.
    Thanks,
    sean :)

    Create a variable. Initialize it to the lowest possible value, like say Integer.MIN_VALUE.
    Loop through your array.
    For each element, see if it's greater than the current value in the variable. If it is, use it.
    When you reach the end of the array, the variable now holds the max value.
    How did you think you were going to do it?

  • Simple dynamic re-inilisation array question

    Hi Friends,
    I've this declaration:
    Object[][] arr = new Object[Rows][Columns]I then populate it.And then i am trying to add some more rows(eg. 10,20) to the end of this,columns remains the same.
    I just needed to ask can I do this,or should I need to rework it with Collections.
    thanks

    Hi,
    No you can't make the arrays grow. You have to allocate a new one and copy the old data into it, or switch to collections as you said.
    /Kaj

  • Database array questions

    Disclaimer: I am new to DB's.
    I'm looking at creating a MySQL database to hold tests done on DUTs (each with a specific serial). In theory, each DUT undergoes 3 tests. Each test produces a 401x9 2D array of DBLs. I am not concerned with the write speed to the DB, but I do want to optimize the read of the DB (potentially may need to retrieve 1000+ of these 2D arrays as fast as possible). I have the DB Toolkit; using LV 8.5. Questions:
    1. I have seen two different ways to save a 2D array in a DB mentioned: first, writing one row at a time with the DB Insert vi, resulting in a 2D array in a table (which is slow writing) or second, changing the 2D array to a variant and using the DB Insert vi, resulting in a single cell in a table. I know I can use other methods (parameterized vi, sql commands, user defined functions on the DB server, please do comment if you have found drastic performance increase with these methods), but of the two ways of storing a 2D array, can I read a 2D array from a table faster than reading a 2D array from a single cell? Whenever I need this data, I will read it all (i.e. I will never have to search for certain data within these individual 2D arrays)
    2. I may have installed the 8.2.1 DB toolkit, because the Database Variant to Data vi/function does not drop onto the Block Diagram when I drag it from the palette, and the Help has ???. I assume this is because it just points to the normal Variant to Data, which in 8.5 is in a subpalette as compared to 8.2.1. Any quick way to fix this?
    3. Any other general suggestions for a DB newbie? I've been trying to derive best practices from KB aritcles, this forum, and the web, but there is so much information and so many varying opinions I find it hard to narrow down best practices.
    Michael

    Hi Miguel,
    It looks like you are embarking on a very interesting project. Although you probably have seen many of the following documents, I've linked a few to get you started.
    Discussion forum using LabVIEW to read from tables
    Developer Zone article about developing a test system
    Knowledgebase article about imitations of speed with database toolset
    As far as your first question, I would suggest trying out both methods with simple code and testing with a small amount of values to determine  which one will be the fastest.
    Good luck with your project!
    Amanda Howard
    Americas Services and Support Recruiting Manager
    National Instruments

  • Simple Java Coding Question

    I know this is a simple question, but I can't search for the answer to this because it involves syntax that Google and the like don't seem to search for..
    I am trying to figure out some Java code that I have found. I would like to know what:
    a[--i] and a[++j] mean.
    My first thought was that they meant to look at the position in the array one less (or more) than i (j). But that doesn't seem to be the case. A is an array of Strings, if that matters...
    Thanks for you help.

    muiajc wrote:
    I know this is a simple question, but I can't search for the answer to this because it involves syntax that Google and the like don't seem to search for..
    I am trying to figure out some Java code that I have found. I would like to know what:
    a[--i] and a[++j] mean.
    It mean increase/decrease the int i/j by 1. This is done before it gets you the value of a[]. for example if i=5 and you said a[--i] it is really a[4] and i is now equal to 4;

  • CAS (array) questions redux

    I have a single Exchange server, where Get-Mailboxdatabase reports that the RPCClientAccessServer is servername.domain.local
    I'm currently having a certificate mismatch due to using a wildcard certificate, this only manifests as an error popup when you first start Outlook. Mail works fine, as do calendars - but I want to get rid of that pop-up.
    I'm already doing a split-brain DNS for EWS and so forth - mail.domain.com resolves to an internal IP internally and an external IP externally through a "real" DNS entry that's Internet-facing, and this way neither users internally or externally
    get certificate errors and everything works - EAS, OWA etc. So it's just this internal issue left.
    The question I have is that  I read something about it being a bad idea to use the same DNS name for CAS if the same address is externally resolvable (which it would be in this case). Does setting RPCClientAccessServer affect external clients too?
    Should I create a second split brain DNS entry instead, like mail-internal.domain.com and point that at servername.domain.local just to use for CAS?
    The second part of this question - can I just do: Set-MailboxDatabase MailboxDatabaseName -RpcClientAccessServer “mail.domain.com” and  walk away, ie skip the CAS array creation entirely if I were to choose that, assuming mail.domain.com resolves internally
    to servername.domain.local?
    Or should I definitely create the array and use that instead even though this is a single-server environment?
    Thanks.

    Indeed!
    http://blogs.technet.com/b/exchange/archive/2012/03/23/demystifying-the-cas-array-object-part-1.aspx is what Will is referring to.
    No, it is not that simple of just changing it and walking away. 
    Is this Outlook 2013 by any chance?
    Cheers,
    Rhoderick
    Microsoft Senior Exchange PFE
    Blog:
    http://blogs.technet.com/rmilne 
    Twitter:   LinkedIn:
      Facebook:
      XING:
    Note: Posts are provided “AS IS” without warranty of any kind, either expressed or implied, including but not limited to the implied warranties of merchantability and/or fitness for a particular purpose.

  • Some basic HP Smart Array questions

    Hopefully a simple answer to what seems to be a fairly simple question...
    If, for example, you have a P800 HP Smart Array with 24 disks and a spare and you want to partition a number of database files across drives to maximise I/O performance (the transaction log file is heavy on writes and the other data and index files are heavy on reads), would it be better to:-
    a) Use the 24/25 disks to create one SAS Array and three logical drives:-
    SAS Array A with spare - 3 Logical drives
         Logical Drive 1 (1200 Gb, RAID 1+0)  
         Logical Drive 2 (1200 Gb, RAID 1+0)
         Logical Drive 3 (1200 Gb, RAID 1+0)
    b) Use the 24 disks to create three SAS arrays each with one Logical Drive:-
    SAS Array A  & Logical Drive 1  (1200 Gb, RAID 1+0)  
    SAS Array B  & Logical Drive 1 (1200 Gb, RAID 1+0)  
    SAS Array C  & Logical Drive 1  (1200 Gb, RAID 1+0)  
    Not sure how the Spare disk fits into Option B?
    Anyway, if the objective is to maximize I/O performance, is it Option A or B?    
    The phrase, 'logical drive'... Does this mean that I/O is partitioned at the logical drive level or does the HP Smart array controller spread the I/O across the SAS Array?  If I look at I/O counters (eg. Perfmon on Windows Server), I can see that Logical drives as in Option A seem to be separated completely as one logical drive could have a disk queue and other logical drives on top of the same SAS array will not have a disk queue.  What are the prose and cons of Option A and B?  Understanding these issues will help me to come up with the right configuration in terms of arrrays and logical drives.
    Thanks in advance,
    Clive

    Hi, Clive:
    I'm not so sure yours is a fairly simple question for the HP consumer notebook forum.
    You may want to copy and paste your post in the HP Business Support Forum -- Disk Array section.
    http://h30499.www3.hp.com/t5/Disk-Array/bd-p/itrc-195

  • Multiple condition checking question

    Hi I have a newbie question -
    if ((temp == null) && (!temp.text.equals(""))) {
    statement;
    If temp really is null, would this give a compiler error? or would it simply break after the first condition?
    Thanks,
    Mike

    whatsupdoc wrote:
    Hi I have a newbie question -
    if ((temp == null) && (!temp.text.equals(""))) {
    statement;
    If temp really is null, would this give a compiler error?Compile it and see.
    I'm curious though what you're trying to accomplish. You seem to be confused about the meaning of &&.
    or would it simply break after the first condition?&& and || are "short-circuit" operators. They stop evaluating once the truth of the operation is known. So if the first operand to && is false, it stops there and does not evaluate the second, since the result of the && must be false, regardless of what the second operand is. Likewise, if the first operand to || is true, then it doesn't evaluate the second one, because the result is true regardless.

  • Trying to send multiple types in a byte array -- questions?

    Hi,
    I have a question which I would really appreciate any help on.
    I am trying to send a byte array, that contains multiple types using a UDP app. and then receive it on the other end.
    So far I have been able to do this using the following code. Please note that I create a new String, Float or Double object to be able to correctly send and receive. Here is the code:
    //this is on the client side...
    String mymessage ="Here is your stuff from your client" ;
    int nbr = 22; Double nbr2 = new Double(1232.11223);
    Float nbr3 = new Float(8098098.809808);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(baos);
    oos.writeObject(mymessage);
    oos.writeInt(nbr);
    oos.writeObject(nbr2);
    oos.writeObject(nbr3);
    oos.close();
    byte[] buffer = baos.toByteArray();
    socket.send(packet);
    //this is on the server side...
    byte [] buffer = new byte [5000];
    String mymessage = null; int nbr = 0; Double nbr2 = null;
    Float nbr3 = null;
    mymessage = (String)ois.readObject();
    nbr = ois.readInt();
    nbr2 = (Double) ois.readObject();
    nbr3 = (Float) ois.readObject();
    My main question here is that I have to create a new Float and Double object to be able to send and receive this byte array correctly. However, I would like to be able to have to only create 1object, stuff it with the String, int, Float and Double, send it and then correctly receive it on the other end.
    So I tried creating another class, and then creating an obj of this class and stuffing it with the 4 types:
    public class O_struct{
    //the indiv. objects to be sent...
    public String mymessage; public int nbr; public Double nbr2;
    public Float nbr3;
    //construct...
    public O_struct(String mymessage_c, int nbr_c, double nbr2_c, float nbr3_c){
    my_message = my_message_c;
    nbr = nbr_c;
    nbr2 = new Double(nbr2_c);
    nbr3 = new Float(nbr3_c);
    Then in main, using this new class:
    in main():
    O_struct some_obj_client = new O_struct("Here is your stuff from your client", 22, 1232.1234, 890980980.798);
    oos.writeObject(some_obj_client);
    oos.close();
    send code....according to UDP
    However on the receiving side, I am not sure how to be able to correctly retrieve the 4 types. Before I was explicitely creating those objects for sending, then I was casting them again on the receiving side to retrieve then and it does work.
    But if I create a O_struct object and cast it as I did before with the indiv objects on the receiving end, I can't get the correct retrievals.
    My code, on the server side:
    O_struct some_obj_server = new O_struct(null, null, null. null);
    some_obj_server = (O_struct)ois.readObject();
    My main goal is to be able to send 4 types in a byte array, but the way I have written this code, I have to create a Float and Double obj to be able to send and receive correctly. I would rather not have to directly create these objects, but instead be able to stuff all 4 types into a byte array and then send it and correctly be able to retrieve all the info on the receiver's side.
    I might be making this more complicated than needed, but this was the only way I could figure out how to do this and any help will be greatly appreciated.
    If there an easier way to do I certainly will appreciate that advise as well.
    Thanks.

    public class O_struct implements Serializable {
    // writing
    ObjectOutputStream oos = ...;
    O_struct struct = ...;
    oos.writeObject(struct);
    // reading
    ObjectInputStream ois = ...;
    O_struct struct = (O_struct)ois.readObject();
    I will be sending 1000s of these byte arrays, and I'm sure having to create a new Double or Float on both ends will hinder this.
    I am worried that having to create new objs every time it is sending a byte array will affect my application.
    That's the wrong way to approach this. You're talking about adding complexity to your code and fuglifying it because you think it might improve performance. But you don't know if it will, or by how much, or even if it needs to be improved.
    Personally, I'd guess that the I/O will have a much bigger affect on performance than object creation (which, contrary to popular belief, is generally quite fast now: http://www-128.ibm.com/developerworks/java/library/j-jtp01274.html)
    If you think object creation is going to be a problem, then before you go and cock up your real code to work around it, create some tests that measure how fast it is one way vs. the other. Then only use the cock-up if the normal, easier to write and maintain way is too slow AND the cock-up is significantly faster.

Maybe you are looking for