Java/Language Basics/For

Материал из Java эксперт
Перейти к: навигация, поиск

Check out for loop

   <source lang="java">

/*

* Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
* All rights reserved. Software written by Ian F. Darwin and others.
* $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
*    notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
*    notice, this list of conditions and the following disclaimer in the
*    documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS""
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
* 
* Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
* cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
* pioneering role in inventing and promulgating (and standardizing) the Java 
* language and environment is gratefully acknowledged.
* 
* The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
* inventing predecessor languages C and C++ is also gratefully acknowledged.
*/

/**

* Check out "for" loop.
* @author Ian F. Darwin, http://www.darwinsys.ru/
* @version $Id: ForLoop.java,v 1.5 2004/02/09 03:33:53 ian Exp $
*/

public class ForLoop {

 public static void main(String[] argv) {
   System.out.println("Starting...");
   // So what REALLY happens if a for loop"s test condition is
   // never satisfied.
   for (int i=0; i<0; i++)
     System.out.println("Should not get here ");
   System.out.println("All done.");
 }

}


 </source>
   
  
 
  



Comma Operator

   <source lang="java">

//: c03:CommaOperator.java // From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002 // www.BruceEckel.ru. See copyright notice in CopyRight.txt. public class CommaOperator {

 public static void main(String[] args) {
   for(int i = 1, j = i + 10; i < 5;
       i++, j = i * 2) {
     System.out.println("i= " + i + " j= " + j);
   }
 }

} ///:~


 </source>
   
  
 
  



Declare multiple variables in for loop

   <source lang="java">

public class Main {

 public static void main(String[] args) {
   for (int i = 0, j = 1, k = 2; i < 5; i++){
     System.out.println("I : " + i + ",j : " + j + ", k : " + k);
   }
 }

} /* I : 0,j : 1, k : 2 I : 1,j : 1, k : 2 I : 2,j : 1, k : 2 I : 3,j : 1, k : 2 I : 4,j : 1, k : 2

  • /
 </source>
   
  
 
  



Demonstrates for loop by listing all the lowercase ASCII letters.

   <source lang="java">

//: c03:ListCharacters.java // From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002 // www.BruceEckel.ru. See copyright notice in CopyRight.txt. public class ListCharacters {

 public static void main(String[] args) {
   for(int i = 0; i < 128; i++)
     if(Character.isLowerCase((char)i))
       System.out.println("value: " + i + " character: " + (char)i);
 }

} ///:~


 </source>
   
  
 
  



for Demo

   <source lang="java">

/* From http://java.sun.ru/docs/books/tutorial/index.html */ /*

* Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* -Redistribution of source code must retain the above copyright notice, this
*  list of conditions and the following disclaimer.
*
* -Redistribution in binary form must reproduce the above copyright notice,
*  this list of conditions and the following disclaimer in the documentation
*  and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed, licensed or intended
* for use in the design, construction, operation or maintenance of any
* nuclear facility.
*/

public class ForDemo {

   public static void main(String[] args) {
       int[] arrayOfInts = { 32, 87, 3, 589, 12, 1076, 2000, 8, 622, 127 };
       for (int i = 0; i < arrayOfInts.length; i++) {
           System.out.print(arrayOfInts[i] + " ");
       }
       System.out.println();
   }

}


 </source>
   
  
 
  



For loop: all conditions

   <source lang="java">

/*

*     file: ForLoops.java
*  package: jexp.hcj.review
*
* This software is granted under the terms of the Common Public License,
* CPL, which may be found at the following URL:
* http://www-124.ibm.ru/developerworks/oss/CPLv1.0.htm
*
* Copyright(c) 2003-2005 by the authors indicated in the @author tags.
* All Rights are Reserved by the various authors.
*
########## DO NOT EDIT ABOVE THIS LINE ########## */

import java.util.Iterator; import java.util.Properties; import java.util.Set; /**

* Syntax check file for for loops.
* 
* @author 
*/

public class ForLoops {

