Hey all, first time poster here, so I'll try to abide by the rules =)
Anyway, I have a homework problem and I've got it running, but not really running. My brain is pretty fried so I'm guessing it's something silly, but if you guys could give me a hand here or point me in the right direction, it'd be very helpful. The question is asking us to rewrite an earlier example so that the size of the array is defined in the first command line argument. If there is no command argument is given, then just use 10 as the default size.
The original code is this:
public class InitArray { public static void main( String args[] ) { int array[]; // declare array named array array = new int[ 10 ]; // create the space for array System.out.printf( "%s%8s\n", "Index", "Value" ); // column headings // output each array element's value for ( int counter = 0; counter < array.length; counter++ ) System.out.printf( "%5d%8d\n", counter, array[ counter ] ); } // end main } // end class InitArray
which gives me an output of:
Index Value 0 0 1 0 2 0 3 0 4 0 5 0 6 0 7 0 8 0 9 0
So now my code is as follows:
import java.util.Scanner; public class InitArray { public static void main( String args[] ) { Scanner input = new Scanner( System.in); int array[]; System.out.print("Please enter a number for the array size: "); array = new int[ input.nextInt() ]; int num = input.nextInt(); int inputNumber = 0; if(args.length == 0) { array = new int[10]; } else { array = new int[Integer.parseInt(args[0] ) ]; } System.out.printf( "%s%8s\n", "Index", "Value" ); for ( int counter = 0; counter < array.length; counter++ ) System.out.printf( "%5d%8d\n", counter, array[ counter ] ); } }
which gives me an output of:
Please enter a number for the array size: 5
And it just hangs there. What am I missing? I hope I posted this is in the right subsection, since it is an array issue. Any help or guidance would be appreciated. Thanks!