Array rotate with juggling algorithm fails - java

This question is from G4G array rotation. I am getting an error in the second loop telling me the array is getting out of scope. But I don't understand why.
import java.util.Scanner;
public class timba {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n, d;
n = sc.nextInt();
d = sc.nextInt();
int[] arr = new int[n];
for (int i = 0; i < arr.length; i++) {
arr[i] = sc.nextInt();
}
while (d > 0) {
int t;
t = arr[0];
for(int j = 0; j < arr.length; j++) {
arr[j] = arr[j+1];
}
arr[n-1] = t;
d--;
}
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
}
}

Inside the second loop, j + 1 index will be out of bounds once j hits arr.length - 1 since indices start from 0, therefore it should be j < arr.length - 1

This should be your exception:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 6 out of bounds for length 6
at timba.main(timba.java:30)
This is caused because your code is letting me input 7 elements when I only specified I want to input 6. Have a look at this line.
for(int i=0;i<arr.length;i++){
arr[i]=sc.nextInt();
}
Say I specified that n is 5 so the length of the array is 5, but, this is letting me input 6. This can simply be fixed by adding a -1 to the code.
for(int i=0;i<arr.length - 1;i++){
arr[i]=sc.nextInt();
}
Next bit of code we have to look at is
for(int j=0;j<arr.length;j++){
arr[j]=arr[j+1];
}
This is a common mistake that beginner Java programmers make. This will always go out of bounds because when j = 4, then "arr[4] = array[5]" but your array only goes up to arr[4] because I only wanted to input 5 elements. That's why the compiler gave you that exception. You can fix this by adding a "-1" just like the previous mistake you made and this should fix this exception.
for(int j=0;j<arr.length - 1;j++){
arr[j]=arr[j+1];
}
Your new code should be
import java.util.Scanner;
public class timba {
public static void main(String[] args) {
Scanner sc= new Scanner(System.in);
int n,d;
n=sc.nextInt();
d=sc.nextInt();
int[] arr= new int[n];
for(int i=0;i<arr.length - 1;i++){
arr[i]=sc.nextInt();
}
while(d>0){
int t;
t=arr[0];
for(int j=0;j<arr.length - 1;j++){
arr[j]=arr[j+1];
}
arr[n-1]=t;
d--;
}
for(int i=0;i<arr.length;i++){
System.out.println(arr[i]);
}
}
}
This should be it for the exceptions, but you also need to fix the code's functionality as it is not giving you the answer that it is supposed to. I think that it can be fixed with just a little bit more of revising and changing the while loop (int t might be causing the problem.)
I hope you enjoy your journey with Java. Have a great day and remember to stay safe!

Related

Why this error of sorting occuring only in cases of >5 table elements?

please see my code for BubbleSorting. When I choose 5 or more numbers for my table to be sorted I get an error:
at first.firstt.sorting_v2.sorting(sorting_v2.java:35).
Completely do not know why it occured, when I choose 2 or three element to sort it works perfect.
I know it can be made different way, this type of sorting but please show me what I did wrong as still learn and I'm very curious about the details of this error hmm.
Also see the image below:enter image description here
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Choose how much number you want to sort:");
int sizeOfTab = scanner.nextInt();
int[] numbers = new int[sizeOfTab];
for (int i = 0; i < sizeOfTab; i++) {
System.out.println("Choose number to collection: ");
numbers[i] = scanner.nextInt();
}
scanner.close();
System.out.println(Arrays.toString(sorting(numbers)));
}
private static int[] sorting(int[] numbers) {
boolean notDone = false;
for (int i = 0; i < numbers.length - 1; i++) {
for (int j = 1; j < numbers.length; j++) {
if (numbers[i] > numbers[j]) {
int tmp = numbers[j];
numbers[j] = numbers[i];
numbers[i] = tmp;
notDone = true;
}
}
}
return notDone ? sorting(numbers) : numbers;
}
}
Your logical error is that you are always restarting your second inner loop from j = 1 aka the second element in
for (int j = 1; j < numbers.length; j++) { ... }
You only ever want to compare numbers[i] > numbers[j] for cases where j is greater than i.
Lets say you have the array [1, 2, 3, 4]
Currently your loop will run and reach a point where it will check numbers[2] > numbers[1] and switch the second and third element despite the array already being sorted.
To fix this simply always have your second loop start from the current value of i with 1 added:
for (int j = i+1; j < numbers.length; j++) { ... }

Need help in understanding this specific descending order selectiion sort of integers

