Array Index Out of Bounds Error in Java - java

package test1;
import java.util.Scanner;
public class Question2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int traincars;
int maxweight;
int count = 0;
int total = 0;
maxweight = input.nextInt();
traincars = input.nextInt();
int[] trains = new int[traincars];
for(int i = 0; i < traincars; i++)
{
trains[i] = input.nextInt();
}
if (total < maxweight)
{
for(int i = 0; i < traincars; i++)
{
total = trains[i] + trains[i+1] + trains[i+2] + trains[i+3];
count++;
}
}else
{
count = count + 3;
}
System.out.println("count");
}
}
this is a really simple program but for some reason, the array for the traincars goes out of bounds..
Why is this happening?

The problem is here:
for(int i = 0; i < traincars; i++)
{
total = trains[i] + trains[i+1] + trains[i+2] + trains[i+3];
count++;
}
When i equals traincars-1 you will be accessing elements i+1, i+2. and i+3 which are out of bounds of your trains array.
If your logic is calling for calculating totals of 4 consecutive elements of the array then your for loop should stop earlier:
for(int i = 0; i < traincars - 3; i++) {...}

In the last iteration of
for(int i = 0; i < traincars; i++)
{
total = trains[i] + trains[i+1] + trains[i+2] + trains[i+3];
count++;
}
You try to access trains[i+1] and this is bigger than the length of your trains array.
To make this for loop matter you should just do the following:
for(int i = 0; i < traincars; i++)
{
total += trains[i]; //unless of course you need something else...
count++;
}

Related

Program that removes duplicated elements and return its new elements and size

My code is almost done but the problem is the returning size it supposed to return the size after the duplicated elements has been removed. it wont output the right size.
import java.util.Scanner;
import java.util.Arrays;
public class Main
{
public static void main (String[] args)
{
int size;
int i;
int j;
Scanner scn = new Scanner(System.in);
System.out.print("Enter the number of elements: ");
size = scn.nextInt();
System.out.println("\n");
int myArray[] = new int [size];
for(i = 0; i < size; i++)
{
System.out.print("Enter value for num["+i+"]: ");
myArray[i] = scn.nextInt();
}
System.out.print("\nThe inputted values are ");
for(i = 0; i < size; i++)
{
System.out.print(" " + myArray[i] + ",");
}
System.out.print("\nDuplicate values ");
for (i = 0; i < myArray.length-1; i++)
{
for (j = i+1; j < myArray.length; j++)
{
if ((myArray[i] == myArray[j]) && (i != j))
{
System.out.print(" " +myArray[j]+ ",");
}
}
}
int length = myArray.length;
length = remove_dupli(myArray,length);
System.out.print("\nThe new values of the array are ");
for(i = 0; i < length; i++)
{
System.out.print(" " +myArray[i]+", ");
}
System.out.println("\nThe new length of the array is: "+array_sort(myArray));
}
is there a problem on this part?
public static int remove_dupli(int myArray[], int n){
if (n==0 || n==1){
return n;
}
int[] temp = new int[n];
int j = 0;
for (int i=0; i<n-1; i++){
if (myArray[i] != myArray[i+1]){
temp[j++] = myArray[i];
}
}
temp[j++] = myArray[n-1];
for (int i=0; i<j; i++){
myArray[i] = temp[i];
}
return j;
}
or this part?
public static int array_sort(int[] myArray) {
int index = 1;
for (int i = 1; i < myArray.length; i++) {
if (myArray[i] != myArray[index-1])
myArray[index++] = myArray[i];
}
return index;
}
}
The output should be:
Enter Number of Elements: 4
Enter value for num[0]: 2
Enter value for num[1]: 2
Enter value for num[2]: 3
Enter value for num[3]: 4
The inputted values are 2,2,3,4
Duplicated values 2,
The new values of the array are 2,3,4
The new length of the array is 3
The process you are using to find the duplicate elements is fine but you are not actually changing the elements in the array , you are just printing the non-duplicate ones, best approach is to change the value of the duplicate elements as a flag and then to find the length of the array after the duplicates have been removed,it will be easy :
for(int i=0;i<array.length;i++){
for(int j=i+1;j<array.length;j++)
{
if((array[i]==array[j]) && i!=j)
System.out.println("duplicate value:"array[j]);
array[j]=-1;
}
}
So, now for the array length after removing the duplicate elements is:
int count=0;
for(int i=0;i<array.length;i++){
if(array[i]!=-1)
count ++;
}

I need to find the first maximum element in a 2D matrix using java but the code doesn't seem to work like i wanted it to. Can anyone help me?

