Getting ArrayIndexOutOfBoundException during left-shift operation on Array [duplicate] - java

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 6 years ago.
This is the code which I tried to perform Array Left shift operation which works fine for a few inputs but as i am increasing the shift amount it gives an ArrayOutOfBoundException exception.
import java.util.Scanner;
public class ArrayShift {
public static void main(String[] args) {
int x,y;
int[] n = new int[10];
int temp = 0;
Scanner sc = new Scanner(System.in);
//x is size of array
x = sc.nextInt();
// y is the amount of shift
y = sc.nextInt();
for(int i = 0;i<x;i++)
{
n[i] = sc.nextInt();
}
//Outer forloop for shift amount = y
for(int k = 0;k<y;k++)
{
temp = n[0];
//Inner forloop for shift amount = 1
for(int i=0;i<x;i++)
{
n[i] = n[i+1];
}
n[x-1]=temp;
}
for(int i=0;i<x;i++)
System.out.print(n[i]+" ");
}
}
Output
20 10
41 73 89 7 10 1 59 58 84 77 77 97 58 1 86 58 26 10 86 51
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10
at ArrayShift.main(ArrayShift.java:14)

You are already declaring the size of the array as 10 in this statement:int[] n = new int[10];
which means even if you enter x value as 100 the value of the array size will still be 10. hence the Array Index out of bound exception

Related

Scanner nextInt() inside a for loop

Class code
import java.util.*;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
ArrayList<ArrayList<Integer>> rows = new ArrayList<>();
for (int i = 0; i < n; i++) {
int d = in.nextInt();
ArrayList<Integer> row = new ArrayList<>();
for (int j = 0; j < d; j++) {
row.add(in.nextInt());
}
rows.add(row);
}
int q = in.nextInt();
for (int i = 0; i < q; i++) {
System.out.println("test");
int x = in.nextInt();
System.out.printf("test2");
int y = in.nextInt();
System.out.println("I dont get it");
try {
System.out.println(rows.get(x - 1).get(y - 1));
} catch (IndexOutOfBoundsException e) {
System.out.println("ERROR!");
}
}
}
}
with this imput
5
5 41 77 74 22 44
1 12
4 37 34 36 52
0
3 20 22 33
5
1 3
3 4
3 1
4 3
5 5
Result
74
52
37
ERROR!
ERROR!
I don't understand how nextInt() works in the last loop. Why do the lines "I dont get it", "test", "test2" never get printed?
Why is the try block executed at the end of the loop and not during the loop?
How could the stdout print 4 results at once?
Please help.
I can see below output with your input.
test
test2I dont get it
74
test
test2I dont get it
52
test
test2I dont get it
37
test
test2I dont get it
ERROR!
test
test2I dont get it
ERROR!
Just remove your .class and compile again and check.
Based on your Input
Output array --> rows=[[41, 77, 74, 22, 44], [12], [37, 34, 36, 52], [], [20, 22, 33]]
In the first three iterations its printing
rows[0][2]=74
rows[2][3]=52
rows[2][0]=37
rows[3][2]=Error
-->because in your output array third index is an empty array [] ,there is nothing in the second position

java wont catch OutOfBounds exception [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 5 years ago.
Improve this question
The out of bounds exception isn't being shown and my code still runs
import java.util.*;
import java.io.*;
public class pr50
{
static String[] arr;
static int modes;
static int old;
static int[] nums;
public static void main(String[] args) throws IOException
{
Scanner in = new Scanner(new File("pr50.dat"));
int limit = in.nextInt();
in.nextLine();
for(int x = 0; x < limit; x++)
{
arr = in.nextLine().split(" ");
nums = new int[arr.length];
for(int b = 0; b < arr.length; b++)
{
nums[b] = Integer.valueOf(arr[b]);
}
Arrays.sort(nums);
old = 0;
modes = 0;
for(int y = 0; y < nums.length; y++)
{
int current = nums[y];
for(int c = 0; current == nums[y+c] && nums[y+c] < nums.length ; c++)
{
if(old < 1)
modes++;
else
old++;
current = nums[y+x];
}
}
if(modes > 1)
System.out.println(modes + " MODES");
else
System.out.println(modes + " MODE");
}
}
}
Here's a sample file:
2
56 77 66 22 33 55 66 66 66
80 93 87 72 80 77 43 87 98 99 100
The error is right here:
for(int c = 0; current == nums[y+c] && nums[y+c] < nums.length ; c++)
Think about this, the loop will run at least onece only if nums[y+c]
means nums[y] < nums.length but if in your array, the largest element is more than or equals the length of array, it will never consider nums[y+1], let's try:
1
1 2 3 //lenght = 3
2 MODES
Because at the largest element, 3 < 3 is fail, it will not run nums[y+1] at the next time loop, but if you type:
1
1 1 1 1 1 1 1 //lenght = 7
last element is 1 and 1 < 7, the loop will run next loop and check nums[6+1]
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 7
So to make it throw OutOfBoundsException, the largest element must be less than the length of line (Mean number of elements)!
run:
1
0
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at test.main(test.java:30)
C:\Users\Fes Nguyen\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 2 seconds)