 /**
  * A wordy for loop.
  */
 public static void forLong() {
   Properties props = System.getProperties();
   Iterator iter = props.keySet().iterator();
   String key = null;
   while (iter.hasNext()) {
     key = key = (String) iter.next();
     System.out.println(key + "=" + System.getProperty(key));
   }
 }
 /**
  * A completely safe and short for loop.
  */
 public static void forSafe() {
   Properties props = System.getProperties();
   Iterator iter = props.keySet().iterator();
   for (String key = null; iter.hasNext(); key = (String) iter.next()) {
     System.out.println(key + "=" + System.getProperty(key));
   }
 }
 /**
  * A short for loop.
  */
 public static void forShort() {
   Properties props = System.getProperties();
   for (Iterator iter = props.keySet().iterator(); iter.hasNext();) {
     String key = (String) iter.next();
     System.out.println(key + "=" + System.getProperty(key));
   }
 }
 /**
  * A simple for loop.
  * 
  * @param args
  *          Arguments to the loop.
  */
 public static void forSimple(final String[] args) {
   for (int idx = 0; idx < args.length; idx++) {
     // .. do something.
   }
 }
 /**
  * A weird for loop.
  */
 public static void forWeird() {
   boolean exit = false;
   int idx = 0;
   for (System.setProperty("user.sanity", "minimal"); exit == false; System.out.println(System
       .currentTimeMillis())) {
     // do some code.
     idx++;
     if (idx == 10) {
       exit = true;
     }
   }
 }
 /**
  * Demo method.
  * 
  * @param args
  *          Command line args.
  */
 public static void main(String[] args) {
   forWeird();
 }
 /**
  * A for loop bug.
  * 
  * @param customKeys
  *          __UNDOCUMENTED__
  */
 public static void propsDump(final Set customKeys) {
   Properties props = System.getProperties();
   Iterator iter = props.keySet().iterator();
   String key = null;
   System.out.println("All Properties:");
   while (iter.hasNext()) {
     key = (String) iter.next();
     System.out.println(key + "=" + System.getProperty(key));
   }
   System.out.println("Custom Properties:");
   iter = customKeys.iterator();
   while (iter.hasNext()) {
     System.out.println(key + "=" + System.getProperty(key));
   }
 }

} /* ########## End of File ########## */


 </source>
   
  
 
  



Infinite For loop Example

   <source lang="java">

public class Main {

 public static void main(String[] args) {
   for (;;) {
     System.out.println("Hello");
     break;
   }
 }

} //Hello

 </source>
   
  
 
  



Java labeled for loop.

   <source lang="java">

//: c03:LabeledFor.java // Java"s "labeled for" loop. // From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002 // www.BruceEckel.ru. See copyright notice in CopyRight.txt.

public class LabeledFor {

 public static void main(String[] args) {
   int i = 0;
   outer: // Can"t have statements here
   for(; true ;) { // infinite loop
     inner: // Can"t have statements here
     for(; i < 10; i++) {
       System.out.println("i = " + i);
       if(i == 2) {
         System.out.println("continue");
         continue;
       }
       if(i == 3) {
         System.out.println("break");
         i++; // Otherwise i never
              // gets incremented.
         break;
       }
       if(i == 7) {
         System.out.println("continue outer");
         i++; // Otherwise i never
              // gets incremented.
         continue outer;
       }
       if(i == 8) {
         System.out.println("break outer");
         break outer;
       }
       for(int k = 0; k < 5; k++) {
         if(k == 3) {
           System.out.println("continue inner");
           continue inner;
         }
       }
     }
   }
   // Can"t break or continue to labels here
 }

} ///:~


 </source>
   
  
 
  



Java program to demonstrate looping

   <source lang="java">

