Simple Java array program

java array programs exercise
java array methods
2d array in java
string array in java
how to declare string array in java
java array of objects
one dimensional array in java
java array test questions

I'm trying to store odd numbers in an array, but when I run the code I'm getting 9, five times as answer. It's only storing the value 9.

Here are the codes:

public class Number2 {
    public static void main(String[] args) {
        int[] element = new int[5];

        for(int i=0; i<5; i++) {
            for(int j=1; j <= 10; j=j+2) {
                element[i] = j;
            }
        }

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

Can you tell me what's wrong with my program?

You use two loops, where you would need only one. Currently for every element in your array, you set it to 1, then to 3, then to 5, then to 7, then to 9, overwriting the former value each time. Thus in the end, your array is just {9,9,9,9,9}. You probably wanted to do this:

for(int i = 0; i < element.length; i++) {
  element[i] = i*2 + 1;
}

Java Array exercises: Array Exercises, ArrayIndexOutOfBoundsException. //Java Program to demonstrate the case of. //ArrayIndexOutOfBoundsException in a Java Array. public class TestArrayException{ public static void main(String args[]){ int arr[]={50,60,70,80}; for(int i=0;i<=arr.length;i++){ System.out.println(arr[i]); } Java Array Index. In Java, each element in an array are associated with a number. The number is known as an array index. We can access elements of an array by using those indices. For example, int[] age = new int[5]; Java Array Index. Here, we have an array of length 5. In the image, we can see that each element consists of a number (array index).

The internal loop (with variable j) runs from 1 up to 9 for each iteration of the outer index loop, and always assigns value to element[i] hence each value of the element array will be 9.

Following your logic this is how it should be:

for (int i = 0, j = 1; i < 5; i++, j += 2)
    element[i] = j;

You want to increment the value to be set along with the index variable.

A few improvements:

Since element is an array not just an element, you should name it plural, like elements. Also don't repeat the array length in multiple places in your code, an array knows its length: elements.length, use that in the for statement:

int[] elements = new int[5];

for (int i = 0, j = 1; i < elements.length; i++, j += 2)
    elements[i] = j;

Also you don't really need 2 variables to do what you want, the ith odd number can be calculated based on the index:

for (int i = 0; i < elements.length; i++)
    elements[i] = i*2 + 1;

Java Array, Well organized and easy to understand Web building tutorials with lots of examples of how to use HTML, CSS, JavaScript, SQL, PHP, Python, Bootstrap, Java� Learn how to play with arrays in Java programming. Here are most commonly used examples − How to sort an array and search an element inside it? How to sort an array and insert an element inside it? How to determine the upper bound of a two dimentional array? How to reverse an array? How to write an array of strings to the output console?

You are changing all the elements in your array to the last value of j.

Your loop needs to be :

for (int i=0;i<5;i++)
   {
      elements[i]=2*i +1;
   }

Think about it this way :

When i is 0 , then you are assigning to elements[0] values from 1 to 9 (the j loop). The last value assigned is 9.

Java Arrays, Tag Archives: Java-Array-Programs Reversing an array in java can be done in three simple methods. Examples: Input : 1, 2, 3, 4, 5 Output :5, 4, 3, 2,… In this page, we will learn how to write the simple program of java. We can write a simple hello java program easily after installing the JDK. To create a simple java program, you need to create a class that contains the main method. Let's understand the requirement first. The requirement for Java Hello World Example

When the last time inner loop execute value of j = 9 and when j become 11 it exits. You are storing each value of j in the same index. ie. you are overwriting the element[i] each time in the inner loop and i doesn't change in the inner loop. So only the final value of j is available. Below code will give the first five odd numbers ie (1, 3, 5, 7, 9)

for(int i=0,j=1; i <= 4; j=j+2,i++)
{
    element[i] = j;
}

Java-Array-Programs Archives, Java Arrays - Programming Examples - Learn how to play with arrays in Java programming. Here are most commonly used examples − Simple Java array program. Ask Question Asked 5 years ago. Active today. Viewed 1k times 1. 1. I'm trying to store odd numbers in an array, but when I run

You are replacing value of array in each iteration i by 9 (1,3,5,7,9 respectively)

Try Below

for(int i=0; i<5; ){
  for(int j=1; j <= 10; j=j+2,i++){
      element[i] = j;
  }
}

You can also write this in one for loop

 for(int j=1,i=0 ; j <= 10 && i<5; j=j+2,i++){
  element[i] = j;
 }

Output

Java Arrays - Programming Examples, Java - Arrays - Java provides a data structure, the array, which stores a fixed-size To use an array in a program, you must declare a variable to reference the array, and you must The following code snippets are examples of this syntax − To print one dimensional array in Java Programming you have to use only one for loop as shown in the following program. Java Programming Code on One Dimensional (1D) Array. Following Java Program ask to the user to enter the array size and then ask to enter the element of the array to store the elements in the array, then finally display the

Java - Arrays, An array is a container object that holds a fixed number of values of a single type. The Java programs in this section to find the largest numbers, second largest� Java programs: Basic Java programs with examples & outputs. Here we covered over the list of 500+ Java simple programs for beginners to advance, practice & understood how java programming works. You can take a pdf of each program along with source codes & outputs. In case if you are looking out for C Programs,

Java Programming Examples on Arrays, What is an array? Array Variables; First Array Program; Java Array: Pass by reference; Multidimensional arrays. how this helps� Java Program to Print an Array; Java Program to Convert String to Date; Java Program to Round a Number to n Decimal Places; Java Program to Concatenate Two Arrays; Java Program to Convert Character to String and Vice-Versa; Java Program to Check if An Array Contains a Given Value; Java Program to Check if a String is Empty or Null

Java Arrays Tutorial: Declare, Create, Initialize [Example], Java interview programs on arrays, Frequently Asked Java Array //Creating a HashMap object with elements of inputArray as keys and their�

Comments
  • user1506916 mentions in an attempted edit: "It's better to use the built in .length property (element.length) of an array rather than specifying a value. This prevents accidental IndexOutOfBounds exceptions."
  • What's the purpose of the first loop?