Enhance for loop question

I like it, but I can't figure out how to use it for the following situation (printing contents of two arrays using one iterator):
old way:
        System.out.println(menuTitle + "/n");
        for (int e ; e < length.menuChoices ; e++)
            System.out.print(menuChoices[e] + " - " + menuLabels[e]);
        }new?
        System.out.println(menuTitle + "/n");
        for (String e : menuChoices)
            System.out.print(e + " - " + menuLabels[????]);
        }Is there a nice way to do this or should I just use the old for loop and hope my teacher doesn't think that I just don't know about the new loop? Thanks.

Is there a nice way to do this or should I just use
the old for loop and hope my teacher doesn't think
that I just don't know about the new loop?No there isn't. In the new for-loop the loop counter has been abstracted away. You'll have to either use the old for-loop, or introduce a counter in the new.
Another way could be to change the design a little.
class MenueItem {
   Type1 choice();
   Type2 label();
for (String e : menuItems)  { // all MenuItems
   System.out.print(e.choise() + " - " + e.label());
}

Similar Messages

  • Question about "Enhanced for loop"

    public class NewLoopTest{
         public NewLoopTest(){
              int result=0;                      
              int[] a=new int[20];           
              for(int i=0;i<a.length;i++){
                   a=i++;
              for(int i:a){  
    System.out.println("i="+i+";"+"a["+i+"]="+a[i]+";result="+result+"+"+i+"="+(result+i));
                   result+=i;           
              System.out.println("-------------");
              result=0;
              for(int i=0;i<a.length;i++){
                   System.out.println("i="+i+";"+"a["+i+"]="+a[i]+";result="+result+"+"+i+"="+(result+i));
                   result+=i;
    This code counts sum of the elements of a array.
    At first I use the enhanced for loop and at second I use the traditional for.
    Enhanced for loop in sdk1.5 returns only even elements of array, am I right?

    Enhanced for loop in sdk1.5 returns only even
    elements of array, am I right?No. It covers them all.
    The i in the enhanced for loop is not the index. It's the element at the current index. You don't have access to the index in the new loop because you don't need it.
    for (int item : arr) {
        System.out.println(item);
    // is equivalent to
    for (int ix = 0; ix < arr.length; ix++) {
        int item = aa[ix];
        System.out.println(item);
    }The i in your new loop is the same as a [ i ] in the old loop.

  • Enhanced for-loop by java5 needs to be more  enhanced?

    Hi, all of you,
    I often need to iterate a collection. Sometimes I need to iterate a subset of a collection. Then I have found the enhanced for-loop is not enough.
    Before Java 5, you did the following:
    for(int i=0;i<collection.size();i++) {
    Object object = collection.get(i);
    doSomething(object);
    }Thanks to Java 5, you can do the following:
    for(Object object:collection) {
    doSomething(object);
    }However, before Java 5, I have the flexibility to skip the first two lines by purpose, as follows
    for(int i=2;i<collection.size();i++) {
    Object object = collection.get(i);
    doSomething(object);
    }What should I do the same thing with Java 5?
    Kind regards.
    Pengyou

    pengyou wrote:
    JoachimSauer wrote:
    masijade. wrote:
    uncle_alice wrote:
    Or, if the collection is a List: for (Object obj : theList.subList(2, theList.size())) {
    doSomething(obj);
    Ah, yeah, I keep forgetting about that. ;-)
    Actually, I just never think about it. ;-)I think you're not alone. I find that subList() is severly under-used. It simplifies a lot of operations (ever tried someList.subList(0, someIndex).clear()? Try it).The solution is nice except it might throw IndexOutOfBoundsException.Which probably means a bug somewhere else. The way to avoid runtime exceptions is to write code that doesn't put you into situations where they'll arise, not to avoid them being thrown

  • How to get count from new enhanced for loop

    Is there a better way to determine the count when new enhanced for loop is used as follows:
    String[] test = new String[]{"1","2","3"};
    int count = 0;
    for(String i: test)
    count++;
    system.out.println("count: "+count);
    }

    There are cases where I need to use the count inside
    the for loop. I can keep track of the count by using
    the increment. But, then I would rather using the old
    for loop. Go ahead and use it. Are you under the assumption that the old form should be avoided?
    There is no saving in term of efficiency and readability.If there is any added efficiency in the "for each" form of the loop, it is on the micro level, and you would never notice it.
    As far as readability, look at some of the crazy solutions you've been given to avoid the general for loop, then reconsider which is more readable.

  • BUG: 10.1.3..36.73 Internal Compile Error with enhanced for loop/generics

    I get the following compiler error when using the Java 5 SE enhanced for loop with a generic collection.
    Code:
    public static void main(String[] args)
    List<Integer> l = new ArrayList<Integer>();
    l.add(new Integer(1));
    printCollection(l);
    private static void printCollection(Collection<?> c)
    for (Object e : c)
    System.out.println(e);
    Error on attempting to build:
    "Error: Internal compilation error, terminated with a fatal exception"
    And the following from ojcInternalError.log:
    java.lang.NullPointerException
         at oracle.ojc.compiler.EnhancedForStatement.resolveAndCheck(Statement.java:2204)
         at oracle.ojc.compiler.StatementList.resolveAndCheck(Statement.java:4476)
         at oracle.ojc.compiler.MethodSymbol.resolveMethod(Symbol.java:10822)
         at oracle.ojc.compiler.RawClassSymbol.resolveMethodBodies(Symbol.java:6648)
         at oracle.ojc.compiler.Parser.resolveMethodBodies(Parser.java:8316)
         at oracle.ojc.compiler.Parser.parse(Parser.java:7823)
         at oracle.ojc.compiler.Compiler.main_internal(Compiler.java:978)
         at oracle.ojc.compiler.Compiler.main(Compiler.java:745)
         at oracle.jdeveloper.compiler.Ojc.translate(Ojc.java:1486)
         at oracle.jdeveloper.compiler.UnifiedBuildSystem$CompileThread.buildGraph(UnifiedBuildSystem.java:300)
         at oracle.jdeveloper.compiler.UnifiedBuildSystem$CompileThread.buildProjectFiles(UnifiedBuildSystem.java:515)
         at oracle.jdeveloper.compiler.UnifiedBuildSystem$CompileThread.buildAll(UnifiedBuildSystem.java:715)
         at oracle.jdeveloper.compiler.UnifiedBuildSystem$CompileThread.run(UnifiedBuildSystem.java:893)

    Install the Service Update 1 patch for JDeveloper (using the help->check for updates), and let us know if this didn't solve the problem.

  • Cursor For loop question

    Hi,
    I have a cursor in my plsql and I am trying to get the record through a FOR loop. I know that for loop will take care of opening, fetching and closing the cursor implicitly.
    Ex.
    declare
    cursor c1 is
    select * from emp;
    begin
    for l_rec in c1 loop
    end loop;
    My question is i want to check whether the cursor in the for loop is returning any record or not using IF condition.
    where and how i will find that?
    Can anyone help how to do that.
    Rds,
    Nag

    without using boolean variables.Obvious question, WHY?
    If you are so particular..
    SQL> declare
      2   cursor c1 is
      3        select empno, ename, job
      4        from emp
      5        where empno = 7839123;
      6   ex exception;
      7   rec c1%rowtype;
      8  begin
      9   open c1;
    10   fetch c1 into rec;
    11   if c1%notfound then
    12    raise ex;
    13   end if;
    14   loop
    15    dbms_output.put_line(rec.empno||'-->'||rec.ename||'-->'||rec.job);
    16    fetch c1 into rec;
    17    exit when c1%notfound;
    18   end loop;
    19  exception
    20   when ex then
    21    dbms_output.put_line('cur not found');
    22  end;
    23  /
    cur not found
    PL/SQL procedure successfully completed.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • VERY IMPORTANT FOR LOOP QUESTION

    public class ForTest2 {
         public static void main(String args[]) {
              int i=0, j = 0;
              for (j=0; j < 10; j++) {
                   i++;
                   System.out.println("i is: " + i);
                   System.out.println("j is: " + j);
              System.out.println("Final i is: " + i);
              System.out.println("Final j is: " + j);
    }j ends up being 10. Why? It should only be 9. This is as when j is 10 the for loop fails, so j++ shouldnt happen.

    First, please, please, please stop using all caps. It's extremely annoying.
    Second, don't mark your question as urgent or important. It is 100
    % guaranteed NOT to get you help any faster, and it might just delay you getting help because it's annoying.
    As for your question, you're misunderstanding how the for loop works. j HAS to become 10 for it to end. The loop body executes as long as j < 10. If j didn't become 10, the loop body couldn't terminate, because j<10 would always be true.
    The body is executed, the j++ is executed, then the j<10 is tested.
    int j;
    for (j = 0; j < 10; j++) {
        // body
    // is equivalent to
    int j;
    j = 0;
    while (j < 10) {
        // body
        j++:
    }

  • A simple for loop question

    Hi
    Lets say I have an array with boolean values in it:
    my_array = [ false , false , false ]
    My question is:
    How do you make a function to check, if the value is all
    false, than do this (not only one but all false than trigger a
    function)
    thank you

    The 350Z,
    > Lets say I have an array with boolean values in it:
    > my_array = [ false , false , false ]
    I'm with ya.
    > My question is:
    > How do you make a function to check, if the value is
    > all false, than do this (not only one but all false than
    > trigger a function)
    Your subject line already states the answer. A for loop
    would come in
    handy. :) In your case, you're looking for all three values
    to be false.
    If even a mere one of them is true, the whole result doesn't
    count. Let's
    write a function that returns true if all three are false,
    and returns false
    if any are true.
    function checkWholeArray(arr:Array):Boolean {
    for (var n:Number = 0; n < arr.length; n++) {
    if (arr[n] == true) {
    return false;
    return true;
    To use this function, you could call it and supply your
    array as the
    parameter ...
    checkWholeArray(my_array);
    ... and since that resolves to either true or false, you
    could even use that
    expression in an if statement.
    if (checkWholeArray(my_array)) {
    // do something
    } else {
    // do something else
    The for loop simply steps through each element in the
    passed-in array.
    If the current element is true, then the desired outcome --
    that all
    elements are false -- is a loss, so the function returns
    false and
    immediately stops (the return statement always exits the
    function at that
    point). Otherwise, the for loop finishes, and the function
    returns true.
    David
    stiller (at) quip (dot) net
    Dev essays:
    http://www.quip.net/blog/
    "Luck is the residue of good design."

  • How do I use an enhanced for loop / for each on my ViewObjectImpl ?

    Guys and Gals,
    With all of my newly acquired Java knowledge in tow, I spent this weekend cleaning up all of my code, dealing mainly with for loops. I converted them from a huge mess to a for each type loop using language such as ...
        RowSet priceUpdateRows = (RowSet)((PriceUpdatesViewRowImpl) priceUpdate).getPriceUpdateRowsView();
        for (Row priceUpdateRow: priceUpdateRows)
        { // do operations on row... which makes perfect sense to me. For each Row in the RowSet, do something. It doesn't, however, makes sense to the compiler. It pouts and gives me a "foreach not applicable to expression type" error. So I read up on iterators and such, messed with code examples, and still can't get the RowSet to iterate with the above code. Could I make RowSet implement Iterable? How would I do that? I tried to create a class called RowSetExt which extended RowSet and implemented Iterable, but then I got a class cast exception.
    I know I could implement something like the following or a while(hasNext()) but they're really not what I'm looking for.
    ViewObject vo = … < Get ViewObject > …
    RowSetIterator rsi = vo.createRowSetIterator("rowsRSI");
    while (rsi.hasNext())
         Row row = rsi.next();
         row.setAttribute("YourAttribute",your_value);
         rsi.closeRowSetIterator();How do I make the for(Row row : <RowSet>) example work? Or could someone point me in a direction?
    Will

    One thing I tried was to make a framework extension class for my ViewObjectImpls
    public class PcsViewObjectImpl
      extends ViewObjectImpl
      implements Iterable<Row>
      Set<Row> set = new HashSet<Row>();
      public Iterator<Row> getRows()
        return set.iterator();
      public Iterator<Row> iterator()
        return getRows();
    }AppModuleImpl
        PriceUpdateRowsViewRowImpl priceUpdateRows = (PriceUpdateRowsViewRowImpl)((PriceUpdatesViewRowImpl) priceUpdate).getPriceUpdateRowsView();
        for (Row priceUpdateRow: priceUpdateRows)
        {However, this gives me a class cast exception at runtime. But I would think some kind of extension class would be the way to go ... ?

  • Insert Procedure For LOOP question

    Hi all,
    I have made a Procedure which basically massages data and loads into into another table and makes a time record aswell. I am practising my good datawarehousing practise (So load table into real DW_table)
    I am using an Explicit Cursor For Loop....
    What i was wondering is if there is some type of SQL%rowcount I can do in order to check that the record where "INSERTED" into dw_client and dw_time; before i create a auit record in another table. I know this is normally done using triggers, but I am testing this for a Datawarehouse and not sure triggers are the best answer. But please correct me if im wrong:
    I basically wanted to put another insert in there, if the inserts actually ran!

    RPuttagunta wrote:
    Why can you not use a merge statement in your code instead of writing a whole procedure for it?
    merge into mehmet_schema.dw_client a
    using
    mehmet_schema.client.....
    If I understand it right, you are checking if there are any records that exists in 'client' and doesn't exist in 'dw_client' table, then, you are inserting. Is that correct?Yes that is correct. Also I am inserting into the dw_time table using the sqeuence values, so i didnt think merge statement would do this!
    aslo i wanted to use this procedure to clean up some of the data, as you can see in my Cursor, again why i havent used a merge
    Edited by: oraCraft on 09-Nov-2010 09:53

  • For loop question

    Hi here is a segment of my code:
    public void vietaLoop(){
         int loopParameter;
         final int START_CONDITION=0;
         final long END_CONDITION=no_Terms;
         double initialTerm = Math.sqrt(2)/2;
         double newTerm;
         double previousTerm;
         /* calculate the next PI term */
         newTerm = Math.sqrt(2+previousTerm);
         /* assign new term to previous */
         previousTerm = newTerm;
         for (loopParameter = START_CONDITION; loopParameter < END_CONDITION;
         loopParameter++)
         /* Prints the new PI approximation */
         System.out.println(+ newTerm);
    im having loads of trouble, above is how far I have got but I'm unable to 'call' the previous calculation to be included in the next calculation to calculate the new term of PI. as a result all my output is the same..... ie = 1.645.......
    If anyone could point me in the right direct... its really getting to me. Thanks.

    Hi there,
    Is this what you want?
    import java.awt.*;
    class vietaLoop
        public static void main(String[] args)
              int loopParameter;
              int no_Terms=10;
              int START_CONDITION=0;
              int END_CONDITION=no_Terms;
              double initialTerm=Math.sqrt(2)/2;
              double newTerm;
              double previousTerm;
              previousTerm=initialTerm;
              for (loopParameter=0; loopParameter<END_CONDITION;loopParameter++)
                   newTerm = Math.sqrt(2+previousTerm);
                   previousTerm = newTerm;
                   System.out.println(newTerm);
    }If you use it as a function, set it as
    public double vietaLoop(int noTerm)
    Then you can change no of term for looping.
    Regards
    John

  • Quick for loop question

    Hi everybody,
    I have a feeling this is so obvious that I'm missing it, so if anyone would give me some advice, I'd appreciate it.
    I have a method with with three parameters that loops through them and progressively adds or subtracts them with a for loop, based on the order. The only way I can think of to do this, though, is with two for loops with almost identical code. I know there must be an easier way to do this, but I think I've been staring at it too long, can anyone give me a hand conceptually, please?
    The method is:
    private void create( int param1, int param2 ) {
            int entries = 5;
            double increment;
            if( param1 > param2 ) {
                increment = param1 - param2;
                for( int i = 0; i < entries; i++ ) {
                    System.out.println( param1 - ( i * increment ) );
            } else if( param2 > param1 ) {
                increment = param2 - param1;
                for( int i = 0; i < entries; i++ ) {
                    System.out.println( param1 + ( i * increment ) );
         }Thanks,
    Jezzica85
    Edited by: jezzica85 on Mar 30, 2009 2:38 PM

    private void create( int param1, int param2 ) {
        if( param1 > param2 ) {
            create(param2, param1);
        } else if( param2 > param1 ) {
            int entries = 5;
            double increment = param2 - param1;
            for(int i = 0; i < entries; i++ ) {
                System.out.println( param2 + (i * param1));
        } //equal do nothing?
    }or
    private void create2( int param1, int param2 ) {
        if (param1 != param2) {
            int entries = 5;
            int minParam = Math.min(param1, param2);
            int maxParam = Math.max(param1, param2);
            double increment = maxParam - minParam;
            for( int i = 0; i < entries; i++ ) {
                System.out.println( maxParam - (i * minParam));
      }

  • Stacked sequence inside for loop question

    Hi everyone,
    I am new to LabVIEW and I just want to make a for loop with a stack sequence inside. I want it so that when the for loop executes for the n-th time, the stacked sequence is at the n-th frame (because each frame contains different tasks to be carried out). Is this possible? or is there an alternative equivalent method? Please help me out! Thanks!!

    Thank you Norbert for the words of advice.
    Try to avoid Stacked Sequence Structures at all cost.  They are a nightmare to deal with when maintaining the code and they do not offer simple scalability, especially if you need to deal with parallelism.
    As Norbert suggested, State Machines is the way to go.  Try to avoid naming covention such as 1...2...3...4...5.......9999.  Give the name of each case based on what that case does.  Create a TypeDef Control for the state selector (you'll thank me after having changed it for the 5th time   ).
    There are probably 100's of examples in this forum.
    RayR

  • Enhanced for loop with DirectoryStream  in java 7

    Hi, I'm a newbie to Java and am having trouble with the following code, which I'm trying to use to iterate through a directory and obtain the file names of all the pics to create thumbnails of them.
    I've done hours and hours of searching on the web and find no answer for this one, so it's probably something very simple I've screwed up.
    All assitance is appreciated.
    The code segment:
            try (DirectoryStream<Path> ds =
              Files.newDirectoryStream(FileSystems.getDefault().getPath(dirNew)))
                  System.out.println("at dirstream");
                  System.out.format("toString: %s%n", ds.toString());
                for (Path p : ds)
                    // Iterate over the paths in the directory and print filenames
                   System.out.println(p.getFileName());
                   System.out.println("at Path p : ds");
                    thumbName = p.getFileName();
                    createThumb(String.format("%s",thumbName));
            } catch (IOException e) {
                System.out.println("dirstream failed!!!");
    //           e.printStackTrace();
                System.out.println("atend of dirstream");and the output:
    run:
    /home/rich/Images/FromWeb-Misc/1
    at dirstream
    toString: sun.nio.fs.UnixSecureDirectoryStream@196b20e
    atend of dirstream
    Edited by: 898552 on Mar 6, 2013 3:04 PM
    Edited by: 898552 on Mar 6, 2013 3:07 PM
    Edited by: 898552 on Mar 6, 2013 3:09 PM

    rp0428 wrote:
    >
    It's not entering the loop.
    >
    With the versions of NetBeans I use you can set breakpoints BEFORE and even ON the loop! Being able to set them inside a loop is just a no-cost extra. ;)I know! But you said "IN THE LOOP" :D The poor guy will set his breakpoint in it and think his debugger is broken ;)
    Relax - take a deep breath - repeat after me
    >
    5 more points - 5 more points - 5 more points
    >
    Congratulations - I see a 'shiny' future for you!
    Status Level: Expert (2,495) :DHaha, I hadn't noticed that :D I better be extra helpful now, so I can pop open a bottle of champagne tonight ;)

  • Compile Error in Enhanced For Loop

    I'm learning generic collections and for practice wrote a simple class that uses a HashMap to store data. However, I'm getting a compile error for the code that accesses the HashMap. The error and code for my class follow.
    Can anyone help?
    Thanks...
    =====================
    The compile error:
    =====================
    MapDict.java:37: package Map does not exist for( Map.Entry entry : glossary.entrySet()  )                        ^1 error=======================
    The code for my class:
    =======================
    import java.util.Scanner;
    import java.util.HashMap;
    public class MapDict
         HashMap<String, String> glossary = new HashMap<String, String>();
         public void getEntries()
              Scanner sc = new Scanner( System.in ).useDelimiter("\n");
              String moreEntries = "y";
              String word        = "";
              String definition  = "";
              while ( moreEntries.toUpperCase().equals( "Y") )
                   System.out.print("Enter word: ");
                   word = sc.next();
                   System.out.print("Enter definition: ");
                   definition = sc.next();
                   glossary.put( word, definition);
                   System.out.print("Another glossary item? (y/n) ");
                   moreEntries = sc.next();
         public void displayEntries()
              System.out.println( glossary.size() );
              // Here is where the compile error occurs:
              for( Map.Entry entry : glossary.entrySet()  )
                   System.out.println( "\nWord: " + entry.getKey() + " Definition: " + entry.getValue() );
    }

    import java.util.Scanner;
    import java.util.HashMap;I don't see java.util.Map or java.util.Map.Entry listed here....

Maybe you are looking for