I am getting java.lang.ArrayIndexOutOfBoundsException error - java

I am getting java.lang.ArrayIndexOutOfBoundsException error.
public class Trainee implements EvaluationDetails
{
private int traineeId;
private String traineeName;
private double traineeMarks[];
public Trainee(int id,String name,double Marks[])
{
traineeId=id;
traineeName=name;
traineeMarks=Marks;
}
public int getTraineeId()
{
return traineeId;
}
public String getTraineeName()
{
return traineeName;
}
public boolean validateTraineeMarks()
{
if(noOfCourses>0 && noOfCourses<8)
{
for(int i=0;i<=traineeMarks.length;i++)
{
if(traineeMarks[i]>0 && traineeMarks[i]<100)
continue;
else
return false;
}
return true;
}
else
return false;
}
public double calculateGPA()
{
int GPA;
int Cp[]=new int[7];
boolean bool=validateTraineeMarks();
if(bool==true)
{
for(int i=0;i<traineeMarks.length;i++)
{
if(traineeMarks[i]>=85 && traineeMarks[i]<=100)
Cp[i] = 5;
else if(traineeMarks[i]>=65 && traineeMarks[i]<85)
Cp[i] = 4;
else if(traineeMarks[i]>=0 && traineeMarks[i]<=65)
Cp[i] = 3;
}
GPA = //GPA calculation logic
}
else
{
System.out.println("Improper values for trainee marks");
return 0.0;
}
return GPA;
}
}
The main class is as shown below:
public class Demo {
public static void main(String[] args)
{
double marks[]={74.0,57.0,86.0,93.0,56.0,73.5,83.0};
Trainee t = new Trainee(102,"Dixon",marks);
System.out.println("Trainee Id:"+t.getTraineeId());
System.out.println("Trainee Name:"+t.getTraineeName());
System.out.println("GPA is"+t.calculateGPA());
}
}
The interface is coded as below:
public interface EvaluationDetails
{
int creditpoints[]={3,3,4,4,2,3,5};
int noOfCourses=7;
public double calculateGPA();
}

for(int i=0;i<=traineeMarks.length;i++) should be for(int i=0;i<traineeMarks.length;i++)
the problem is you are trying to access array.length + 1 elemnt

Your mistake is here:
for(int i=0;i<=traineeMarks.length;i++)
Indexes in java (and all c-like languages) start from 0 and therefore the last index of array is length-1. So, fix your loop definition as following:
for(int i=0;i<traineeMarks.length;i++)

Here is your mistake:
for(int i=0;i<=traineeMarks.length;i++)
you should go from i=0 to traineeMarks.length-1 so,
for(int i=0;i<traineeMarks.length;i++)

for(int i=0;i<=traineeMarks.length;i++)
should be
for(int i=0;i< traineeMarks.length;i++)

for(int i=0;i<=traineeMarks.length;i++) //this is wrong this cause to java.lang.ArrayIndexOutOfBoundsException
use
for(int i=0;i<traineeMarks.length;i++)

Related

Java - Count the occurences of the elements of array A in array B

Assuming that B[] is longer than A[], I'm trying to figure out a way to count the number of times all the elements of A[] occurs in B[].
So say a[]{A,B} & B[A,B,C,A,C,A,B,B,A,B]
It would return 3
Here's a generic method that counts occurrences of one array within the other:
public static <T> int countOccurrences(T[] hayStack, T[] needle) {
int foundCount = 0;
for (int i = 0; i <= hayStack.length - needle.length; i++) {
boolean found = true;
for (int j = 0; j < needle.length; j++) {
if (!Objects.equals(hayStack[i + j], needle[j])) {
found = false;
break;
}
}
if (found) {
foundCount++;
}
}
return foundCount;
}
And here's a test class to go with it:
public class ArrayzTest {
#Test
public void countOccurrences_whenNeedleEmpty_returnsHaystackLength(){
assertThat(Arrayz.countOccurrences(hayStack(), emptyArray()), is(hayStack().length));
}
#Test
public void countOccurrences_whenHaystackEmpty_returnsZero(){
assertThat(Arrayz.countOccurrences(emptyArray(), hayStack()), is(0));
}
#Test
public void countOccurrences_whenHaystackHasNeedles_countsOccurrences(){
assertThat(Arrayz.countOccurrences(hayStack(), needle()), is(3));
}
private Integer[] needle() {
return new Integer[]{1,2,3};
}
private Integer[] hayStack() {
return new Integer[]{1,2,3,1,2,3,1,2,3};
}
private Integer[] emptyArray() {
return new Integer[0];
}
}