sorted array in java using swap methods

My problem is when I sort a list it will get the last element of the array wrong, ending up with it at the beginning of the array. In my example it fails to sort the last element which is 9, ending up printed first ahead of small numbers such as 0 and 1. Here is my code:
public class ty {
public static void main(String[]argus){
int []numbers={45,23,34,545,56,23,4,1,66,0,9};
int j;
for( int i=0;i<numbers.length;i+=1){
int first=0;
for(j=0;j<=i;j+=1){
if(numbers[j]>=first){
first=numbers[j];
numbers[j]=numbers[i];
numbers[i]=first;}
}//inner loop
}//first loop
for(int i=0;i<numbers.length;i+=1){
System.out.print(numbers[i]+" ");}
}
}
//the output is 9 0 1 4 23 23 34 45 56 66 545
As you see, they are in order except for the 9 at the start which is out of place.
You have the wrong output as a result of a logical error. You have mistakes in the Selection sort technique. Here's how to do it:
int []numbers={45,23,34,545,56,23,4,1,66,0,9};
for(int i=0; i<numbers.length-1; i+=1){
int m = i;
for(int j=i+1; j<numbers.length; j+=1){
if(numbers[m]>numbers[j])
m = j;
}
int temp = numbers[m];
numbers[m] = numbers[i];
numbers[i] = temp;
}
for(int i=0; i<numbers.length; i+=1)
System.out.print(numbers[i]+"\t");
This will work correctly and give the output:
0 1 4 9 23 23 34 45 56 66 545

