Instantiating array but keep getting IndexOutOfBounds Exception - java

I'm trying to tally a count array to keep up with a set of 50 choices where there are three options for each choice. The count array should have 150 elements, per my instructor (3 x 50 = 150). But I keep getting an IndexOutofBounds Exception at line 55 (index = thisChoice.get(i)). I'm thinking that it must have something to do with how (or where?) I'm instantiating my count array at
line 50: int[] count = new int[students.get(0).getChoices().size()*3]
because the rest of the code came from my instructor and is presumably correct. Any ideas on what could be sending it out of bounds?
public class P1Driver {
public static void main(String[] args) throws IOException{
ArrayList<Students> students = new ArrayList<Students>();
ArrayList<String> choices = new ArrayList<String>();
Scanner scan1 = new Scanner(new File("Choices.txt"));
Scanner scan2 = new Scanner(new File("EitherOr.csv"));
// Scan the first file.
int choicesIndex = 0;
while(scan1.hasNextLine()){
String line = scan1.nextLine();
choices.add(line);
choicesIndex++;
}
scan1.close();
// Scan the second file.
int studentIndex = 0;
while(scan2.hasNextLine()){
String line = scan2.nextLine();
String [] splits = line.split(",");
students.add(new Students(splits[0]));
for(int i = 1; i < splits.length; i++){
students.get(studentIndex).addChoices(Integer.parseInt(splits[i]));
}
studentIndex++;
}
scan2.close();
// Instantiate and add to the count array.
int index, countIndex;
ArrayList<Integer> thisChoice;
int[] count = new int[students.get(0).getChoices().size()*3];
for(int i = 0; i < students.size(); i++){
countIndex = 1;
thisChoice = students.get(i).getChoices();
for(int j = 0; j < thisChoice.size(); j++){
index = thisChoice.get(i);
count[countIndex + index] = count[countIndex + index] + 1;
countIndex+=3;
}
}
// Display data.
countIndex = 1;
for(int i = 0; i < choices.size(); i+=2){
System.out.println(choices.get(i) + count[countIndex] + choices.get(i+1) + count[countIndex+1] + " Invalid: " + count[countIndex-1]);
countIndex+=3;
}

HI Please check second nested loop, it should be j instead of i .
also you haven't used int j in that loop.
for (int i = 0; i < students.size(); i++) {
countIndex = 1;
thisChoice = students.get(i).getChoices();
for (int j = 0; j < thisChoice.size(); j++) {
index = thisChoice.get(j);
count[countIndex + index] = count[countIndex + index] + 1;
countIndex += 3;
}
}

Related

3rd inner while loop not working

In the blow code the inner 3rd while loop not working please tell me why ?
Here I tried with for loop by replacing the 3rd inner while loop it is working correctly but why not working with while loop .....? can you give me genuine reason...?
import java.util.Scanner;
public class MergeArray {
void arrayInitialization(Scanner arg) {
//entering test cases
System.out.println("enter test cases");
int t = arg.nextInt();
int k, l, i;
k = 0;
l = 0;
i = 0;
//outer while loop
while (t-- > 0) {
//initializing a1[]'s size
System.out.println("enter a1[]'s size");
int as1 = arg.nextInt();
int a1[] = new int[as1];
//inner while loop-1
while (as1-- > 0) {
System.out.println("enter a1[]'s elements");
a1[i] = arg.nextInt();
System.out.print(a1[i]);
i++;
}
i = 0;
//initializing a2[]'s size
System.out.println("enter a2[]'s size");
int as2 = arg.nextInt();
int a2[] = new int[as2];
//inner while loop-2
while (as2-- > 0) {
System.out.println("enter a2[]'s elements");
a2[i] = arg.nextInt();
System.out.print(a2[i]);
i++;
}
System.out.println();
int a3[] = new int[a1.length + a2.length];
int size = as1 + as2;
//inner while loop-3
while (size-- > 0) {
if (k < a1.length)
a3[l] = a1[k];
if (k < a2.length)
a3[l + 1] = a2[k];
k++;
l += 2;
}
for (int j = 0; j < (a1.length + a2.length); j++) {
System.out.print(a3[j]);
}
}
}
public static void main(String[] args) {
MergeArray ma = new MergeArray();
Scanner sc = new Scanner(System. in );
ma.arrayInitialization(sc);
}
}
I tried so much but not found solution. Here I am using while loop because I know that while loop will work fast instead of for loop.
It does not work because you are decrementing the sizes of as1 and as2. Which will be
int size = as1 + as2; // size = 0 + 0;
Instead you can make use of the array length e.g.
int size = as1.length + as2.length;
Murat K's Answer is right, but try to init the arrays like this:
//init a1
System.out.println("enter a1[]'s size");
int a1[] = new int[arg.nextInt()];
//fill a1
for (int i = 0; i < a1.length; i++) {
System.out.println("enter element " + i + " of a1[]");
a1[i] = arg.nextInt();
}
//init a2
System.out.println("enter a2[]'s size");
int a2[] = new int[arg.nextInt()];
//fill a2
for (int i = 0; i < a2.length; i++) {
System.out.println("enter element " + i + " of a2[]");
a2[i] = arg.nextInt();
}
//init a3
int a3[] = new int[a1.length + a2.length];
//merge a1 and a2 into a3
for (int i = 0; i < a1.length; i++) {
a3[i] = a1[i];
}
for (int i = 0; i < a2.length; i++) {
a3[a1.length + i] = a2[i];
}
//print
for (int i : a3) {
System.out.print(i);
}

Matrix Multiplication Returing Array Index out of bound error

This is one first post here, Pardon me if my question doesn't meet required standards here.
I have written a piece of code which takes input for two matrix from two separate files and performs multiplication and output the data to a new file.
It gives perfect output for 2x3 or 3x3 matrix. If i give input of 4x4 matrix i get array index out of bound runtime exception. I don't understand the reason as i dynamically create index
I get an array index out of bound exception at line 40.
I get an error.
![Snipet][2]
List item
public class MM {
private BufferedReader br;
private int sum = 0;
private final static String matrixA="matrixA.txt";
private final static String matrixB="matrixB.txt";
public static void main(String[] args) {
new MM().MathMultiplicationValues(matrixA, matrixB);
}
private void MathMultiplicationValues(String mat1, String mat2) {
try {
br = new BufferedReader(new FileReader(mat1));
String line;
int mat1rows = 0, mat1cols = 0, mat2rows = 0, mat2cols = 0;
while ((line = br.readLine()) != null) {
mat1cols = line.split(" ").length + 1;
mat1rows++;
}
br.close(); // To close file
br = new BufferedReader(new FileReader(mat2)); // to read input from file.
while ((line = br.readLine()) != null) {
mat2cols = line.split(" ").length + 1;
mat2rows++;
}
int[][] mat1vals = new int[mat1rows ][mat1cols ];
int[][] mat2vals = new int[mat2rows ][mat2cols ];
br.close();
br = new BufferedReader(new FileReader(mat1));
for (int i = 1; i < mat1rows + 1; i++) {
line = br.readLine();
String[] colvals = line.split(" ");
for (int j = 1; j < mat1cols; j++) {
mat1vals[i][j] = Integer.parseInt(colvals[j - 1]);
}
}
br.close();
br = new BufferedReader(new FileReader(mat2));
for (int i = 1; i < mat2rows + 1; i++) {
line = br.readLine();
String[] colvals = line.split(" ");
for (int j = 1; j < mat2cols; j++) {
mat2vals[i][j] = Integer.parseInt(colvals[j - 1]);
}
}
br.close();
if ((mat1cols-1) == mat2rows) {
int[][] resltmat = new int[mat1rows + 1][mat2cols + 1];
for (int i = 1; i < mat1rows + 1; i++) { //Loop does matrix multiplication.
for (int j = 1; j < mat1cols; j++) {
for (int k = 0; k < mat2rows + 1; k++)
sum = sum + mat1vals[i][k] * mat2vals[k][j];
resltmat[i][j] = sum;
sum = 0;
}
}
final PrintWriter pw = new PrintWriter("Answer.txt"); //Creates a new file called Matrix Answer.
for (int i = 1; i < mat1rows + 1; i++)
{
for (int j = 1; j < mat2cols; j++) {
pw.print(resltmat[i][j] + " "); // Writes the output to file the file called MatrixAnswer
}
pw.println();
}
pw.close();
} else // If no of columns not equal to rows control passes to else block.
System.out.println("Multiplication of Matrix is not possible because columns are not equal to rows");
} catch (Exception e) {
e.printStackTrace();
}
}
}
Might be because of this
for (int i = 1; i < mat1rows + 1; i++) {
line = br.readLine();
String[] colvals = line.split(" ");
for (int j = 1; j < mat1cols; j++) {
mat1vals[i][j] = Integer.parseInt(colvals[j - 1]);
}
}
i = mat1rows on the last iteration which is OOB. Change for (int i = 1; i < mat1rows + 1; i++) to for (int i = 1; i < mat1rows; i++)
As you used in the allocation, the dimension of the resulting matrix are mat1rows x mat2cols. Thus in the computation of resltmat[i][j] the index i has bound mat1rows (check) and the index j has the upper bound mat2cols (fail). Thus change the range of j from mat1cols to mat2cols.

Array Index Out of Bounds Error in 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++;
}

Java Array Storing Values

I'm trying to store the values inputted on the for-loop structure that I will need for later use, but it can only be recognized inside the for loop structure. I need the stored values to be recognize for the rest of the program but somehow I'm getting an error "cannot find symbol"
public class TryArray {
public static void main(String args[]) throws IOException {
BufferedReader inpt = new BufferedReader(new InputStreamReader(System. in ));
int[] arrayCrit = new int[5];
String[] crits = new String[5];
for (int i = 0; i < crits.length; i++) {
System.out.print("Criteria: ");
crits[i] = inpt.readLine();
for (int j = 0; j < arrayCrit.length; j++) {
System.out.print("Percentage: ");
arrayCrit[j] = Integer.parseInt(inpt.readLine());
}
}
System.out.println(crits[i] + arrayCrit[j])
}
}
Edit: Yes, I can move the print output inside the for-loop, but I need to input all the values first before showing all of it. Please I need help.
Hope this will help.
public static void main(String args[]) throws IOException {
BufferedReader inpt = new BufferedReader(new InputStreamReader(
System.in));
int[] arrayCrit = new int[5];
String[] crits = new String[5];
for (int i = 0; i < crits.length; i++) {
System.out.print("Enter Criteria: ");
crits[i] = inpt.readLine();
System.out.print("Enter Percentage: ");
arrayCrit[i] = Integer.parseInt(inpt.readLine());
}
// Printing the values
for (int i = 0; i < crits.length; i++) {
System.out.println("Criteria :" + crits[i] + " Percentage: "
+ arrayCrit[i]);
}
}
to show all you have to make another loop to read, after the insertion
import java.io.*;
public class TryArray{
public static void main(String args[])throws IOException{
BufferedReader inpt = new BufferedReader (new InputStreamReader(System.in));
int [] arrayCrit = new int [5];
String [] crits = new String [5];
for(int i=0; i<crits.length; i++){
System.out.print("Criteria: ");
crits[i]=inpt.readLine();
for (int j=0; j<arrayCrit.length; j++){
System.out.print("Percentage: ");
arrayCrit[j]=Integer.parseInt(inpt.readLine());
}
}
for(int i=0; i<crits.length; i++){
for (int j=0; j<arrayCrit.length; j++){
System.out.println(crits[i] + arrayCrit[j])
}
}
}
}
or I misunderstood your question?
What you're currently doing will overwrite the values entered for the previous criteria when you get the input for the next. I believe you want to have a 2d array for arrayCrit to store all the percentages for each criteria. Only in such a scenario it makes sense to have 2 for loops.
String[] crits = new String[5];
int[][] arrayCrit = new int[5][5]; // The 2d array
for (int i = 0; i < crits.length; i++) {
System.out.print("Criteria: ");
crits[i] = inpt.readLine();
for (int j = 0; j < arrayCrit[i].length; j++) {
System.out.print("Percentage: ");
arrayCrit[i][j] = Integer.parseInt(inpt.readLine()); // Inputting different set of percentage for each criteria
}
}
// Displaying each criteria with its own percentages
for (int i = 0; i < crits.length; i++) {
System.out.print("For Criteria: " + crits[i]+" ---> ");
for (int j = 0; j < arrayCrit[i].length; j++) {
System.out.print("Percentage " + j + " : " + arrayCrit[i][j] + "\t");
}
System.out.println();
}
1) Add
import java.io.*;
2)You are using nested for loops
for(int i=0; i<crits.length; i++){ //this will execute 5 times
System.out.print("Criteria: ");
crits[i]=inpt.readLine();
for (int j=0; j<arrayCrit.length; j++){ //this will execute 5 times for each i = 25 times
System.out.print("Percentage: ");
arrayCrit[j]=Integer.parseInt(inpt.readLine());
}
}
Remove nested for-loop as
for(int i=0; i<crits.length; i++){ //this will execute 5 times
System.out.print("Criteria: ");
crits[i]=inpt.readLine();
}
for (int j=0; j<arrayCrit.length; j++){ //this will execute 5 times
System.out.print("Percentage: ");
arrayCrit[j]=Integer.parseInt(inpt.readLine());
}
3) can not find symbol
You want to print criteria and percentage at same time, as you have initialized both arrays with size 5, then you can directly print
for (int i = 0; i < 5; i++) {
System.out.println(crits[i] + arrayCrit[i]);
}
4)You can use following program which is enhanced version of your program
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class TestArray {
public static void main(String args[]) throws IOException {
BufferedReader
inpt = new BufferedReader(new InputStreamReader(System. in ));
System.out.println("How many records?");//ask for how many records
int n = Integer.parseInt(inpt.readLine());// store in n
int[] arrayCrit = new int[n];//create array with size n
String[] crits = new String[n];
//**as you mentioned in edit you want to take all the input before printing**
for (int i = 0; i < n; i++)
{
System.out.print("Criteria: ");
crits[i] = inpt.readLine();
System.out.print("Percentage: ");
arrayCrit[i] = Integer.parseInt(inpt.readLine());
}
//print both arrays
System.out.println("Criteria \t Percentage");
for (int i = 0; i < n; i++)
{
System.out.println(crits[i] + "\t"+arrayCrit[i]);
}
}
}
Useful link
Nested for
You have to define i and j outside the loop. Otherwise, you can only use them inside the loop:
int i;
int j;
int[] arrayCrit = new int[5];
String[] crits = new String[5];
for (i = 0; i < crits.length; i++) {
System.out.print("Criteria: ");
crits[i] = inpt.readLine();
for (j = 0; j < arrayCrit.length; j++) {
System.out.print("Percentage: ");
arrayCrit[j] = Integer.parseInt(inpt.readLine());
}
}