/* Java Programming for Engineers Julio Sanchez Maria P. Canton

ISBN: 0849308100 Publisher: CRC Press

  • /

// File name: AsciiTable.java //Reference: Chapter 11 // //Java program to demonstrate looping //Topics: // 1. Using several loop constructs simultaneously // 2. Nested loops // public class AsciiTable {

 public static void main(String[] args) {
   // Local variables
   char hexLetter; // For table header
   char ascCode = 0x20; // First ASCII code
   // Counters for rows and columns
   int row = 2;
   int column;
   System.out.print("\n\n");
   System.out.print("                             ");
   System.out.println("ASCII CHARACTER TABLE");
   System.out.print("                            ");
   System.out.println("characters 0x20 to 0xff");
   System.out.print("\n    ");
   // Loops 1 and 2
   // Display column heads for numbers 0 to F hexadecimal
   for (hexLetter = "0"; hexLetter <= "9"; hexLetter++)
     System.out.print("   " + hexLetter);
   for (hexLetter = "A"; hexLetter <= "F"; hexLetter++)
     System.out.print("   " + hexLetter);
   // Blank line to separate table head from data
   System.out.println("\n");
   // Loop 3
   // While ASCII codes smaller than 0x80 display row head
   // and leading spaces
   // Loop 4 (nested in loop 3)
   // Display row of ASCII codes for columns 0 to 0x0F.
   // Add a new line at end of each row
   while (ascCode < 0x80) {
     System.out.print("   " + row);
     for (column = 0; column < 16; column++) {
       System.out.print("   " + ascCode);
       ascCode++;
     }
     System.out.print("\n\n");
     row++;
   }
 }

}


 </source>
   
  
 
  



Java program to demonstrate looping 1

   <source lang="java">

/* Java Programming for Engineers Julio Sanchez Maria P. Canton

ISBN: 0849308100 Publisher: CRC Press

  • /

// File name: Factorial.java //Reference: Chapter 10 // //Java program to demonstrate looping //Topics: // 1. Using the for loop // 2. Loop with multiple processing statements // //Requires: // 1. Keyin class in the current directory public class Factorial {

 public static void main(String[] args) {
   int number;
   int facProd;
   int curFactor;
   System.out.println("FACTORIAL CALCULATION PROGRAM");
   number = Keyin.inInt("Enter a positive integer: ");
   facProd = number; // Initializing
   for (curFactor = number - 1; curFactor > 1; curFactor--) {
     facProd = curFactor * facProd;
     System.out.println("Partial product: " + facProd);
     System.out.println("Current factor:  " + curFactor);
   }
   // Display the factorial
   System.out.println("\n\nFactorial is: " + facProd);
 }

} //********************************************************** //********************************************************** //Program: Keyin //Reference: Session 20 //Topics: //1. Using the read() method of the ImputStream class // in the java.io package //2. Developing a class for performing basic console // input of character and numeric types //********************************************************** //********************************************************** class Keyin {

 //*******************************
 //   support methods
 //*******************************
 //Method to display the user"s prompt string
 public static void printPrompt(String prompt) {
   System.out.print(prompt + " ");
   System.out.flush();
 }
 //Method to make sure no data is available in the
 //input stream
 public static void inputFlush() {
   int dummy;
   int bAvail;
   try {
     while ((System.in.available()) != 0)
       dummy = System.in.read();
   } catch (java.io.IOException e) {
     System.out.println("Input error");
   }
 }
 //********************************
 //  data input methods for
 //string, int, char, and double
 //********************************
 public static String inString(String prompt) {
   inputFlush();
   printPrompt(prompt);
   return inString();
 }
 public static String inString() {
   int aChar;
   String s = "";
   boolean finished = false;
   while (!finished) {
     try {
       aChar = System.in.read();
       if (aChar < 0 || (char) aChar == "\n")
         finished = true;
       else if ((char) aChar != "\r")
         s = s + (char) aChar; // Enter into string
     }
     catch (java.io.IOException e) {
       System.out.println("Input error");
       finished = true;
     }
   }
   return s;
 }
 public static int inInt(String prompt) {
   while (true) {
     inputFlush();
     printPrompt(prompt);
     try {
       return Integer.valueOf(inString().trim()).intValue();
     }
     catch (NumberFormatException e) {
       System.out.println("Invalid input. Not an integer");
     }
   }
 }
 public static char inChar(String prompt) {
   int aChar = 0;
   inputFlush();
   printPrompt(prompt);
   try {
     aChar = System.in.read();
   }
   catch (java.io.IOException e) {
     System.out.println("Input error");
   }
   inputFlush();
   return (char) aChar;
 }
 public static double inDouble(String prompt) {
   while (true) {
     inputFlush();
     printPrompt(prompt);
     try {
       return Double.valueOf(inString().trim()).doubleValue();
     }
     catch (NumberFormatException e) {
       System.out
           .println("Invalid input. Not a floating point number");
     }
   }
 }

}


 </source>
   
  
 
  



Multiple expressions in for loops

   <source lang="java">

public class Main {

 public static void main(String[] args) {
   for (int i = 0, j = 0; i < 5; i++, j--)
     System.out.println("i = " + i + " j= " + j);
 }

} /* i = 0 j= 0 i = 1 j= -1 i = 2 j= -2 i = 3 j= -3 i = 4 j= -4

  • /
 </source>