Question

I am trying to create an array of int elements, however its giving me char elements. whats going on?

import java.util.Scanner;
public class Assignment5a {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        int x[] = new int[1500];
        //create an array of numbers 2 to 1500
        for (int i=2; i<15; i++){
            x[i] = i;
        }

        System.out.println(x);

this is what I have. Any help is appreciated.

Was it helpful?

Solution 2

When you simply write System.out.println(*array*), the command will print the location in memory that stores the array.

If you are looking to print out the value stored in the array, you must specify the array index value you wish to print (note: array indexes begin at 0 and end at size-1):

System.out.println(x[position]);

If you wish to print out the characters to the entire array, you must either use a for-loop or an enhanced for-loop:

for(int i = 0; i < x.length; i++){
    System.out.println(x[i]);
}

The above code will create an int i which acts as an index for the array. Every time the loop runs, the value stored at position i will be printed out from the array x[]. x.length is used to make sure that int i does not exceed the array size limit.

OTHER TIPS

You are attempting to print out the array itself, which behaves as Object when printed. You have to do

System.out.println(Arrays.toString(x));

if you want to print out the whole array, or

System.out.println(x[0]);

to get a single element.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top