Two dimensional array bug (can't find it)

I am doing this homework project that produces the pascals triangle but I'm getting an error and I can't find it. I looked it over many times but to me it seems okay, Can someone help me find the bug?
public class PascalsTriangle {
public static void main(String[] args) {
int[][] triangle = new int[11][];
fillIn(triangle);
print(triangle);
}
public static void fillIn(int[][] triangle) {
for (int i = 0; i < triangle.size(); i++) {
triangle[i] = new int[i++];
triangle[i][0] = 1;
triangle[i][i] = 1;
for (int j = 1; j < i; j++) {
triangle[i][j] = triangle[i-1][j-1] + triangle[i-1][j];
}
}
}
public static void print(int[][] triangle) {
for (int i = 0; i < triangle.length; i++) {
for (int j = 0; j < triangle[i].length; j++) {
System.out.print(triangle[i][j] + " ");
}
System.out.println();
}
}
I assume you have already changed your code to use length instead of size as the other answer mentions.
When you call this method:
public static void fillIn(int[][] triangle) {
for (int i = 0; i < triangle.length; i++) {
triangle[i] = new int[i++]; // this line
triangle[i][0] = 1;
The line pointed out above should be:
triangle[i] = new int[i + 1];
When you call i++ the int array will be initialized with length i and then i will be incremented. You are already incrementing i in the declaration of your for loop. So, we take away the ++.
But then we have another problem. You start the loop at i = 0. Then you initialize an array with length 0. Then you add an element to that array. Something doesn't make sense. What you meant to do was to initialize the array as int[i + 1].
Finally the program displays some lines from Pascal's Triangle:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1
1 10 45 120 210 252 210 120 45 10 1
not sure this method exist
triangle.size()
try
triangle.length
instead

Changed from a regular array to an arrayList [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have written code that printed out integers from a .dat file and moved them into a regular array and printed out the average and standard deviation. Now I want to switch from a regular array to an ArrayList. I have written the code below but doesn't seem run correctly.
.dat file includes these numbers: "51 52 55 57 58 61 62 63 66 66 66 70 72 73 74 75 75 77 77 78 79 81 82 84 86 87 88 91 94 97"
Thanks for the help!
import java.io.*;
import java.lang.Math;
import java.util.*;
import java.text.DecimalFormat;
public class gradeSorter{
public static void main(String[] args) throws IOException {
{
DecimalFormat fmt = new DecimalFormat("0.000");
Scanner scanner = new Scanner(new File("grades.dat"));
double average;
double deviation;
double sum = 0;
int number = 0;
ArrayList<Integer> element = new ArrayList<Integer>();
for (int count = 0; count < element.size(); count++)
{
while (scanner.hasNext())
{
element.add(scanner.nextInt());
number = element.get(count);
for (int item : element){
sum += number;
System.out.println(number);
}
}
average = sum / element.size();
for (int i = 0; i < element.size(); i++)
{
sum += Math.pow((element.get(i) - average),2);
}
deviation = Math.sqrt((sum / (30-1)));
System.out.println("The average of these grades is : " + fmt.format(average));
System.out.println("The standard deviation of these grades is: " + fmt.format(deviation));
}
}
}
}
UPDATE***
import java.io.*;
import java.lang.Math;
import java.util.*;
import java.text.DecimalFormat;
public class gradeSorter{
public static void main(String[] args) throws IOException {
{
DecimalFormat fmt = new DecimalFormat("0.000");
Scanner scanner = new Scanner(new File("grades.dat"));
double average;
double deviation;
double sum = 0;
int number = 0;
int newnumber = 0;
ArrayList<Integer> element = new ArrayList<Integer>();
while (scanner.hasNextInt())
{
element.add(scanner.nextInt());
}
for (int item : element){
sum += item;
System.out.println(item);
}
average = sum / element.size();
for (int i = 0; i < element.size(); i++)
{
newnumber += Math.pow((element.get(i) - average),2);
}
deviation = Math.sqrt(newnumber / (element.size()));
System.out.println("The average of these grades is : " + fmt.format(average));
System.out.println("The standard deviation of these grades is: " + fmt.format(deviation));
}
}
}
----jGRASP exec: java gradeSorter
51
52
55
57
58
61
62
63
66
66
66
70
72
73
74
75
75
77
77
78
79
81
82
84
86
87
88
91
94
97
The average of these grades is : 73.233
The standard deviation of these grades is: 12.288
----jGRASP: operation complete.
First Issue:
Your for loop doesn't even run once, since element.size() is 0 initially, so the condition of loop will be false at the first iteration only:
for (int count = 0; count < element.size(); count++)
Just remove this loop. You don't need it. An ArrayList can grow dynamically. You don't need to bother about it's size.
Second Issue:
The for loop inside your while loop is doing the danger. It will accumulate the sum of all element, after adding each element. So, your sum won't be the sum of all elements of the list. It would be sum of the elements, added many times. You should move the inner for loop outside the while:
Third Issue:
You are using scanner.hasNext() and reading an int using scanner.nextInt(). You should only test for the element type, that you are reading. Use scanner.hasNextInt() to test for any available integer to read.
Well, there might be some more. But you should first solve these issues, and run the code to see what all parts did you got right.
In all, that part of your code should be modified to:
ArrayList<Integer> element = new ArrayList<Integer>();
// Remove the for loop from here
while (scanner.hasNextInt()) { // Use scanner.hasNextInt()
element.add(scanner.nextInt());
}
for (int item : element) { // Moved this for loop outside the while loop
sum += item;
}
System.out.println(sum);
Remove your for loop and things should run just fine. Just have this:
public static void main(String[] args) throws IOException {
{
....
....
while (scanner.hasNext())
{
number = scanner.nextInt();
element.add(number);
for (int item : element)
{
sum += number;
System.out.println(number);
}
}
average = sum / element.size();
....
....
....
Also details of error you got would be useful.

Categories

Resources