Why the program is not showing any output?

I have been trying to troubleshoot this java program from hours now and has not been able to find what is wrong with the execution. I think that the main class is not defined correctly.
It compiles successfully but the output is blank which should not be the case right? I intially tried to call the main class using the objects but still no luck. Any suggestions will work.
The original program:It compiles successfully on adding the main method but the output is blank.
import java.lang.Math; // headers MUST be above the first class
// one class needs to have a main() method
public class OrdSetSimple
{
// arguments are passed using the text field below this editor
public static void main(String[] args){
OrdSetSimple obj = new OrdSetSimple(10);
System.out.print("Success");
}
private int _set_size;
private int _set[];
private int _last;
public OrdSetSimple(int size) {
int k;
_set_size=size;
_set = new int[_set_size];
for(k=0; k<_set_size; k++)
_set[k]=0;
_last=-1;
}
private int make_a_free_slot(int val) {
int pos, i, j;
pos = binSearch(val);
if (pos >= 0)
return -1;
for (i=0; i<=_last; i++) {
if (_set[i] > val)
break;
}
if ((i<=_last)||(_last==-1)) {
for (j=_last; j>=i; j--)
_set[j+1] = _set[j];
pos = i;
} else {
pos = _last+1;
}
_last++;
return pos;
}
public void addElement(int n) {
int pos;
if (n<0) {
System.out.println("Addition of a negative integer impossible\n");
return;
}
if (_last+1>=_set_size) {
System.out.print("Addition of " + n);
System.out.println(" impossible since the array is already full");
System.out.println("The array is: " + toString());
} else {
pos = make_a_free_slot(n);
if (pos>=0)
_set[pos]=n;
}
return;
}
public int getSize() {
return _last+1;
}
public int getElementAt(int i) {
if ((i<0)||(i>_last))
return -1;
else
return _set[i];
}
private int binSearch(int x) {
int i=0;
int j=_last-1;
int m=0;
if (_last==-1)
return -1;
while(i<j) {
m= (i+j)/2;
if (x>_set[m])
i=m+1;
else
j=m;
}
if (x == _set[i]) return i;
else return -1;
}
public OrdSetSimple difference(OrdSetSimple s2) {
OrdSetSimple s1 = this;
int size1=s1.getSize();
int size2=s2.getSize();
OrdSetSimple set=new OrdSetSimple(size2);
int k;
for(k=0; k<size1; k++)
if (s2.binSearch(s1.getElementAt(k)) < 0)
set.addElement(s1.getElementAt(k));
return set;
}
public String toString() {
int k = 0;
String s="";
for (k=0; k<=_last; k++)
s += _set[k] + " ";
return s;
}
}
Your very first statement is wrong.
OrdSetSimple obj = new OrdSetSimple();//This will call the default constructor which will not initialize anything. This constructor will be added to your program by compiler, hence you don't get any compilation error.
Correct it like
OrdSetSimple obj = new OrdSetSimple(100);

Create all Combinations Java

