How to fix array index out of bounds error? - java

The error that I am getting
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 610
at Fib.sorted(Fib.java:67)
at Fib.main(Fib.java:17)
My code
public class Fib
{
public static void main(String args[])
{
System.out.println(Arrays.toString( fiblist) );
System.out.println(Fib.add());
System.out.println(Fib.square());
System.out.println(Fib.reversal());
System.out.println(Fib.sorted());
}
public static int fiblist[] = {1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597,2584,4181,6765};
public static int fiblen = fiblist.length;
public Fib()
{
// Do nothing
}
public static ArrayList<Integer> sorted()
{
ArrayList sorted = new ArrayList();
for(int counter = 0; counter < fiblist[4]; counter++ )
{
int temp1 = fiblist[counter];
System.out.println("Elements stored " + temp1);
}
for(int counter = fiblist[14]; counter < fiblist[19]; counter++)
{
int temp2 = fiblist[counter];
System.out.println("Last Elements stored " + temp2);
}
return sorted;
}
}
I'm trying to store the last 5 elements of my array in temp 2.
Then I will switch them.
Is there an easier way to do this?
Switch the first five elements of an array with the last five?
How would you switch them with a for loop?

You are confusing array index and value. fiblist[19] is 6765. You want your counters to go from 0 to 4 and 14 to 19, not fiblist[19].
for(int counter = 0; counter < 4; counter++ )
{
int temp1 = fiblist[counter];
System.out.println("Elements stored " + temp1);
}
for(int counter = 14; counter < 19; counter++)
{
int temp2 = fiblist[counter];
System.out.println("Last Elements stored " + temp2);
}

This works
for(int i=0;i<fiblist.length;i++){
System.out.print(fiblist[i]+",");
}
System.out.println();
for (int i=0;i<5;i++){
temp=fiblist[i];
fiblist[i]=fiblist[fiblist.length-i-1];
//the first ellement= the last
//the second=second from last...
fiblist[fiblist.length-1-i]=temp;
}
for(int i=0;i<fiblist.length;i++){
System.out.print(fiblist[i]+",");
}
Output:
1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597,2584,4181,6765,
6765,4181,2584,1597,987,8,13,21,34,55,89,144,233,377,610,5,3,2,1,1,

Try this. It's a sorting algorithm (A fairly poor one though)
public static void sort(int[] a) {
int iMin;
int n = a.length;
for (int j = 0; j < n-1; j++) {
iMin = j;
for (int i = j+1; i < n; i++) {
if (a[i] < a[iMin]) {
iMin = i;
}
}
if(iMin != j) {
swap(j, iMin, a);
}
}
}
public static void swap(int i, int j, int[] arr){
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}

Related

Is this a selection sort or a bubble sort?

Is this a selection sort? I think it is Bubble Sort because I'm using (dot)compareTo. I look at different sources on the internet so I can make one. Here is the codes.
import java.util.Arrays;
public class SelectionSort {
public static void main(String args[]) {
String[] row = {"apple", "orange", "banana", "grapes", "mango", "avocado"};
int min = row.length;
for(int m = 0; m < min-1; m++) {
for (int n = m+1; n < row.length; n++) {
if(row[m].compareTo(row[n]) > 0){
String bar = row[m];
row[m] = row[n];
row[n] = bar;
}
}
}
System.out.println("Expected Outcome: " + Arrays.toString(row));
}
}
this is not selection sort
I selection sort in each iteration you find minimum value and put it to the proper location. See this picture
A simple implementation show here:
https://www.javatpoint.com/selection-sort-in-java
public class SelectionSortExample {
public static void selectionSort(int[] arr){
for (int i = 0; i < arr.length - 1; i++)
{
int index = i;
for (int j = i + 1; j < arr.length; j++){
if (arr[j] < arr[index]){
index = j;//searching for lowest index
}
}
int smallerNumber = arr[index];
arr[index] = arr[i];
arr[i] = smallerNumber;
}
}
public static void main(String a[]){
int[] arr1 = {9,14,3,2,43,11,58,22};
System.out.println("Before Selection Sort");
for(int i:arr1){
System.out.print(i+" ");
}
System.out.println();
selectionSort(arr1);//sorting array using selection sort
System.out.println("After Selection Sort");
for(int i:arr1){
System.out.print(i+" ");
}
}
}
It is not Selection Sort (Milad already answered this), but it is also not Bubble Sort.
The way you can tell that it is not bubble sort, is because bubble sort compares pairs of items that are next to each-other (ex: compares items at index 0-1, 1-2, 2-3... and swaps if necessary). In your code, when m=0, the inner loop will compare item at index 0 with all the other items in the array.
Bubble Sort in Java:
public void sort( int[] array) {
boolean isSorted;
for (var i = 0; i < array.length; i++) {
isSorted = true;
for (var j = 1; j < array.length - i ; j++)
if (array[j] < array[j - 1]) {
swap(array, j, j - 1);
isSorted = false;
}
if (isSorted)
return;
}
}
private void swap(int[] array, int index1, int index2) {
var temp = array[index1];
array[index1] = array[index2];
array[index2] = temp;
}

