Nested For Loop Trouble?

Ok I need to have a nested for loop that asks a user to enter in a int number from 1-50. Whatever the number is, lets say 4 I need the program to count up asterisk and count down asterisks, like this.
This is my code:
import java.io.*;
public class Stars {
     static int n;
     static private InputStreamReader in = new InputStreamReader(System.in);
     static private BufferedReader br = new BufferedReader(in);
     public static void main(String[] Args)throws IOException
          System.out.println("Please enter in a number to see display: ");
          String num = br.readLine();
          n=Integer.parseInt(num);
          for(int i=1;i<=n;i++)
               for(int j=1;j<=i;j++)
                    System.out.print("*");
               for(int j=1;j<=i;j--)
                    System.out.print("*");
               System.out.println();
Can someone tell me what I am doing wrong so I can figure out my mistake(s).

Ok, well I know that the loop relies on the number entered in by the user. So if i pick 3 the three enter in the loop and counts up in a for loop and for every number it counts up to the three it does a print("*"); Now what I am getting confused about is where the other for loop comes into play. I know that I need to start from the number I have which is 3, so I need to have one less than that and then count down. The thing is that i'm not sure where or how the second for loop gets implemented into the code. Does it get nested with the first loop like this:
for(int i=1;i<=n;i++)
               for(int j=1;j<=i;j++)
                        for(int j=n-1;j>=i;j--)
                    System.out.print("*");
               System.out.println();
          }Or is the second for loop on its own like this:
for(int i=1;i<=n;i++)
               for(int j=1;j<=i;j++)
                    System.out.print("*");
               for(int j=n-1;j>=i;j--)
                    System.out.print("*");
               System.out.println();
          }If someone can help me understand, for this is my first time with nested for loops.

