Mainly you need to declare a function main()
within the class that carries the same name as the source file .java
that you will compile and execute later. Therefore, you can do it in two ways, as if Arreglo
was a separate class than the one containing the main()
method, or you can do what you need in the main()
method directly.
Run the program in the main()
method:
To do what you need first, you must define the method main()
, then use a cycle for
and the method System.out.println()
as follows:
public class Arreglo
{
public static void main(String args[])
{
// Declaro el array como una variable.
int caja[] = new int[3];
caja[0] = 3;
caja[1] = 4;
caja[2] = 1;
// Utilizo un ciclo 'for' para iterar sobre los elementos del array.
for(int i = 0; i < caja.length; i++)
{
// Imprimimos los elementos del array en pantalla.
System.out.println(""+caja[i]);
}
}
}
Arreglo
is a separate class:
To print it you must first declare the main()
method in a class with the same name as the source file, then make use of a for
cycle and the System.out.println()
method within the class as follows :
public class Arreglo
{
// Declaro el array como una variable miembro de la clase Arreglo.
int caja[] = new int[3];
// Defino el constructor de la clase, donde defino el contenido de mi arreglo.
public Arreglo()
{
caja[0] = 3;
caja[1] = 4;
caja[2] = 1;
}
public void mostrarEnPantalla()
{
// Utilizo un ciclo 'for' para iterar sobre los elementos del array.
for(int i = 0; i < caja.length; i++)
{
// Imprimimos los elementos del array en pantalla.
System.out.println(""+caja[i]);
}
}
}
public class NombreFichero
{
public static void main(String args[])
{
Arreglo arr = new Arreglo();
arr.mostrarEnPantalla();
}
}
Also, I have corrected a couple of errors that I have noticed that your code has to achieve what you need.
First, you invoke the array
within the array()
method, allowing it to only exist within the method when it is executed, therefore, you could not show it in the mostrarEnPantalla()
method.
To solve this problem I have declared the array caja[]
as a member variable of class Arreglo
:
public class Arreglo
{
int caja[] = new int[3];
...
}
Then, I define the elements of the array in the constructor of this class:
public Arreglo()
{
caja[0] = 3;
caja[1] = 4;
caja[2] = 1;
}
Once it is declared and initialized, you can print its elements with the mostrarEnPantalla()
method.
Per second, I have also changed this cycle while
:
int i = 0;
while(i < 3)
{
System.out.println(""+caja[i]);
i++;
}
For this cycle for
that allows you to iterate over the array elements regardless of their length:
for(int i = 0; i < caja.length; i++)
{
System.out.println(""+caja[i]);
}
If you want to use a cycle while
instead of for
, you can change the previous code by this:
int i = 0;
while(i < caja.length)
{
System.out.println(""+caja[i]);
i++;
}