why is there an error in calling and checking the conditions of the array?

public class Hello {
public static void main(String [] args){
int [] testArray = new int [10];
for(int k = 0; k<testArray.length; k++){
testArray[k] = k + 1;
}
sum(testArray);
for(int m = 0; m<testArray.length; m ++ ){
if(testArray[m] == 7) {
increaseByn(testArray, 3);
sum(testArray);
break;
}
else {
increaseByn(testArray, 5);
sum(testArray);
break;
}
}
}
public static int sum(int [] nums){
int sum = 0;
for(int i = 0; i<nums.length; i++){
System.out.print(nums[i] + " ");
sum = sum + nums[i];
}
System.out.println("\n" + "Sum: " + sum);
return sum;
}
public static int increaseByn(int [] nums, int n){
int sum2 = 0;
for(int j = 0; j<nums.length; j++){
nums[j] = nums[j] + n;
sum2 = sum2 + nums[j];
}
return sum2;
}
}
// End of program
I would like to print the sum of the element in an array and also add 3 to each element if the previous array has 7, and add 5 to each element of the previous array otherwise.
I have two questions:
1.) How do I return the sum while calling the method sum?
2.) I want to check if the array has the above-listed numbers. Therefore, I wrote a for a loop. However, the for loop does not check both the conditions
Thank you in advance!
First of all, those breaks shouldn't be there, as they stop the loop after the first iteration:
for(int m = 0; m<testArray.length; m ++ ){
if(testArray[m] == 7) {
increaseByn(testArray, 3);
sum(testArray);
// break;
}
else {
increaseByn(testArray, 5);
sum(testArray);
// break;
}
}
Most surely the process increases 5 and just stops.
And in order to return the sum, you are already returning it (but doing nothing with it, as it is not referenced). You could save it into a new var:
int mySum = sum(testArray);
//do something with mySum
But then I'd delete those system outs into the sum function, if you don't want to saturate/duplicate the output:
public static int sum(int [] nums){
int sum = 0;
for(int i = 0; i<nums.length; i++){
//System.out.print(nums[i] + " ");
sum = sum + nums[i];
}
//System.out.println("\n" + "Sum: " + sum);
//return it and show it out of the function scope
return sum;
}
I would really caution against looping the same array so often, why not capture if a 7 is in the array, create your sum while you iterate it once, and then multiply the array.length with 3 or 5 depending on having nr 7?
public class Hello {
public static void main(String [] args){
int [] testArray = new int [10];
for(int k = 0; k<testArray.length; k++){
testArray[k] = k + 1;
}
int sum = 0;
boolean hasSeven = false;
for(int m = 0; m<testArray.length; m ++ ){
if(testArray[m] == 7) {
hasSeven = true;
}
sum += testArray[m];
}
sum += (hasSeven ? 3 : 5) * testArray.length;
System.out.println( sum );
}
}
You could set a boolean flag to true if a 7 is found in the array and only increase each array element by 5 if it is not found at the end of the loop. Your current code will increment each element by 5 and break the loop if the first element is not 7.
After getting the sum once, you can easily calculate the new sum after incrementing by adding the number of elements by the increment and adding that to the original sum.
int sum = sum(testArray);
int currSum = 0;
boolean foundSeven = false;
for(int m = 0; m<testArray.length; m ++ ){
if(testArray[m] == 7) {
increaseByn(testArray, 3);
foundSeven = true;
currSum = sum + testArray.length * 3;
break;
}
}
if(!foundSeven){
increaseByn(testArray, 5);
currSum = sum + testArray.length * 5;
}
//currSum now has the sum of the updated array