I need the maximum elements position if there is more than one maximum element then the first one is to be printed.
My code prints the position of the maximum element but not the first one.
I don't understand why the last iteration is not working as I intend it to.
Please solve it using only Java.
import java.util.Scanner;
class Main {
public static void main(String[] args) {
// put your code here
Scanner sc = new Scanner(System.in);
// define lengths
int n = sc.nextInt();
int m = sc.nextInt();
// add length to matrix
int[][] matrix = new int[n][m];
// insert elements
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
matrix[i][j] = sc.nextInt();
}
}
// define max
int max = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (matrix[i][j] > max) {
max = matrix[i][j];
}
}
// System.out.print(i + " " + j);
}
// System.out.print(max + " ");
// print index of highest element
// int pos1 = 0;
// int pos2 = 0;
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
if (matrix[i][j] == max) {
System.out.print(i + " " + j);
break;
}
// pos2 += 1;
break;
}
// pos1 += 1;
// break;
}
}
}
There is no need to go through the matrix twice. When you are searching for the max, store also the coordinates of the matrix where that max was found. A code example:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
// put your code here
Scanner sc = new Scanner(System.in);
// define lengths
int n = sc.nextInt();
int m = sc.nextInt();
// add length to matrix
int[][] matrix = new int[n][m];
// insert elements
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
matrix[i][j] = sc.nextInt();
}
}
// define max
int max = Integer.MIN_VALUE, row=0, col=0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (matrix[i][j] > max) {
max = matrix[i][j];
row=i;
col=j;
}
}
}
System.out.print("max: "+max + " is at: ");
System.out.print(col + " " + row); //indexes starting from zero
}
}
Create a new variable to hold the position of the max value and set it in the current loop
int max = matrix[0][0];
int[] maxPos = new int[2];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (matrix[i][j] > max) {
max = matrix[i][j];
maxPos[0] = i;
maxPos[1] = j;
}
}
}
and then remove the rest of the code and print the result
System.out.printf("Max is %d and is found at [%d, %d]\n", max, maxPos[0], maxPos[1]);

why do I get -1 when i try to delete an element in an array

I checked out the questions that were already posted, but I still couldn't find a solution.
My output for the code is:
Enter the number of integers: 5
Enter 5 integers: 1
2
3
4
5
Enter the number to be deleted: 2
-1
package array;
import java.util.*;
//import java.util.ArrayLists;
public class DeleteFromArray {
public static void main(String[] args) {
int n = 0; // number of integers
int d = 0; // the number to be deleted
int count = 0;
Scanner scan = new Scanner(System.in);
System.out.print("Enter the number of integers: ");
n = scan.nextInt();
if (n <= 0) {
System.out.println("Invalid input");
System.exit(-1);
}
int[] buffer = new int[n];
System.out.print("Enter " + n + " integers: ");
for (int k = 0; k < buffer.length; k++) {
buffer[k] = scan.nextInt();
}
System.out.print("Enter the number to be deleted: ");
d = scan.nextInt();
for (int i = 0; i < buffer.length; i++) {
if (buffer[i] == d) {
for (int j = 0; j < (buffer.length) - 1; j++) {
buffer[j] = buffer[j + 1];
}
count++;
break;
}
}
if(count ==0) {
System.out.println("Element not found!");
}
else {
System.out.print("Element Deleted Successfully..!!");
System.out.print("\nNow the New Array is :\n");
for (int i = 0; i < (buffer.length)-1; i++) {
System.out.println(buffer[i]+ " ");
}
}
scan.close();
}
}
Your for loop
for (int j = 0; j < (buffer.length) - 1; j++) {
buffer[j] = buffer[j + 1];
}
will not work properly because it will replace the value at 0 index with the value at index 1 and so on. What you want to do is just intialize the j=i where i is the index of d. and it will replace this value with the next.
for (int j = i; j < (buffer.length) - 1; j++) {
buffer[j] = buffer[j + 1];
}
Try this loop it will work.

Sort random array in ascending order without arrays.sort

I am trying to sort an array of random numbers without using the arrays.sort. I have the code, but it doesn't work. not sure where is the error. Any kind of help is appreciated.
import java.util.*;
public class Sort
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
System.out.print("How many numbers do you want? ");
int howMany = in.nextInt();
int [] myArray = getRandomArray(howMany);
}
/* public static int bsearch(int[] arr, int key)
{
}*/
public static int[] getRandomArray(int howMany) {
int[] returnMe = new int[howMany]; // Assume size >= 0
Random rand = new Random();
for (int i = 0; i < howMany ; i++)
returnMe[i] = rand.nextInt(Integer.MAX_VALUE) + 1;
//System.out.print(returnMe[i] + " ");
for (int i = 1; i <= (howMany - 1); i++)
{
for (int j = 0; j < howMany - i -1; j++)
{
int tmp = 0;
if (returnMe[j] > returnMe[j+1])
{
tmp = returnMe[j];
returnMe[j] = returnMe[j + 1];
returnMe[j + 1] = tmp;
}
}
}
for ( int i = 0; i < howMany; i++)
System.out.println(returnMe[i] + " ");
return returnMe;
}
}
Your line
for (int j = 0; j < howMany - i -1; j++)
should be
for (int j = 0; j <= howMany - i -1; j++)
or alternatively, remove the "-1" and keep "<". Otherwise, you will ignore the last number in the array. Everything else looks fine to me.