I want to create all combinations with two states(1 and 0).
If i do this with two for-loops, this works. But when I use a self-calling function it doesnt. Does anybody can tell me why, please ?
For-Loops :
public class Counter {
public Counter() {
loop(iter);
for (int i=0; i < 2; i++) {
for (int i2=0; i2 < 2; i2++) {
System.out.println(Integer.toString(i)+Integer.toString(i2));
}
}
}
public static void main(String args[]){
new Counter();
}
}
Self-Calling Function :
class Stringhelper {
public Stringhelper() {
}
public String getstring(String string,int beginning,int ending) {
if (string.length() != 0) {
String newstring="";
for (int iter=Math.abs(beginning); iter < ending && iter < string.length(); iter=iter+1) {
newstring=newstring+Character.toString(string.charAt(iter));
}
return newstring;
}
else {
return "";
}
}
}
public class Counter {
public String abil="";
public int iter=1;
public Stringhelper shelper=new Stringhelper();
public void loop(int iter) {
for (int i=0; i < 2; i++) {
abil=abil+Integer.toString(i);
if (iter==0) {
System.out.println(abil);
abil=shelper.getstring(abil,0,abil.length()-1);
}
else {
loop(iter-1);
}
}
}
public Counter() {
loop(iter);
}
public static void main(String args[]){
new Counter();
}
}
And using the self-calling Function the output is 00,01,010,011 instead of 00,01,10,11
Explaining your code here (ignore abil for now):
public void loop(int iter) {
for (int i=0; i < 2; i++) {
abil=abil+Integer.toString(i);
if (iter==0) {
System.out.println(abil);
abil=shelper.getstring(abil,0,abil.length()-1);
}
else {
loop(iter-1);
}
}
}
When iter is 0 it will print it
In the next iteration, when it is not equal to 0, another loop is created, added to the stack, where it starts again from 0, and prints abil's new stack value.
When you create a new stack it recreates all the variables in temporary storage until the code exits. In this case it keeps creating stacks and never exits. In order to exit a stack, use return.
In summary, you need to learn more about how stacks and recursion work in order to fix your problem.
public void loop(int iter) {
for (int i=0; i < 2; i++) {
if (i==1) {
abil=shelper.getstring(abil,0,iter);
}
abil=abil+Integer.toString(i);
if (iter==4) {
System.out.println(abil);
}
else {
loop(iter+1);
}
}
}
this did the trick

