For beginners, the input and output of arrays is a troublesome problem. Here are several array output methods:
1. Input and output of a single array element
import java.util.Scanner;
public class Greedy {
@SuppressWarnings("null")
public static void main(String[] args) {
@SuppressWarnings("resource")
Scanner in= new Scanner(System.in);
int N=in.nextInt();
int a;
int arr[] =new int[N];
for(int i=0;i<N;i++) {
a=in.nextInt();
arr[i]=a;
}
for(int i=0;i<N;i++) {
System.out.println(arr[i]);
}
}
}
The output is:
2. Output of the entire array
This requires calling the toString method in Arrays. This toString method is a method with parameters. You need to pass in the array you want to print as a parameter.
import java.util.Arrays;
import java.util.Scanner;
public class Greedy {
@SuppressWarnings("null")
public static void main(String[] args) {
@SuppressWarnings("resource")
Scanner in= new Scanner(System.in);
int N=in.nextInt();
int a;
int arr[] =new int[N];
for(int i=0;i<N;i++) {
a=in.nextInt();
arr[i]=a;
}
System.out.println(Arrays.toString(arr));
}
}
Print the result: