Eager to Code, Enjoy to Debug ~ Embark into Each Stage with Your Heart

Chapter 7: Arrays (Exercise 7.12)

Posted by: Chyne on: May 23, 2009

/* Exercise 7.12
* 1. Size of the array specified by the first command-line argument.
* 2. If no command-line argument is supplied, use 10 as the default size of the array.
*/

package Exercises;
public class SizeOfArray {

public static void main(String[] args) {
// check existence of command-line arguments
if (args.length == 0)
// set default size of array to 10
int array[] = new int[10]; // create array

System.out.printf(“%s%8s\n”, “Index”, “Value”); // column heading

// ouput each array element’s value
for (int counter = 0; counter < array.length; counter++) {
System.out.printf(“%5d%8s\n”, counter, array[counter]);
} // end for loop

} else {
// get array size from first command-line-argument
int arrayLength = Integer.parseInt(args[0]);
int array[] = new int[arrayLength]; // create array

// get initial value and increment from command-line argument
int initialValue = Integer.parseInt(args[1]);
int increment = Integer.parseInt(args[2]);

// calculate value for each array element
for (int counter = 0; counter < array.length; counter++) {
array[counter] = initialValue + increment * counter;
}

System.out.printf(“%s%8s\n”, “Index”, “Value”);

// display array index and value
for (int counter = 0; counter < array.length; counter++) {
System.out.printf(“%5d%8d\n”, counter, array[counter]);
} // end for loop
} // end if-else
} // end main
} // end class SizeOfArray

Leave a Reply

Friday’s Java Snack


In Java, "thread" means:

  • An instance of class java.lang.Thread
  • A thread of execution


An instance of Thread is just an object that has variables and methods, and lives and dies on the heap.
 
A thread of execution is an individual process that has its own call stack (one thread per call stack).

 

May 2009
M T W T F S S
« Apr   Jun »
 123
45678910
11121314151617
18192021222324
25262728293031

Archives


  • system_forex_: I like this website very much. This is such a outstanding web. And it is not like other money oriented website, the message here is genuinely impo
  • Faruk: its very very very fine solution perfect
  • blackhawk: Nice tip -- thanks for sharing

StatCounter

free hit counters