/* Groups.java - Written by Craig Persiko
This program demonstrates using a static Scanner object,
static numGroups, and output with nested loops.
*/
import java.util.Scanner;
public class Groups
{
// The following two variables are shared by all methods in this class
static Scanner keyIn = new Scanner(System.in);
static int numGroups;
public static void main(String args[])
{
int groupSize;
setNumGroups();
System.out.print("What is the size of each group? ");
groupSize = keyIn.nextInt();
keyIn.nextLine();
for(int group = 1; group <= numGroups; group++)
{
System.out.println("group = " + group);
for(int x = 1; x <= groupSize; x++)
System.out.println("\t x = " + x);
System.out.println("End group " + group);
}
}
/* Inputs an integer number of groups and stores it in
the static variable numGroups, shared for this class.
Beware of side-effects like this - errors can be caused easily
if you forget that a shared class variable is modified by a method. */
static void setNumGroups()
{
System.out.print("Please enter an integer number of groups: ");
numGroups = keyIn.nextInt();
keyIn.nextLine();
}
}
/* Sample Output:
-bash-3.2$ java Groups
Please enter an integer number of groups: 3
What is the size of each group? 4
group = 1
x = 1
x = 2
x = 3
x = 4
End group 1
group = 2
x = 1
x = 2
x = 3
x = 4
End group 2
group = 3
x = 1
x = 2
x = 3
x = 4
End group 3
-bash-3.2$ java Groups
Please enter an integer number of groups: 2
What is the size of each group? 1
group = 1
x = 1
End group 1
group = 2
x = 1
End group 2
-bash-3.2$
*/
syntax highlighted by Code2HTML, v. 0.9