As said in title, this is a descending sort of integer using selecction sort.This is the program.. I m having difficulties in understanding the steps. Can someone help me in understanding it? Thanks in advance!!
import java.util.Scanner;
public class Selectionsort_descending
{
public static void main(String args[])
{
int i,j,k,m,n;
Scanner sc = new Scanner(System.in);
System.out.println("Enter any number");
n=sc.nextInt();
int a[]=new int [n];
for (i=0;i<=n-1;i++)
{
System.out.println("Enter number");
a[i]=sc.nextInt();
}
for (j=0;j<=n-1;j++)
{
for (k=j;k<=n-1;k++)
{
if (a[j]<a[k])
{
m=a[j];
a[j]=a[k];
a[k]=m;
}
}
}
for (i=0;i<=n-1;i++)
{
System.out.print(a[i]+" ");
}
}
}
First of all I would highly suggest to get your code more formatted. In Eclipse it is done by pressing [Ctrl]+[Shift]+[F].
By doing that, your code should look like that (I did some improvements which I will explain then).
import java.util.Scanner;
public class Selectionsort_descending {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter any number");
int n = sc.nextInt();
int a[] = new int[n];
for (int i = 0; i < n ; i++) {
System.out.println("Enter number");
a[i] = sc.nextInt();
}
for (int j = 0; j < n ; j++) {
for (int k = j; k < n; k++) {
if (a[j] < a[k]) {
int m = a[j];
a[j] = a[k];
a[k] = m;
}
}
}
for (int i = 0; i < n ; i++) {
System.out.print(a[i] + " ");
}
sc.close();
}
}
Firstly I changed the "i <= n-1" to "i < n" because I think it is much more readable like this.
Secondly I declared all variables when they were actually used and not right at the beginning as you did.
In the first for-loop you enter your numbers through the console.
Then you check each number of your Array: (j for Loop)
go through all numbers which came after this number (k for Loop)
is the current number (a[j]) less than a number that is located later in the Array (a[k]) ? → Change positions
This algorythm is also called "Selection Sort" if you want to read more about it.
I hope i could help you!
Since the swap is done inside the inner loop, it's a bubble sort or something similar. If the swap is done outside the inner loop, it's a selection sort or something similar. Wiki links:
http://en.wikipedia.org/wiki/Bubble_sort
http://en.wikipedia.org/wiki/Selection_sort

2D array trouble finding char element(s)

I am trying to find the longest series of horizontal O's in my 2d array and just print out the longest path. I don't see my logic error, I keep reading over this but don't see my error. I have been stuck here for about 2 days. I am thinking maybe there is something wrong with my finding max length statement? I get an out of bounds error on line 58 and 31. Any advice to what I'm doing wrong would be much appreciated.
public class game {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Scanner kbd = new Scanner(System.in);
System.out.println("ENTER A SINGLE INTEGER: ");
int n = kbd.nextInt();
char[][] mazeValue = new char[n][n];
System.out.println("ENTER A PATH: ");
for(int i = 0; i < mazeValue.length; i++ ){
for(int j = 0; j< mazeValue[i].length; j++){
mazeValue[i][j]= kbd.next().charAt(0);
}
}
printMaze(mazeValue);
horizontalPath(mazeValue);
}
public static void printMaze(char mazeValue[][])
{
System.out.println("MAZE");
for(int i = 0; i < mazeValue.length; i ++)
{
for (int j = 0; j < mazeValue[i].length; j++)
{
System.out.printf("%4c",mazeValue[i][j]);
}
System.out.printf("\n");
}
}
public static void horizontalPath(char mazeValue[][])
{
int horizontalPath=0;
int maxHorizontalCount=0;
int i;
int j;
for(i= 0; i<mazeValue.length; i++){
for(j = 0; j<mazeValue[i].length; j++){
if(mazeValue[i][j]== 'o'){
horizontalPath = horizontalPath + mazeValue[i][j];
}
}
if(horizontalPath < mazeValue[i][j])
maxHorizontalCount = mazeValue[i][j];
}
System.out.printf("Longest horizontal path row %d length %d",i,maxHorizontalCount);
}
}
I'm guessing you have some imports before your code which offsets the line numbers, and your problem is in line 47 in the code above:
if(horizontalPath < mazeValue[i][j])
maxHorizontalCount = mazeValue[i][j];
This block is outside of your for loop over j. This means that by the time control gets here, j will be equal to n, thus causing an index out of bounds.
Also note you're not actually computing a max value of anything, just setting maxHorizontalCount to the value at [i][j]. To compute a max, you should do something like
maxHorizontalCount = maxHorizontalCount > mazeValue[i][j] ? maxHorizontalCount : mazeValue[i][j];
or use Math.max() of course.

