to reverse the elements of an array [duplicate] - java

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 5 years ago.
Here is my code to reverse the elements in an array:
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[] arr = new int[n];
for(int i=0; i < n; i++){
arr[i] = in.nextInt();
}
int i=0;
int j=n-1;
int c;
while(i<j){
c=arr[i];
arr[i]=arr[j];
arr[j]=c;
i++;
j--;
}
System.out.println(arr[n]);
in.close();
}
}
The problem is my code is generating arrayIndexOutOfBound exception. How to remove it ?

Change,
System.out.println(arr[n]);
to:
System.out.println(Arrays.toString(arr));

System.out.println(arr[n]);
Here is the problem because there's no index "n"
n is the number of elements
You have to loop form 0 to n-1
for(int i =0;i < n;i++){
System.out.println(arr[i]);
}

your code works fine for reversing the array of elements but arrayIndexOutOfBound exception is raised due to System.out.println(arr[n]). Remember array index starts from zero.For n size array, the range will be [0,(n-1)] ie., if n=5 range will be 0 to 4.
for(int k=0;k<arr.length;k++)
{
System.out.println(arr[k]);
}

Related

WAP to compute the sum of the first n terms of the following series [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 10 months ago.
S = 1 + 1/2! + 1/3! + 1/4!.....
Here is my code:
import java.util.Scanner;
public class question{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n =sc.nextInt();
int[] fact= new int[n];
fact[0] =fact[1] =1;
for(int i=2;i<=n;i++)
{
fact[i]= fact[i-1]*i;
}
double sum=0;
for(int i=1;i<=n;i++){
sum+=1/fact[i];
}
System.out.println(sum);
}
}
This code is giving error
input:3
Exception in thread "main" java.lang.ArrayIndexOutOfBoindsException: Index 33 out of bounds for length 3 at question.main(question.java.12)
What is the reason for this error? How to resolve it?
The array is one element too small, it should be
int[] fact = new int[n+1];
Also note that sum+=1/fact[i] will be an integer division. You can use
sum += 1.0/ fact[i]
to get a floating point division.
Also you do not need to store the factorials in an array as the purpose is just to sum. You could do the following:
int fact = 1;
double sum = 0;
int n = 15;
for(int i = 1; i<=n; i++){
sum += 1.0/fact;
fact *= i;
}

ArrayIndexOutOfBoundsException when printing out values from an array [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 6 years ago.
The program should print out values stored in an array of size 5 after the user has input the values.
Here is my code:
import java.util.Scanner;
public class Arrays_Qu1 {
public static void main(String[] args) {
Scanner sc= new Scanner(System.in);
int arr[]= new int [5];
System.out.println("Enter a number");
int i;
for (i=0;i<arr.length;i++) {
arr[i]=sc.nextInt();
}
System.out.println(arr[i]);
}
}
After I enter the 5th value, the program does not terminate but instead throws:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
Because you are printing outside the loop and it is trying to print arr[5] which is out of bound of the array. The print should be in loop if you want to print each element.
int i;
for (i = 0; i < arr.length; i++) {
arr[i] = sc.nextInt();
System.out.println(arr[i]); // to print each element
}
// value of i is now 5, so arr[i] is invalid
System.out.println(arr[i-1]); // to print last element
System.out.println(Arrays.toString(arr)); // to print whole array
You should access the last element of the array like:
System.out.println(arr[i - 1])
but I believe printing just the last element of an array is not what you want. So you should move line
System.out.println(arr[i])
in a for loop and it should be ok.

Array Sorting getting error [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
class arr{
//array sorting to find maximum value
public static void main(String[]args){
int[] array={1,6,4,5,2};
int n;
int i,j;
for( i=0;i<(array.length*2);i++){
for( j=0;j<array.length;j++){
if(array[j]>array[j+1]){
array[j]=array[j+1];
array[j+1]=array[j];
}
}
}
System.out.println(array[array.length]);
}
}
>
Can anyone tell me why i am getting runtime error and this sorting method will work or not?
Dont reinvent the wheel.., you are able to use arrays, so then use the array help class too...
:-)
public static void main(String[] args) {
final int[] array = { 1, 6, 4, 5, 2 };
System.out.println("Array before sort " + Arrays.toString(array));
Arrays.sort(array);
System.out.println("Array before sort " + Arrays.toString(array));
}
you will likely have an indexOutOfbounds exception because your second loop:
for( j=0;j<array.length;j++){
if(array[j]>array[j+1]){
array[j]=array[j+1];
array[j+1]=array[j];
}
}
J loops through teh array then you attempt to index the array at J + 1 which on the last element in the array would push it out of bounds thus throwing an outOfBoundsException
for( j=0;j<array.length;j++){
if(array[j]>array[j+1]){
array[j]=array[j+1];
array[j+1]=array[j];
}
}
Since array.length = 5 and j < array.length, the value array[j+1] in the last round of the inner loop cause array out of bound exception.
The swap needs another variable to hold array[j] before changing it.
e.g:
int x;
for( j=0;j<array.length - 1;j++){
if(array[j]>array[j+1]){
x = array[j];
array[j]=array[j+1];
array[j+1]=x;
}
}
The bubble sort algorithm can be implemented as follows
public static void sort(int[] arr){
int len = arr.length;
int k = 0;
for(int j = 0 ; j < len-1; j++){
for(int i= 0+k; i < len-1; i += 2){
if(arr[i] <= arr[i+1])
continue;
int tmp = arr[i];
arr[i] = arr[i+1];
arr[i+1] = tmp;
}
k++;
if ( k % 2 == 0)
k = 0;
} }
The inner loop must alternately start at indexes 0 and 1 so as not to always swap the same pairs (k variable).
The others have already pointed out why you're getting an exception.

Java - Printing 2d array with (with spaces between lines) [duplicate]

This question already has answers here:
The best way to print a Java 2D array? [closed]
(14 answers)
Closed 7 years ago.
I have a basic java question - I have an array and I need to do a multiplication of all the elements, so for input:
1 2 3
The output will be:
1 2 3
2 4 8
3 6 9
How can I print the 2d array from the main ?
PS - I want the method just to return the new 2d array, without printing it ( I know I can do it without the method and and print mat[i][j] within the nested loop)
public class Main {
public static void main(String[] args) {
int[] array = {1, 2, 3};
System.out.println(matrix(array));
}
public static int[][] matrix(int[] array){
int[][] mat = new int[array.length][array.length];
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array.length; j++) {
mat[i][j] = array[i] * array[j];
}
}
return mat;
}
}
You have to print all the individual elements of the array, because if you just try to print an array, it will print all kinds of other stuff you might not want to see. So you cherry pick out what you want, and format it a little. In the below code you have each element printed, seperated on a space until it reaches a new row, where it then jumps to a new line.
int[][] matrixArray = matrix(array);
for(int i = 0, i < matrixArray.length; i++) {
for(int j = 0; j < matrixArray[0].length; j++) {
System.out.print(matrixArray[i][j] + " ");
}
System.out.println();
}

