I have to prompt the user for an integer value and create an integer array of that size, but I'm not sure how to populate it using a for loop with the values 1… size, and print out the elements of the array preceded by their indices.
Here is a sample execution of the program. The user input is in bold.
How large an array? 5
0: 1
1: 2
2: 3
3: 4
4: 5
Here's what I have so far:
Scanner sc = new Scanner(System.in);
System.out.print("How large an array? ");
int i = sc.nextInt();
int arr [] = new int[i];
for (int j = 0; j < i; j ) {
System.out.print(arr[i] ": ");
}
CodePudding user response:
Do you mean something like that? I'm not sure if understood your question right.
Scanner sc = new Scanner(System.in);
System.out.print("How large an array? ");
int i = sc.nextInt();
sc.close();
int[] arr = new int[i];
for (int j = 0; j < i; j ) {
arr[j] = j 1;
System.out.println(j ": " arr[j]);
}
CodePudding user response:
You have to set the values that should be saved in the array first, before you can access them. That won't happen automatically.
After fixing your code, I came up with this:
Scanner sc = new Scanner( System.in );
System.out.print( "How large should the array be? " );
int size = sc.nextInt();
int[] array = new int[ size ];
//fill array with values
for ( int i = 0; i < size; i )
array[ i ] = i 1;
//print values
for ( int i = 0; i < size; i )
System.out.println( i ": " array[ i ] );
It produces the following answer for input 5:
0: 1
1: 2
2: 3
3: 4
4: 5
I hope this helps you further.
CodePudding user response:
If you don't really need an array, you could this simpler by using Java 8 IntStream
range feature:
public class Main {
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.print("How large an array? ");
int numbersCount = sc.nextInt();
List<Integer> numbers = IntStream.range(1, numbersCount 1)
.boxed()
.collect(Collectors.toList());
for (int i = 0; i < numbersCount; i ) {
System.out.println(i ": " numbers.get(i));
}
}
}