Simple Java Fibonacci code issue

import java.util.Scanner;
public class Fibonacci
{
public static void main(String[] args)
{
int count;
Scanner in = new Scanner(System.in);
System.out.println("Please enter number");
count = in.nextInt();
int[] fib = new int [count];
fib[0] = 1;
fib[1] = 1;
for (int i=2; i<count; i++)
{
fib[i] = fib[i-1] + fib[i-2];
}
for(int i=0; i<count; i++)
{
System.out.print(fib[i] + " ");
}
}
}
This is my very simple Fib program, what i cant figure out is why it always stops one number short. For example:
run: Please enter number 6 1 1 2 3 5 8 BUILD SUCCESSFUL (total time: 5
seconds)
run: Please enter number 7 1 1 2 3 5 8 13 BUILD SUCCESSFUL (total
time: 5 seconds)
I thought in my FOR loops it should be "(int i=2; i <= count;"
but when i put in greater than or equal to in both, or either FOR loop it gives me an error
Any suggestions? i know its something easy i'm overlooking
Your code is giving correct output. but still if you need one more element try to initialize array with count + 1 and then have your loop running for i <= count
public static void main(String[] args) {
int count;
Scanner in = new Scanner(System.in);
System.out.println("Please enter number");
count = in.nextInt();
int[] fib = new int [count+1];
fib[0] = 1;
fib[1] = 1;
for (int i=2; i <= count; i++){
fib[i] = fib[i-1] + fib[i-2];
}
for(int i=0; i <= count; i++){
System.out.print(fib[i] + " ");
}
}
}
Arrays are zero-based. This means, that (assuming count = 5) if you have the following array:
int[] fib = new int[5];
then you can access fib[0], fib[1], fib[2], fib[3] and fib[4]. So
for (int i = 0; i < 5; i++) {
System.out.print(fib[i] + " ");
}
would be fine. As it would access everything in fib, starting with index 0, and stopping with the last index smaller than 5, which is 4. However, if you do:
for (int i = 0; i <= 5; i++) {
System.out.print(fib[i] + " ");
}
then you will access the last index smaller than OR EQUAL TO 5, which is 5. But, as stated before, fib[5] is invalid. That's what gives you your error.
A simpler solution is to avoid needing an array in the first place and you don't need to get the size right.
public static void main(String[] args) {
System.out.println("Please enter a number");
Scanner in = new Scanner(System.in);
int count = in.nextInt();
long a = 1, b = 1;
for(int i = 0; i < count; i++) {
System.out.print(a + " ");
long c = a + b;
a = b;
b = c;
}
System.out.println();
}
There should be one more array element space for int fib[], thus the fib[count] could be stored.
import java.util.Scanner;
public class Fibonacci
{
public static void main(String[] args)
{
int count;
Scanner in = new Scanner(System.in);
System.out.println("Please enter number");
count = in.nextInt();
int[] fib = new int [count + 1];
fib[0] = 1;
fib[1] = 1;
for (int i=2; i <= count; i++)
{
fib[i] = fib[i-1] + fib[i-2];
}
for(int i = 0; i<= count; i++)
{
System.out.print(fib[i] + " ");
}
}
}
public class Fibonacci
{
private int [] fibArray;
public Fibonacci()
{
}
public void Fibonacci()
{
fibArray = new int[0];
}
public void setFibonnaci(int size)
{
fibArray = new int[size];
if(fibArray.length == 1)
{
fibArray [0] = 0;
}
else if(fibArray.length == 2)
{
fibArray[0] = 0;
fibArray[1] = 1;
fibArray[2] = 2;
}
else
{
fibArray[1] = 1;
fibArray[0] = 0;
for(int x = 2; x < fibArray.length; x++)
{
fibArray [x] = fibArray[x-1] + fibArray[x-2];
}
}
}
public int getSequence(int number)
{
if(number -1 < fibArray.length)
{
return fibArray[number - 1];
}
return -1;
}
//check the test case for getFibo
public String toString()
{
String output = "";
for (int x = 0; x < fibArray.length; x++)
{
output += x + " - " + fibArray[x];
}
return output;
}
}
Late response but new to site and just trying to help. This fib class works 100%

Categories