1

I have the code below, where the user has to input 5 values in an array, and print out the same.

package Arrays;

import java.util.Scanner;

public class Arrays {
    public static void main(String[] args) {
        final int size=5;
        Scanner input = new Scanner(System.in);
        System.out.println("Enter the 5 number you want to be stored in an array");
        int a[] =new int[size];
        for(int i=0;i<a.length;i++){
            a[i]=input.nextInt();
        }           
        displayArray(a);
        sumOfArray();
        productOfArray();
        smallAndLargeOfArray();
        averageOfArray();
    }

    private static void displayArray(int arr[]) {
        for (int i = 0; i < arr.length; i++) {
            System.out.println(arr[i] + ' ');
        }
    }
}

here is my input:

1
2
3
4
5

and the output that I'm getting is:

33
34
35
36
37

Please let me know where I'm going wrong and how can I fix this.

2
  • Remember that a char in java is really just an integer. When you write arr[i] + ' ' you are actually adding 2 numbers, not concatenating 2 strings. Commented Nov 26, 2014 at 7:59
  • In other words: change + ' ' to + " ". Commented Nov 26, 2014 at 8:00

3 Answers 3

7

Change

System.out.println(arr[i] + ' ');

to

System.out.println(arr[i]);

or

System.out.println(arr[i] + " ");

When you are printing arr[i] + ' ', first the expression is evaluated as the addition of an int and a char (the integral value of the space character, which is 32), and only then the resulting integer is printed. Therefore, all the integers in your array are offset by 32 when printed this way.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the explaination
2

' ' has ascii code 32. When you use arr[i] + ' ' you convert second operand to integer and add to first operand.

Comments

1

In ASCII space has a char value of 32 (decimal) and char is actually an integer value. It gets added to your int value and gives that output.

System.out.println(arr[i]);

and

System.out.println(arr[i]+" ");

will solve the issue.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.