Counting array reference input and displaying count -- infinite loop

I am trying to display the occurrence of how many times an integer occurs in an array but I get an infinite loop/logic error. For instance, if the user enters: 2, 5, 6, 5, 4, 3, 23, 43, 2, 0 then it should display:
2 occurs 2 times
3 occurs 1 time
4 occurs 1 time
5 occurs 2 times
6 occurs 1 time
23 occurs 1 time
43 occurs 1 time
Any help would really be appreciated. Note: This is not an assignment or homework, It is a exercise question from intro to Java book by Y.D. Lang
import java.util.*;
public class CountNumbers {
public static void main(String[] args) {
System.out.println("Enter the integers between 1 and 100: ");
int[] arrayRefVar = createList();
int[] countNum = countNumbers(arrayRefVar);
displayCount(countNum, arrayRefVar);
}
public static int[] createList() {
Scanner Input = new Scanner(System.in);
int[] List = new int[100];
int i = 0;
while (List[i] != 0) {
List[i] = Input.nextInt();
i++;
}
return List;
}
public static int[] countNumbers(int[] List) {
int[] count = new int[100];
for (int i = 0; i < count.length; i++) {
count[i] = i;
}
int[] countNum = new int[List.length];
for (int i = 0; i < countNum.length; i++) {
countNum[i] = 0;
}
for (int i = 0; i < List.length; i++) {
for (int j = 0; j < count.length; j++) {
if (List[i] == count[j]) {
countNum[i]++;
}
}
}
return countNum;
}
public static void displayCount(int[] countList, int[] arrayRefVar) {
for (int i = 0; i < arrayRefVar.length; i++) {
System.out.println(arrayRefVar[i] + " occurs " + countList[i] + " " + checkPlural(arrayRefVar[i]));
}
}
public static String checkPlural(int n) {
if (n > 1) {
return "times";
} else {
return "time";
}
}
}
If your input should end in 0, then you should check whether the currently read int is zero or not.
while(i < List.length) {
List[i] = Input.nextInt();
if(List[i] == 0)
break ;
++i;
}
Since you are checking for the condition after incrementing i, you are not checking the current value.
Note : nextInt() method from the Scanner class can throw exceptions namely : InputMismatchException, NoSuchElementException and IllegalStateException. So either handle it in a try catch block or make the caller handle it by throwing the exception.
So I finally got it after countless tries, if anybody has any suggestions to make the code more efficient the input would be greatly appreciated. Here it is:
import java.util.Random;
public class CountSingleDigits {
public static void main (String[] args) {
int[] arrayRefVar = createList();
int[] counts = new int[10];
for (int i = 0; i < 10; i++) {
counts[i] = i;
}
int[] tempCounts = new int[10];
for (int i = 0; i < arrayRefVar.length; i++) {
for (int j = 0; j < 10; j++) {
if (arrayRefVar[i] == counts[j]) {
tempCounts[j]++;
}
}
}
for (int i = 0; i < 10; i++) {
System.out.println(counts[i] + " appears " + tempCounts[i] + " times ");
}
for (int i = 0; i < arrayRefVar.length; i++) {
if (i % 10 == 0) {
System.out.println();
}
System.out.print(arrayRefVar[i] + " ");
}
}
public static int[] createList() {
Random f = new Random();
int[] List = new int[100];
for (int i = 0; i < List.length; i++) {
List[i] = f.nextInt(9);
}
return List;
}
}
One issue is that your while loop for user input is never entered. You use 0 as the sentinel value to exit user input, however, when you initialize an array of integers, they are all 0 by default.
int[] List = new int[100];
int i = 0;
//problem: while loop never entered
while (List[i] != 0) {

Finding differences in a array

I'm not sure how to set the differences to store in the array differences. The numbers stored should be 5-(1+2+3), 7-(1,2,4), 8-(3,5,9) : the output should be differences[0]= 1, differences[1] = 0, differences[2] = 9
import java.util.Scanner;
public class Main {
public static int[][] Array = { { 5, 1, 2, 3 }, { 7, 1, 2, 4 }, { 8,3,5,9 } }; //My 2D array//
int [] differences = new int [3];
public static int[] Sum(int[][] array) {
int index = 0; //setting the index to 0//
int temp[] = new int[array[index].length]; //making a temperary variable//
for (int i = 0; i < array.length; i++) {
int sum = 0;
for (int j = 1; j < array[i].length; j++) {
sum += array[i][j]; //going to add the rows after the first column//
}
temp[index] = sum;
for(int a = 0; a<differences.length; a++){
if(sum != array[index][0])
sum -= array[i][j];
System.out.println("the first integer " + array[index][0] + " the answer is " + sum); //going to print out the first integer each row and print out the sum of each row after the first column//
index++; //index is going to increment//
}
return temp;
}
public static void main(String[] args) {
new Main().Sum(Array);
}
}
Output:
the first integer 5 the answer is 6
the first integer 7 the answer is 7
the first integer 8 the answer is 17
Why do you want to complicate the task of yours when it is this simple? :)
public int[] Sum(int[][] array)
{
int sum;
for(int i = 0; i < Array.length; i++)
{
sum = Array[i][0] * -1;
for(int j = 1; j < Array[i].length; j++)
{
sum += Array[i][j];
}
differences[i] = sum;
}
return differences;
}
If I understand your problem correctly, I think that you want to put a
differences[i] = Array[i][0] - sum
somewhere in your code

Implementation of selection sort in Java

I think I have done the selection sort but I am not sure. Is this really an implementation of selection sort?
static void selectionSort()
{
int min = Integer.MIN_VALUE;
int n = 0;
for(int I=0; I<arraySize; I++)
{
min = dataArray[I];
for(int j=I; j<n; j++)
{
if(dataArray[min]<dataArray[j])
{
min = j;
if(dataArray[min] < dataArray[I])
{
int temp = dataArray[I];
dataArray[I] = dataArray[min];
dataArray[min] = temp;
}
}
}
}
}
I'm not sure I understand how your algorithm works at all. Specifically, you do
min = dataArray[i];
and then later
dataArray[min]<dataArray[j]
i.e. you treat min both as a value in the array, and an index.
Selection sort works as follows:
Find the minimum value in the list
Swap it with the value in the first position
Repeat the steps above for the remainder of the list
(source)
The changes required for your code to accurately implement selection sort would be the following:
Change the inner loop to just find the index of the smallest element. Call it minIndex for instance.
Do the swapping after the inner loop. i.e., swap element at index I with minIndex.
Oh, and as DonCallisto points out in the comments, you may want to do n = dataArray.length instead of n = 0 :-)
public class SelectionSort {
/**
* #Author Chandrasekhara Kota
*/
public static void main(String[] args) {
int arr[]={9,1,8,5,7,-1,6,0,2,2718};
int sortedArr[]=selectionSort(arr);
for (int i = 0; i <sortedArr.length; i++)
{
System.out.println(sortedArr[i]);
}
}
private static int[] selectionSort(int[] arr) {
int minIndex, tmp;
int n = arr.length;
for (int i = 0; i < n - 1; i++)
{
minIndex = i;
for (int j = i + 1; j < n; j++)
if (arr[j] < arr[minIndex])
minIndex = j;
if (minIndex != i) {
tmp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = tmp;
}
}
return arr;
}
}
Here is a selection sort implementation in java -
public class SelectionSort {
static int intArray[] = { 10, 5, 100, 1, 10000 };
public static void doSort() {
for (int outer = 0; outer < intArray.length; outer++) {
int minPosition=outer;
for(int inner=outer;inner<intArray.length;inner++){
if(intArray[inner]<intArray[minPosition]){
minPosition=inner;
}
}
int temp=intArray[minPosition];
intArray[minPosition]=intArray[outer];
intArray[outer]=temp;
}
}
public static void printArray() {
for (int i = 0; i < intArray.length; i++) {
System.out.print(" " + intArray[i]);
}
}
public static void main(String args[]) {
System.out.print("Array Before Sorting->");
printArray();
doSort();
System.out.print("\nArray After Sorting ->");
printArray();
}
}
The above code is picked from - http://www.javabrahman.com/algorithms-in-java/selection-sort-in-java/. This link has detailed explanation on the working of the above code just in case you need the same.

Categories

Resources