Creating a new array element copies to the array index below it [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 8 years ago.
Improve this question
When I create a new array element, it gets stored into the array index, then the array index increments to the next.
However, I am getting a different result. The array element copies down to all previous array indexes.
import java.util.Scanner;
import java.io.*;
public class VectorOfContacts implements ProjTwo
{
private int size;
private int capacity;
private int incrementCapacity;
Contact[] contacts;
File file = new File("contacts.txt");
Scanner input = new Scanner(System.in);
public VectorOfContacts()
{
size = 0;
capacity = 10;
incrementCapacity = capacity;
contacts = new Contact[capacity];
}
public int getSize()
{
return size;
}
public int getCapacity()
{
return capacity;
}
public void setSize()
{
this.size = size;
}
public void setCapacity()
{
this.capacity = capacity;
}
//public VectorOfContacts(int inCapacity)
//{
//inCapacity = 100;
//incrementCapacity = inCapacity;
//}
public void readInitialFromFile()
{
Contact c = new Contact();
String temp = null;
try{
Scanner input = new Scanner(file);
for (int i = 0 ; i < size; i++)
{
temp = input.nextLine();
String[] part = input.nextLine().split(":");
System.out.println(part);
String name = part[0];
long number = Long.parseLong(part[1]);
String comment = part[2];
c.setName(name);
c.setPhoneNumber(number);
c.setComment(comment);
contacts[i] = c;
contacts[size] = contacts[i];
}
input.close();
}catch(FileNotFoundException e){
System.out.println("File not found.");
System.exit(0);
}
}
public void writeFinalToFile()
{
try{
PrintWriter output = new PrintWriter(file);
for (int i = 0; i < size; i++)
{
output.println(contacts[i]);
}
output.close();
}catch(FileNotFoundException a){
System.out.println("Something is wrong.");
System.exit(0);
}
System.exit(0);
}
public void addContact(Contact c)
{
addElement(c);
}
public void deleteContact(String nm)
{
System.out.println("Delete which name?");
nm = input.nextLine();
for(int i = 0; i < size; i++)
{
if(contacts[i].getName() == nm);
{
contacts[i] = contacts[i+1];
}
}
System.out.println("Deletion confirmed");
}
public void showByName(String nm)
{
nm = input.nextLine();
for ( int i = 0; i < size; i++)
{
if (nm.startsWith(contacts[i].getName()))
{
System.out.println(contacts[i]);
}
}
}
public void showByPhoneNumber(long pN)
{
pN = input.nextLong();
for ( int i = 0; i < size; i++)
{
if (contacts[i].getPhoneNumber() == pN)
{
System.out.println(contacts[i]);
}
}
}
public void showByComment(String c)
{
c = input.nextLine();
for ( int i = 0; i < size; i++)
{
if (c.startsWith(contacts[i].getComment()))
{
System.out.println(contacts[i]);
}
}
}
public boolean isFull()
{
if (size == capacity)
{
return true;
}
else
{
return false;
}
}
public boolean isEmpty()
{
if (size == 0)
return true;
else
return false;
}
public void addElement(Contact item)
{
if (isFull() == true)
incrementCapacity();
contacts[size] = item;
size++;
System.out.println("size" + size);
for (int i = 0; i < size; i++)
{
System.out.println(contacts[i]);
}
}
public void incrementCapacity()
{
Contact[] temp_contacts = new Contact[capacity + incrementCapacity];
for(int i = 0; i < size; i++)
{
temp_contacts[i] = contacts[i];
}
capacity = capacity + incrementCapacity;
contacts = temp_contacts;
}
}
These are the end results
size1
test:1234:1
size2
no:5555:2
no:5555:2
size3
jaja:1666:test
jaja:1666:test
jaja:1666:test
You print one object for all indexes, you need to use next:
for (int i = 0; i < size; i++){
System.out.println(contacts[i]);
}
You could improve a lof of things.
Don't expose everything as public
The class VectorOfContacts does a lot of things. You should split it into many classes.
Use the Java Framework (Array.copy(), ArrayList, ...)
Don't do if (true) return true else return false
Write tests
In readInitialFromFile you're creating the contact outside of the loop. So you reusing the same object of all contacts.
Those setters dont do anything, you missing an argument. But they shouldn't be public anyway so you don't need them.
public void setSize()
{
this.size = size;
}
public void setCapacity()
{
this.capacity = capacity;
}
isFull and isEmpty shouldn't be public and can be a lot shorter
private boolean isFull() {
return size == capacity;
}
private boolean isEmpty() {
return size == 0;
}
Please clean up your code first.

Returning the index number of an Arraylist in Java

I would like my method public void showClassRoomDetails(String teacherName) to return the Arraylist index number using the teacherName.
Thanks
import java.util.ArrayList;
public class School
{
private ArrayList<Classroom> classrooms;
private String classRoomName;
private String teacherName;
public School()
{
classrooms = new ArrayList<Classroom>();
}
public void addClassRoom(Classroom newClassRoom, String theClassRoomName)
{
classrooms.add(newClassRoom);
classRoomName = theClassRoomName;
}
public void addTeacherToClassRoom(int classroomId, String TeacherName)
{
if (classroomId < classrooms.size() ) {
classrooms.get(classroomId).setTeacherName(TeacherName);
}
}
public void showClassRoomDetails(String teacherName)
{
for (Classroom classroom : this.classrooms)
{
if (classroom.returnTeacherName().equals(teacherName))
{
System.out.println(classroom.returnClassRoomName());
System.out.println(classroom.returnTeacherName());
break;
}
}
}
}
Use a regular loop, not the foreach loop:
public int showClassRoomDetails(String teacherName)
{
for (int i = 0; i < this.classrooms.size(); i++)
{
Classroom classroom = classrooms.get(i);
if (classroom.returnTeacherName().equals(teacherName))
{
return i;
}
}
// Return -1 when the teacher was not found
return -1;
}
Either use a regular for loop (for (int i=0;i<classrooms.size();i++)) or use ArrayList.indexOf(classroom).
Something like this?
for (int i = 0; i < classrooms.size(); i++) {
Classroom classroom = classrooms.get(i);
if (classroom.returnTeacherName().equals(teacherName)) {
System.out.println("Index: " + i);
}
}
Much more elegantly,
public int showClassRoomDetails(String teacherName) {
for (int i = 0; i < classrooms.size(); i++) {
Classroom classroom = classrooms.get(i);
if (classroom.returnTeacherName().equals(teacherName)) {
return i;
}
}
return -1;
}
Alternatively, keep a counter that gets incremented for each not true condition (on your if statement).
//Return set containing multiple matched indexes
public Set<Integer> showClassRoomDetails(String teacherName){
Set<Integer> result = new HashSet<Integer>();
int i=0;
for (Classroom classroom : this.classrooms){
if (classroom.returnTeacherName().equals(teacherName))
result.add(i);
i++;
}
return result;
}

Categories