how to print number of occurences of element of an 1d array [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I have worked on this but I keep getting an exception. Can anyone tell me where the problem is?
package assingment;
public class frequencyCount {
static void count(int x[]){
System.out.println("ENTERED ARRAY IS ");
for( int i=0; i < x.length; i++)
{
System.out.print(x[i]);
}
int c[] = new int [x.length];
for(int i=0; i<c.length ;i++)
{ c[i] = 0;
}
for(int i=0; i< x.length ;i++){
int m= x[i];
c[m]++;
}
System.out.println("frequency table");
for(int i=0; i< c.length ;i++){
System.out.print(i + " "+ c[i]);
}
}
public static void main(String[] args) {
count(new int []{1,1,5,2,10});
}
}
This is because you are incorrectly allocating the space to store your counts properly. What you need is to create an array where the total number of elements is the maximum of your array, plus 1 to account for 0. I'm going to assume that all of your numbers are positive to make things simple. As such, you actually need to determine what the maximum value is in your array first, then allocate the space accordingly.
By not doing this, when you specify the value of 5 in your array, you only allocated an array of size 5, and so if you try using 5 to index into your array, you get an OutOfBounds exception as you are trying to access the sixth position of the array, where it doesn't exist.
FWIW, there are much more smarter ways to do this, such as using a HashMap, but I'm assuming you haven't covered more advanced data structures in your Java course yet, and you probably need a solution with arrays. However, I completely recommend using HashMap.
As such, modify your code to find the maximum first, then allocate accordingly:
package assingment;
public class frequencyCount {
static void count(int x[]){
System.out.println("ENTERED ARRAY IS ");
// NEW - To store maximum
int maxi = -1;
for( int i=0; i < x.length; i++)
{
System.out.println(x[i]);
// Keep checking for the maximum
if (x[i] > maxi)
maxi = x[i];
}
// NEW - modify length to account for maximum
int c[] = new int [maxi+1];
for(int i=0; i<c.length ;i++)
{
c[i] = 0;
}
for(int i=0; i< x.length ;i++){
int m= x[i];
c[m]++;
}
System.out.println("frequency table");
for(int i=0; i< c.length ;i++){
System.out.println(i + " "+ c[i]);
}
}
public static void main(String[] args) {
count(new int []{1,1,5,2,10});
}
}
You are trying to access c[m] where m=x[i] in 3rd cycle. But x[2]=5 and c[5] causes an exception since there are only 5 elements in c[] (from c[0] to c[4])

Categories

Resources