-
Help with Array
Hi, I have a question regarding arrays in Java.
I want a user to
- decide how many numbers he want to type in and store in the array.
- Let the user type in the numbers.
- Show the numbers from the array backwards.
This is how my code looks like now. What am I doing wrong? Can anyone point me in the right direction?
Code:
import java.util.Scanner;
public class steg4egenlabb2 {
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
int tal = 0;
System.out.print("Enter the amount of numbers you want to store in the array : ");
tal = keyboard.nextInt();
System.out.println("Enter " + tal + " numbers:");
int[] antal = new int[tal];
antal[0] = keyboard.nextInt();
System.out.println("The numbers written backwards:");
System.out.println(antal[0]);
}
}
This is how it currently shows with that code
Code:
Enter the amount of numbers you want to store in the array : 5
Enter 5 numbers:
1 2 3 4 5
The numbers written backwards:
1
Thanks
-
Hello, I have taken the liberty to rewrite your class in order to help you out.
Code:
import java.util.Scanner;
public class steg4egenlabb2 {
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
int tal = 0;
System.out.print("Enter the amount of numbers you want to store in the array : ");
tal = keyboard.nextInt();
int[] antal = new int[tal];
// loop array elements and get values from the user
for( int i = 0; i < tal; i++ ) {
System.out.print( "Enter Value for Element " + (i+1) + ": " );
antal[i] = keyboard.nextInt();
}
System.out.println("The numbers written backwards:");
// loop through the array backwards and output the values.
for( int i = antal.length - 1; i >= 0; i-- ) {
System.out.println( "Element at position " + ( 1 + i ) + " is: " +antal[i]);
}
}
}
The output of running this program is
Code:
Enter the amount of numbers you want to store in the array : 5
Enter Value for Element 1: 1
Enter Value for Element 2: 2
Enter Value for Element 3: 3
Enter Value for Element 4: 4
Enter Value for Element 5: 5
The numbers written backwards:
Element at position 5 is: 5
Element at position 4 is: 4
Element at position 3 is: 3
Element at position 2 is: 2
Element at position 1 is: 1
Greetings.