If statements in 2D arrays

When I am trying to run this code it shows java.lang.ArrayIndexOutOfBoundsException Error. Please help me to fix this code.
import java.util.*;
class Example {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
Random r = new Random();
final int N, S;
System.out.print("Input No of Students : ");
N = input.nextInt();
System.out.print("No of Subject : ");
S = input.nextInt();
int[][] st = new int[N][S];
int[] stNo = new int[N];
int[] stMax = new int[N];
for (int i = 0; i < N; i++) {
stNo[i] = r.nextInt(10000);
for (int j = 0; j < S; j++) {
st[i][j] = r.nextInt(101);
}
}
// Find max Value of marks of a Student
for (int i = 0; i < N; i++) {
for (int j = 0; j < S; j++) {
if (st[i][j] > st[i][j + 1]) {
stMax[i] = st[i][j + 1];
}
}
}
// Display marks
// Dispaly Column names
System.out.print("stNo\t");
for (int i = 1; i < S + 1; i++) {
System.out.print("Sub " + i + "\t");
}
System.out.print("Max");
// Print Values
for (int i = 0; i < N; i++) {
System.out.print(stNo[i] + "\t");
for (int j = 0; j < S; j++) {
System.out.print(st[i][j] + "\t");
}
System.out.print(stMax[i]);
System.out.println();
}
}
}
The error is
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: (here shows the input for "S")
at pack1.Example.main(Example.java:31)
As I am a new to coding I can not fix this. Please help me to fix this.
Thanks
An ArrayIndexOutOfBoundsException error means you exceed the boundaries of the array. In your case, st has S colomns and you tried to reach the S+1-th element (index S).
st[i][j + 1] => when j == S-1 (the end of the loop), you do an out of bounds.
Now, as your comment say, you're looking for the max value. Then the code should be:
stMax[i] = 0;
for (int j = 0; j < S; j++) {
if (st[i][j] > stMax[i]) {
stMax[i] = st[i][j];
}
}
What your code is doing is comparing the current value to the next one. And every time the next value is greater than the current one, you update stMax[i]. This does not make sense.
This line is causing the exception:
stMax[i] = st[i][j + 1];
You are iterating j to the end of the array, and always looking for the next element. So when j reaches the end of the array it is still looking for one more index, hence the outOfBoundsException.

Categories