Similar Messages

  • Issues with nested for loops - saving images from a camera

    Hi all,
    I've written a vi. to capture a specific number of images ('Image No') and save these images, outputted to a folder of my choice.  Each image is identified sequentially.  However, I wish to do a number of iterations ('Run') of this capture sequence, such that the filename of each image would be 'Filename (Run)_(Image No).png', e.g. run 5, image 10 would be 'Filename 5_10.png'.  I have tried a nested for loop for this but I receive an error 'Asynchronous I/O operation in progress' (I've attached a printscreen).
    Can anyone assist me in solving this problem? I preiously posted this in machine Vision but got no response (http://forums.ni.com/t5/Machine-Vision/Capturing-image-sequences-issues-with-nested-for-loops/m-p/19...).  Please find attached my vi.
    Kindest regards and thanks,
    Miika
    Solved!
    Go to Solution.
    Attachments:
    Labview problem.jpg ‏3841 KB
    Image sequence save to file.vi ‏48 KB

    Miika,
    the problem is not the filenam, but the name of the folder (AHHHHH!). You try to create the same folder in the outer for loop over and over again.... (it is the error message above the '======', not below )
    Norbert
    CEO: What exactly is stopping us from doing this?
    Expert: Geometry
    Marketing Manager: Just ignore it.

  • Nested for loop in Xquery

    hi all,
    I need to implement nested for loop in Xquery, but not able to do. Please help.
    Thanks in advance..
    Rajan

    Nested for loops are simple in Xquery. Here is a very basic example:
    Input:
    <root>
    <FirstLevel>
         <SecondLevel>
              <Value>1</Value>
         </SecondLevel>
         <SecondLevel>
              <Value>2</Value>
         </SecondLevel>
         <SecondLevel>
              <Value>3</Value>
         </SecondLevel>
    </FirstLevel>
    <FirstLevel>
         <SecondLevel>
              <Value>4</Value>
         </SecondLevel>
         <SecondLevel>
              <Value>5</Value>
         </SecondLevel>
         <SecondLevel>
              <Value>6</Value>
         </SecondLevel>
    </FirstLevel>
    </root>XQuery:
    declare namespace ns0 = "http://temp.uri/OTM";
    declare function ns0:NestedForLoop($input as element(*))    as element(*)
         <ns0:Output>
              for $firstLevel in $input/FirstLevel
              for $secondLevel in $firstLevel/SecondLevel
                    return
                  <element>{ $secondLevel/Value/text() }</element>
         </ns0:Output>
    declare variable $input aselement(*) external;
    ns0:NestedForLoop($input)Output:
    <otm:Output       xmlns:otm="http://temp.uri/OTM">
         <element>1</element>
         <element>2</element>
         <element>3</element>
         <element>4</element>
         <element>5</element>
         <element>6</element>
    </otm:Output>Of course, this case is very simple and usually you wont even loop for this you can use a simple XPath like $input/FirstLevel/SecondLevel/Value/text() to achieve the above result. So, If you are having problems in a specific case of nested for loops, please post the input and output here and we can help out.

  • Interrupting Nested For Loops/Sequences

    I have a lagre program consisting of nested for loops and case statements calibrating an array of patch antennas. The entire process of which will take about 15 hours. During this time, I want to have two things happen.
    Every 20 minuites or so, I want the process to stop what it's doing, follow certain commands for the measurement equipment to recalibrate itself, and then go back to what it was doing.
    I also want to protect it against unpredicted and predicted crashes. If the system needs to stop for whatever reason, I would like to be able to pick up the process where it left off. A sort of checkpoint system, where, when it passes a checkpoint, if it needs to be restarted, I can tell it to start from the last checkpoint it passed.
    Anyone had any experiece with these types of problems?

    jaysmall wrote:
    I also want to protect it against unpredicted and predicted crashes. If the system needs to stop for whatever reason, I would like to be able to pick up the process where it left off. A sort of checkpoint system, where, when it passes a checkpoint, if it needs to be restarted, I can tell it to start from the last checkpoint it passed.
    Could you open and append parameters to a file? Every time you restart execution of the vi after crashes you can look through the contents of the file to determine the last operation that was successful and continue with the last know good settings.  -SS

  • Multiplication Table with Two Nested For Loops

    I am trying to code a multiplication table in which the user enters the number of rows between 2 and 10 and enters the number of columns from 2 to 10. This must be in nested for loop format somewhat like this:
    rows has been assigned the input variable for rows and columns is the name for input value for columns
    for (int i = 1; i <=rows; i++)
    for (int j = 1; j <=columns; j++)
    i * j
    i can't figure out how to get it to print out in table format or if the calculation coding is correct. can anyone help me please?
    it should look like this for rows is 4 and columns is 7
    1 2 3 4 5 6 7
    2 4 6 8 10 12 14
    3 6 9 12 15 18 21
    4 8 12 16 20 24 28
    Edited by: hatecodingsomuch on Feb 22, 2009 8:15 PM

    hatecodingsomuch wrote:
    I refuse to ask for help from people who are acting like they are all-knowing and unwilling to help someone, considering I am asking for help...to learn. Obviously I am not understanding java very well and I don't need to be ridiculed like this from members who are supposed to help "NEW TO JAVA" individuals. Get off your high horse or get off the website. I will never use this again.Good luck with that.
    You do seem to be yet another "do my homework for me" type of flunkie. I predict you'll soon have an epiphany that software development really isn't for you.
    I hope you know how to say "Do you want fries with that, sir?" better than the next guy so you can edge him out.

  • Nested for loops

    Sorry to bother you all, but I have a small problem with my java homework.
    I have to make a nested for loop to produce the following output:
    00
    10 11
    20 21 22
    30 31 32 33
    (only goes from 0 to 3)
    Now, all I have managed to do are two simple loops, one with increment 10 and the other with increment just ++.
    Could you help me?

    Think through this logically. You need two loops. You need this output:
    00
    10 11
    20 21 22
    30 31 32 33
    Each number above has two digits (two digits, two loops...not a coincidence). So you need one loop to control the first digit, and another loop to control the second digit. Look at the values for the first digit: 0,1,2,3. Those are your first loop values. Now, each time the first loop has a value, your second loop goes through all of its values. Here's the values you need:
    First iteration:
    loop index 1: 0
    loop index 2: 0
    Second iteration:
    loop index 1: 1
    loop index 2: 0,1
    Third Iteration:
    loop index 1: 2
    loop index 2: 0,1,2
    Fourth Iteration:
    loop index 1: 3
    loop index 2: 0,1,2,3
    Notice the pattern for loop 2? Look at the starting value for each iteration, and notice the ending value. That gives you your loop constraints.

  • Nested for loops error

    Hi all Community members,, I am facing problem with pulling attributes from a xml which I have created. I am using nested for loop. Please kindly help me out to solve this problem....
    Thanks in advance...
    Below is the code & xml ...
    import flash.events.Event;
    import flash.events.EventDispatcher;
    import flash.events.*;
    import flash.net.*;
    var myXML:XML;
    var voiceOver:String;
    var startOffset:Number;
    var slideData:Array;
    var id_cont_array:Array = new Array();
    var id_textfield_array:Array = new Array();
    var id_image_array:Array = new Array();
    var myXML_Container_Length:Number;
    var myXML_textField_Length:Number;
    var myXML_images_Length:Number;
    var loader:URLLoader = new URLLoader();
    loader.load(new URLRequest("dynamic.xml"));
    loader.addEventListener(Event.COMPLETE,processXML);
    function processXML(e:Event):void
    slideData=new Array();
    myXML = new XML(loader.data);
    loader.removeEventListener(Event.COMPLETE, processXML);
    loader.removeEventListener(IOErrorEvent.IO_ERROR, loadError);
    myXML = new XML(e.target.data);
    voiceOver = myXML. @ voice_over;
    startOffset = myXML. @ start_offset;
    for (var i : uint = 0; i<myXML.*.length(); i++)
      //trace(myXML + "slide");
    //myXML_List = myXML.children();
    myXML_Container_Length = myXML.children().length();
    //trace(myXML_Container_Length+ "==myXML_Container_Length")
    //myXML_textField_Length = myXML.containerss[0].children().length();
    //myXML_images_Length = myXML.children().length();
    //trace(myXML.child("containerss")[3]. @ id.toXMLString()+ "==myXML.containerss[0]. @ id;");
    //trace(myXML.containerss[0].textfield[0]. @ id+ "==myXML.slide.containerss[0]. @ id");
    //trace(myXML.containerss[0].textfield[1]. @ id+ "==myXML.slide.containerss[1]. @ id");
    //trace(myXML.containerss[3].image[0]. @ id + "==image[0]");
    //trace(myXML.containerss[0].children() + "==myXML.containerss[0].children()");
    for (var j:Number=0; j<=myXML_Container_Length; j++)
      id_cont_array.push(myXML.containerss[j]. @ id);
      //trace(myXML.containerss[j].children().length() + "==j");
      myXML_textField_Length = myXML.containerss[j].children().length();
      trace(myXML_textField_Length + "==myXML_textField_Length");
      for (var k:Number=0; k<=myXML_textField_Length-1; k++)
       id_textfield_array.push(myXML.containerss[j].textfield[k]. @ id);
       //id_image_array.push(myXML.containerss[k].image[j]. @ id);
       trace(id_textfield_array[k] + "==id_textfield_array[k]==" + k + "---j==" + j);
       //trace(id_image_array[k] + "==id_image_array");
      //trace(id_textfield_array[j]+"==id_cont_array[j]");
    //trace(myXML_List.length() + "===myXML_List");
    function loadError(e:IOErrorEvent):void
    trace("loadError");
    /// XML is as given below..
    <slide orientation="VERTICAL" voice_over="Slide1.mp3" start_offset="0" margin="">
    <containerss id="0" orientation="HORIZONTAL" padding="10" margin="10" x="10" y="160" width="200" height="150">
      <textfield id="Text1" text="textfieldText1" padding="10" margin="10"  x="10" y="160"/>
      <image id="img1" text="" padding="10" margin="10" x="10" y="160"/>
      <textfield id="Text2" text="textfieldText2" padding="10" margin="10" x="10" y="160"/>
    </containerss>
    <containerss id="1" orientation="HORIZONTAL" padding="10" margin="10" width="200" height="200" x="10" y="160">
      <textfield id="Text3" text="textfieldText3" padding="10" margin="10" x="10" y="160"/>
      <image id="img2" text="" padding="10" margin="10" x="10" y="160"/>
    </containerss>
    <containerss id="2" orientation="VERTICAL" padding="10" margin="10" width="200" height="150" x="10" y="160">
      <textfield id="Text5" text="textfieldText5" padding="10" margin="10" width="200" height="150" x="10" y="160"/>
      <image id="img3" text="" padding="10" margin="10" x="10" y="160"/>
      <textfield id="Text6" text="textfieldText6" padding="10" margin="10" x="10" y="160"/>
    </containerss>
    <containerss id="4" orientation="VERTICAL" padding="10" margin="10" width="200" height="150" x="10" y="160">
      <textfield id="Text7" text="textfieldText7" padding="10" margin="10" width="200" height="150" x="10" y="160"/>
      <image id="img4" text="" padding="10" margin="10" x="10" y="160"/>
      <textfield id="Text8" text="textfieldText8" padding="10" margin="10" width="200" height="150" x="10" y="160"/>
    </containerss>
    </slide>

    Parsing is totally wrong. You function processXML() should be like that:
    function processXML(e:Event):void
              slideData = new Array();
              loader.removeEventListener(Event.COMPLETE, processXML);
              loader.removeEventListener(IOErrorEvent.IO_ERROR, loadError);
              myXML = new XML(e.target.data);
              voiceOver = myXML.@voice_over;
              startOffset = myXML.@start_offset;
              myXML_Container_Length = myXML.children().length();
              var node:XMLList;
              for (var j:Number = 0; j <= myXML_Container_Length - 1; j++)
                        id_cont_array.push(myXML.containerss[j].@id);
                        node = myXML.containerss[j].children();
                        myXML_textField_Length = node.length();
                        for (var k:Number = 0; k <= myXML_textField_Length - 1; k++)
                                  switch (node[k].name().toString())
                                            case "textfield":
                                                      trace(node[k].@id);
                                                      id_textfield_array.push(node[k].@id);
                                                      break;
                                            case "image":
                                                      id_image_array.push(node.@id);
                                                      break;

  • Capturing image sequences - issues with nested for loops

    Hi all,
    I've written a vi. to capture a specific number of images ('Image No') and save these images, outputted to a folder of my choice.  Each image is identified sequentially.  However, I wish to do a number of iterations ('Run') of this capture sequence, such that the filename of each image would be 'Filename (Run)_(Image No).png', e.g. run 5, image 10 would be 'Filename 5_10.png'.  I have tried a nested for loop for this but I receive an error 'Asynchronous I/O operation in progress' (I've attached a printscreen).
    Can anyone assist me in solving this problem?  Please find attached my vi.
    Kindest regards and thanks,
    Miika
    Solved!
    Go to Solution.
    Attachments:
    Image sequence save to file.vi ‏48 KB
    Labview problem.jpg ‏3841 KB

    Hi,
    You cannot create a folder if this one is already existing.
    Just check that the folder exists before creating it.
    Regards

  • Trouble with charAt and nested for loops

    Hi,
    I have a programming assignment in which my goal is to write a program that reads a social security number written as contiguous digits (eg, 509435456; obtained via JOptionPane); uses charAt to obtain each character; and then prints each digit on a separate line, followed by a colon and the digit printed the number of times equal to its value. Thus the output for 509435456 would be:
    5:55555
    0:
    9:999999999
    4:4444
    3:333
    5:55555
    4:4444
    5:55555
    6:666666
    I'm also required to use a char variable for the inner loop control variable, and write the inner for loop as something along the lines of
    for(char index = '1'; index <= digit; index++) where digit is the char variable use to store the digit taken from the string.
    Here's what I have so far:
    import javax.swing.JOptionPane;
    public class Prog3a
         public static void main (String [] asd)
         String ssn = JOptionPane.showInputDialog("Que es tu SSN?");
         for (int rows = 0; rows < 9; rows++) //number of rows
                   char digit = ssn.charAt(rows) - '0';
                   System.out.print(digit + ":");
                   for (char index = 0; index < digit; index ++) //how many characters are going to be on each row
                             System.out.print(digit);
              System.out.println("");
    }Unfortunately, the char digit = ssn.charAt(rows) - '0'; errors on me, and only works when char is replaced with int. However, digit is no longer a char for the inner loop, and this fails to meet the requirements of the assignment. How can I assign the char without this "loss of precision"?

    Original Assignment:
    +3a. Write a program that reads a social security number written as contiguous digits (for instance, 509435456), uses the charAt method to obtain each character and then prints each digit on a separate line followed by a colon and the digit printed the number of times equal to its value. Thus the output for 509435456 would be+
    +5:55555+
    +0:+
    +9:999999999+
    +4:4444+
    +3:333+
    +5:55555+
    +4:4444+
    +5:55555+
    +6:666666+
    The string should be read using JOptopnPane.
    +Use a char variable, e.g., index, for the inner loop control variable and write the inner for loop as for(char index = '1'; index <= digit; index++) where digit is the char variable use to store the digit taken from the string.+
    +3b. Write the program so that index, the inner loop index, is an int variable. This means you must convert the character assigned to digit to an int.+
    Is that any help? It's as much as I know.

  • Nested for loop

    hello
    how can i implement this code in labview. i am new to labview, so plz if u design a vi of this code.
    for i=1:m
    c = (i-m/2);
    for j=1:n
    d = (j-n/2);
    N1(i,j)=exp(-(c^2+d^2)/c1^2);
    end
    end
    wher m is num of rows and n is number of column and c1 is a constant
    thnx
    kitty

    Here's a quick framework for you to start with.  I left out most of the math.
    Some things to notice:
    The i terminal starts with 0 and counts up for each iteration.  Since you want your math to start with 1, you need to increment.
    See the autoindexing out of the FOR loops?  That's what is building up your 2D array.
    Since you claim to be new, you might want to check out some of the online tutorials.
    LabVIEW Basics
    LabVIEW 101
    There are only two ways to tell somebody thanks: Kudos and Marked Solutions
    Unofficial Forum Rules and Guidelines
    Attachments:
    Nested loop.png ‏13 KB

  • Nested for loop in the collections

    Hi Experts,
    collection1
    ============
    SELECT o.object_id
          BULK COLLECT INTO l_obj_info
            FROM (SELECT     n.node_id, n.object_id
                        FROM nodes n
                  START WITH n.node_id = 100
                  CONNECT BY PRIOR n.node_id = n.parent_node_id) n
                 INNER JOIN
                 objects o ON n.object_id = o.object_id
           WHERE o.object_type_id = 285;
    collection2
    ============
    SELECT *
          BULK COLLECT INTO l_tab
            FROM ((SELECT     REGEXP_SUBSTR (i_l_text, '[^,]+', 1, LEVEL)
                         FROM DUAL
                   CONNECT BY REGEXP_SUBSTR (i_l_text, '[^,]+', 1, LEVEL) IS NOT NULL));
       END;
    collection3
    ============
    SELECT o.object_id
                   BULK COLLECT INTO l_fin_tab
                     FROM objects o JOIN ATTRIBUTES att
                          ON o.object_id = att.object_id
                    WHERE o.object_id = collection1.object_id
                      --AND att.VALUE = collection2.val;
    Please tell me how to implement for loop in the collection3 to get the values from collection1 and collection2.
    i have tried in the below way
    CREATE OR REPLACE TYPE LIST_OF_ATTRIBUTES_TYPE AS TABLE OF varchar2(4000);
    CREATE OR REPLACE TYPE LIST_OF_OBJECT_IDS_TYPE AS TABLE OF number(9);
    CREATE OR REPLACE FUNCTION f_get_objects_by_type_id (
       i_object_type_id   IN   NUMBER,
       i_l_text           IN   VARCHAR2,
       i_scope_node_id         NUMBER
       RETURN list_of_object_ids_type
    AS
       CURSOR objs_info
       IS
          SELECT o.object_id
            FROM (SELECT     n.node_id, n.object_id
                        FROM nodes n
                  START WITH n.node_id = i_scope_node_id
                  CONNECT BY PRIOR n.node_id = n.parent_node_id) n
                 INNER JOIN
                 objects o ON n.object_id = o.object_id
           WHERE o.object_type_id = i_object_type_id;
       l_tab       list_of_attributes_type := list_of_attributes_type ();
       --l_obj_info   list_of_object_ids_type := list_of_object_ids_type ();
       l_fin_tab   list_of_object_ids_type := list_of_object_ids_type ();
    BEGIN
       BEGIN
          SELECT *
          BULK COLLECT INTO l_tab
            FROM ((SELECT     trREGEXP_SUBSTR (i_l_text, '[^,]+', 1, LEVEL)
                         FROM DUAL
                   CONNECT BY REGEXP_SUBSTR (i_l_text, '[^,]+', 1, LEVEL) IS NOT NULL));
       END;
       IF l_tab.COUNT > 0
       THEN
          FOR i IN objs_info
          LOOP
             FOR j IN l_tab.FIRST .. l_tab.LAST
             LOOP
                SELECT o.object_id
                BULK COLLECT INTO l_fin_tab
                  FROM objects o JOIN ATTRIBUTES att ON o.object_id =
                                                                     att.object_id
                 WHERE
                                att.VALUE = l_tab (j) and o.object_id =objs_info(i);
             END LOOP;
          END LOOP;
       END IF;
       RETURN l_fin_tab;
    END f_get_objects_by_type_id;

    Why are you wanting to do this?
    It looks like you are trying to implement SQL joins in PL code.  Not only is that using up expensive PGA memory by storing the data in collections, but doing such retrieval of data to try and join it in PL loops, is never going to be as fast as just joining the SQL queries using SQL itself.
    Post some example data and your database version, with an example of what the output should look like from that example data.
    Re: 2. How do I ask a question on the forums?

  • I need to take elements from within 2 nested for loops and place them in an array at the specific row and column that I need.

    I have tried intializing an array and replacing elements by specifying a particular row, and column, but in the end I get an array with only one element replaced, and I suspect that it is because as the for loops are running through their iterations each time the array is re-initializing. I have a simple vi that I will post below, it is not the exact situation that I have but is a good place for me to get some understanding. I have the row and column indexes being driven by the inner and outer loop iterations, which gives me the pattern I need. I am using the inner iterations as array elements. How do I set this up so that it works and d
    oes keep re-initializing my array.
    Attachments:
    Untitled.vi ‏26 KB

    I have fixed a number of things in your vi.
    You were right in thinking that the array was continuously re-initialized. To avoid this, use a shift register (right-click the loop border), which will pass the updated array into the next iteration.
    Chilly Charly    (aka CC)
             E-List Master - Kudos glutton - Press the yellow button on the left...        
    Attachments:
    your_vi.vi.zip ‏13 KB

  • Nested for loop logic

    I am trying to create a triangle with for loop. i wrote this codepublic class Test {
        public static void main(String[] args) {
            for(int x = 1; x <= 6; x++) {
                for(int y = 1; y <= (x*2-1); y++) {
                    System.out.print("x");
               System.out.println("");
    }and i got answer like this
    x
    xxx
    xxxxx
    xxxxxxx
    xxxxxxxxx
    xxxxxxxxxxx
    but what i am trying to do is that will strat showing the results from the middle.
    ___X___
    __XXX__
    something like that. Need some explaination or hint what i am missing. (underscores are not part of my program:))
    thanks

    So since the spaces look right now, lets step through the plus loop
    for(k = i; k <= i*2-1; k++)
                    System.out.print("+"); First time starting to go through the loop i is 0.
    So 0 is not <= -1 [0*2-1 = -1] so no pluses get printed on the first time through.
    the second time starting to go through the loop i is 1.
    So first time through 1 is <= 1 [1*2-1 = 1] so print a +.
    Second time through 2 is not <= 1, so we end with just one +.
    The third time starting the loop i is 2.
    So first time through 2 is <= 3 [2*2-1 = 3] so print a +.
    Second time through 3 is <= 3 so print another +.
    Third time through 4 is not <= 3 so we end with just two +s.
    Uh oh, we wanted three s not two s, where did we go wrong? Let's try one more and see if we can see it.
    The fourth time starting i is 3.
    So first time through 3 is <= 5 [3*2-1 = 5] so print a +.
    Second time through 4 is <= 5 so print another +.
    Third time through 5 is <= 5 so print another +.
    Fourth time through 6 is not <= 5 so we end with just three +s.
    Now we have a choice, we can get mad and start throwing stuff and screaming at the stupid computer for doing it all wrong, or we can realize the problem is somewhere in the code and we can find it and fix it.
    What do you think?
    JSG
    EDIT: Note: you actually have two problems displayed here, both should be obvious but one is slightly hidden in the output until you fix the other. Both should have made themselves clear if you had done a simple step through yourself. As i demonstrated it is really easy to do and something you better get real good at if you want to be a good programmer.
    Edited by: JustSomeGuy on Nov 24, 2008 11:22 AM

  • Collection-Based For Loop Troubles!

    I am trying to compile this code from the book "Beginning Java 2: JDK 5 Edition" by Ivor Horton, using XCode on a Mac with SDK 1.4 (I know that the book is for JDK 5, but I figure that the first 5 chapters or so are going to be basic enough that it won't matter?):
    public class StringTokenizing {
    public static void main(String[] args) {
    String text = "To be or not to be, that is the question.";
    String delimiters = "[, .]";
    int[] limits = {0, -1};
    for(int limit : limits) {
    System.out.println("\nAnalysis with limit = " + limit);
    String[] tokens = text.split(delimiters, limit);
    System.out.println("Number of tokens: " + tokens.length);
    for(String token : tokens) {
    System.out.println(token);
    But, just as with EVERY code involving collection-based for loops -- In this case, the "for(int limit : limits)" statement, etc -- the compiler won't do it. The error points to that line and just says "; expected" as if it has no idea what to do with for loops that are not in the for (x ; x ; x) format...
    ...Grrrr. This is really starting to make it impossible to follow the examples in the book. Can someone help me?
    Thanks!
    -matt

    Kay, have you asked a written permission prior to posting that reply
    while I was posting my reply hm? I guess you didn't.
    kind regards,
    Jos (it's all anarchy and chaos overhere ;-)
    ^
    |
    +----- slow old sod                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Tough Nested FOR loop

    Friends,
    I am very new to Java and am trying to understand nested loops. Could someone please explain (step by step) how/why the code below returns 001012 ?
    public class ForLoop
    public static void main(String[] args)
    for (int a = 0; a < 3; a++)
    for (int b = 0; b <= a; b++)
    System.out.print(b);
    Thanks,
    Mark!

    I'm sure you can Google yourself some good info on nested loops, but the post Walken16 gave you:
    public class ForLoop
       public static void main(String[] args)
          for (int a = 0; a < 3; a++){
             System.out.println("in outer loop, a = "+a);
             for (int b = 0; b <= a; b++){
                System.out.println("in inner loop, b = "+b);
    }...should give you what you need. The key is to understand when the loops start and stop. The println's in there should illustrate this nicely if you think about it.

Maybe you are looking for