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.
Related
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]);
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;
}
}
I have taken array int[] a = {33,33,5,5,9,8,9,9}; In this array so many values are duplicates means 33 comes twice & 5 also comes twice & 9 comes three times.
But I want to count the first value which is duplicate means 33 is first value which comes twice so answer would be 2.
I try:
public class FindFirstDuplicate
{
public static void main(String[] args) {
int c=0;
int[] a = {33,33,5,5,9,8,9,9};
outerloop:
for(int i = 0; i < a.length; i++)
{
for(int j = i+1; j< a.length; j++)
{
if(a[i] == a[j])
{
System.out.println(a[i]); //Duplicate value
c++;
break outerloop;
}
}
}
System.out.print("Count: "+c);
}
}
Output:
33
1
public class HelloWorld{
public static void main(String[] args) {
int[] a = {33,33,5,5,9,8,9,9};
for(int i = 0; i < a.length; i++)
{
int c=1; // we already found one.
// and we initialize this counter inside the loop,
// so that it is reset for each new starting number.
for(int j = i+1; j< a.length; j++) // we're starting from next number (reason we start with c=1)
{
if(a[i] == a[j])
c++;
}
if(c > 0) {
System.out.println("First uplicate value: "+ a[i] + " Count: " + c);
break; // we have to break out of the outer loop,
// so the inner loop can finish counting duplicates
}
}
}
}
Try something like:
int[] numbers = {33, 33, 5, 5, 9, 8, 9, 9};
Set<Integer> set = new HashSet<Integer>();
for (int i = 0; i< numbers.length; i++) {
if (!set.add(number[i])) {
System.out.println("first duplicate is " + number[i] + " and index is " + i);
break;
}
}
If the values in the array are non-negative and reasonably small, you can use a BitSet to store whether or not you have seen a value previously:
BitSet bits = new BitSet();
for (int i = 0; i < numbers.length; ++i) {
if (bits.get(numbers[i])) {
System.out.println("first duplicate at " + i + ": " + numbers[i]);
break;
}
bits.set(numbers[i]);
}
You could try this out:
int[] a = {33,33,5,5,9,8,9,9};
Integer[] uniques = new Integer[a.length];
Integer[] counts = new Integer[a.length];
int len = 0;
for(int num : a){
boolean matched = false;
for(int i = 0; i < len; i++){
if(num == uniques[i].intValue()){
matched = true;
counts[i] = new Integer(counts[i]+1);
break;
}
}
if(!matched){
uniques[len] = new Integer(num);
counts[i] = new Integer(1);
len++;
}
}
for(int i = 0; i < len; i++){
if(counts[i].intValue() > 1){
System.out.println("first duplicate is " + uniques[i] + " and number of times it appears " + counts[i]);
break;
}
}
In your code you exit both loops after the first duplicate is found, so any other occurences of the element would be ignored.
Also you start with c = 0. When you get to the second occurence, c will be incremented and be 1, not 2.
To count all elements simply change the loop condition of the outer loop and remove the break:
int c = 1;
int i;
for(i = 0; (c == 1) && (i < a.length); i++)
{
for(int j = i+1; j < a.length; j++)
{
if(a[i] == a[j])
{
c++;
}
}
}
System.out.println(a[i]); //Duplicate value
System.out.print("Count: "+c); // maybe do something else, if c == 1 (no duplicates)???
However SMA's answer describes a more performant way (for arbitrary input arrays) of finding the first duplicate. Once you found the second occurence of the first duplicate, you'd only need to count the number of occurences in the rest of the array to get the final count.
I have an array called blockHeights, which contains 3 values inside of it, namely 1,2,3. So blockHeights[0] is equal to 1.
I also have a loop:
for (int i = 1; i <= blockHeights.length; i++)
In the first time around the loop, I want to create a variable called totalBlockHeights where it is
int totalBlockHeights = blockHeights[0] + blockHeights [1] + blockHeights [2];
However, in the next loop I want that variable to change, so that it only adds blockHeights[1] and blockHeights[2] together, ignoring blockHeights[0].
How would I go about doing this?
Try the following (I'm assuming the third iteration should only include blockHeights[2], following the pattern):
for (int i = 1; i <= blockHeights.length; i++) {
int totalBlockHeights;
for (int j = i - 1; j < blockHeights.length; j++) { // all block heights from here onwards
totalBlockHeights += blockHeights[j];
}
// do whatever
}
Well, if you want the sum of your array, and the sum of the array without first value
int totalBlockHeights = 0;
for(int i = 0; i < blockHeights.length; i++){
totalBlockHeights += blockHeights[i];
}
System.out.println(totalBlockHeights);
System.out.println("totalBlockHeights without first value = " + (totalBlockHeights - blockHeights[0]));
this way you only loop once
Try following code:
public class Loop {
public static void main(String[] argv) {
int[] blockHeights = new int[] {1, 2, 3};
int totalBlockHeights = 0;
for(int i = 0; i < blockHeights.length; i++) {
totalBlockHeights = 0;
for(int j = i; j < blockHeights.length; j++) {
totalBlockHeights += blockHeights[j];
}
System.out.println(totalBlockHeights);
}
}
}
int[] blockHeights = new int[] { 1, 2, 3 };
int totalBlockHeights = 0;
int customBlockHeights = 0;
for (int i = 0; i < blockHeights.length; i++) {
totalBlockHeights += blockHeights[i];
if (i == 0) {
continue;
}
customBlockHeights += blockHeights[i];
}
System.out.println(totalBlockHeights);
System.out.println(customBlockHeights);
This will print:
6
5
You dont need two for to achieve that.
you can perform this on two for loop outer loop for (int i = 1; i <= blockHeights.length; i++), and in inner loop (take a variable j) you can do like int totalBlockHeights = totalBlockHeights + blockHeights[j], and for i<j, you can just continue the for loop.
as answered by btrs20
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++;
}