How to stop a "ArrayIndexOutOfBounds" exception

Hi guys I've been learning java over the summer and this is the last assignment, and I'm stuck. The program is supposed to take 13 numbers that I enter, sort them and then find the index number of the greatest number that I input in the original array. I'm trying to see if my selection method works but every time I try to enter in the numbers I get an out of bounds error. This is kind of frustrating and I've been trying to find and answer for a couple of hours now. Any help would be greatly appreciated. Thanks!
import java.util.Scanner;
public class fmax
{
public static void main(String[] args)
{
int indmax;
int[] fmax = new int[13];
fillmax(fmax);
//System.out.println(fmax);
indmax = maxfmax(fmax);
//indmin = minfmax();
System.out.println(indmax);
}
public static void fillmax(int[] farray)
{
Scanner sc = new Scanner(System.in);
int i = 0;
for(i = 0; i < farray.length; i++)
{
farray[i] = sc.nextInt();
}
}
public static int maxfmax(int[] farray)
{
int[] copy = farray;
int j, x=0, i;
boolean flag = true;
int temp;
while(flag)
{
flag = false;
for( j = 0; j < copy.length -1; j++)
{
if(copy[j] < copy[j+1])
{
temp = copy[j];
copy[j] = copy[j+1];
copy[j+1] = temp;
flag = true;
}
}
for(i=0; i <= farray.length; i++)
{
if(farray[i] == copy[1])
x = i;
}
}
return x;
}
}
This line will throw the out of bounds exception.
for(i=0; i <= farray.length; i++)
Your termination condition is incorrect. Try this:
for(i=0; i < farray.length; i++)
so that you stop the loop before you go past the last index (farray.length - 1).
You defined the Lenght of the Array as 13 than you run this line:
for(i=0; i <= farray.length; i++)
This means you will go for the items fmax[13] which doesnt exist, because java starts counting at 0. So the hightest index is fmax[12]. You need to change your condition to something like that:
for(i=0; i < farray.length; i++)
or
for(i=0; i <= farray.length -1; i++)
In this case length for array is returning size of your array - but it starts with 1 not with zero.
i <= farray.length - causes out of bounds exception
u have to use - as was mentioned i < farray.length in your for loop
Array always has index beginning with zero and ending with length-1
for(i=0; i <= farray.length; i++)
Your terminating condition is wrong. It is trying to access element located at index length, which does not exist and hence you get the exception. It should be modified to something like below to make it work:
for(i=0; i < farray.length; i++)

Turning 2 arrays into a two-dimensional array in java

Hi I am trying to take two arrays and turn them into one 2 dimensional array. However, I keep getting an error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
at test5.sum(test5.java:12)
at test5.main(test5.java:38)
Here is my code:
public class test5 {
int[][] final23;
public int[][] sum(int[] x, int[] y) {
final23 = new int[2][x.length];
for (int i = 0; i < final23[i].length; i++) {
final23[1][i] = x[i];
final23[2][i] = y[i];
}
return final23;
}
public void print() {
for (int i = 0; i < final23[i].length; i++) {
for (int j = 0; j < final23[i].length; j++) {
System.out.print(final23[i][j] + " ");
}
}
}
public static void main(String[] args) {
int l[] = { 7, 7, 3 };
int k[] = { 4, 6, 2 };
test5 X = new test5();
X.sum(k, l);
X.print();
}
}
I am not really sure what the problem is. Sorry if the question is dumb, I am new to coding!
The problem is:
final23 [2][i] = y[i];
Java arrays always start at 0. So final23 only has [0] and [1].
Any array with n elements can go from 0 to n-1.
There is also a second problem with your program. You have this loop in both sum and print methods:
for (int i = 0; i < final23[i].length; i++)
In sum method it should be
for (int i = 0; i < final23[0].length; i++)
And in print method
for (int i = 0; i < final23.length; i++)
Otherwise you'll get ArrayIndexOutOfBoundsException again.
Note that the program works correctly only if both input arrays have the same length. This might be ok for your purposes, but keep that in mind.
Try
for (int i = 0; i < final23[i].length; i++)
{
final23 [0][i] = x[i];
final23 [1][i] = y[i];
}
Remember, all arrays are 0 based, even n-dimensional ones.

Categories