Reputation: 5
How can I reverse this code? I thought that I'm using the right way to reverse this array, but it still doesn't work...
I hope someone can help me. tq
so, this is my code :
import java.util.Scanner ;
public class ArrayYear
{
public static void main (String[] args)
{
Scanner in = new Scanner(System.in);
int[] arr = new int[3];
int[] year = new int[3];
//read element into array
for ( int i=0 ; i <= arr.length ; i++ )
{
arr[i] = in.nextInt() ; // input value
for ( int j=0 ; j<=arr.length/2 ; j++ ){
int temp = arr[j];
arr[j] = arr[arr.length - i - 1 ];
arr[arr.length - i - 1 ] = temp;
}
year[i]= in.nextInt();
System.out.println( "ID :" + arr[i] + "("+ year[i] +")" ) ;
}
}
}
note : the array that needed to be reverse is only the first array arr[i]
Upvotes: 0
Views: 374
Reputation: 5
import java.util.Collections;
import java.util.Scanner;
public class ArrayYear {
public static void main(String[] args) {
Scanner in = new Scanner(System. in );
int[] arr = new int[3];
int[] year = new int[3];
// read element into array
for (int i = 0; i < arr.length; i++) {
// input value
arr[i] = in .nextInt();
year[i] = in .nextInt();
// reverse array
for (int j = 0; j < arr.length / 2; j++) {
int temp = arr[j];
arr[j] = arr[arr.length - j - 1];
arr[arr.length - j - 1] = temp;
}
for (int j = 0; j < year.length / 2; j++) {
int temp = year[j];
year[j] = year[year.length - j - 1];
year[year.length - j - 1] = temp;
}
}
for (int i = 0; i < arr.length; i++) {
// print array
System.out.println("ID :" + arr[i] + "(" + year[i] + ")");
}
}
}
Upvotes: 0
Reputation: 7919
You have to fill the array first then reverse it and also loop should be upto i<=arr.length-1
.Reversing the array code would be
public static int[] reverseArray(int a[]) {
int b[] = new int[a.length];
int index = 0;
for (int i = a.length - 1; i >= 0; i--)
b[index++] = a[i];
return b;
}
public static void main(String[] args) throws java.lang.Exception {
Scanner sc = new Scanner(System. in );
int c[] = new int[5];
int index = 0;
while (sc.hasNextLine()) {
c[index++] = Integer.parseInt(sc.nextLine().trim());
}
System.out.println("Before Reverse " + Arrays.toString(c));
System.out.println("After Reverse " + Arrays.toString(reverseArray(c)));
}
Input
1
2
3
4
5
Output
Before Reverse [1, 2, 3, 4, 5]
After Reverse [5, 4, 3, 2, 1]
Upvotes: 1