Getting ArrayIndexOutOfBoundsException exception at runtime [closed] - java

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
My code compiles, but I get this error at runtime:
Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 5
at staffstore.writestaff(staffstore.java:16)
at addStaffGUI$2.actionPerformed(addStaffGUI.java:89)
This is the part of code I believe to be causing the problem:
JButton submit = new JButton("Submit");
submit.setBounds(145,470,100,20);
panel2.add(submit);
submit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
stfname =(stfnametb.getText());
stlname =(stlnametb.getText());
staddress2 =(staddresstb.getText());
stphone2 =(stphonetb.getText());
try {
staffstore.writestaff();
} catch (IOException e1) {
e1.printStackTrace();
}
third.dispose();
}
});
This is line 9-19 of StaffStore.java
String[] stlist = new String[5];
/*stlist[0] = addStudentGUI.fname;
stlist[1] = addStudentGUI.lname;
stlist[2] = addStudentGUI.sgrade;
stlist[3] = addStudentGUI.saddress;
stlist[4] = addStudentGUI.sphone;*/
stlist[5] = addStaffGUI.stfname;
stlist[6] = addStaffGUI.stlname;
stlist[7] = addStaffGUI.staddress2;
stlist[8] = addStaffGUI.stphone2;

An array of size n can only have an index position up to size n-1. The highest such index for an array of size 5 is 4.
That said, these four declarations are illegal:
stlist[5] = addStaffGUI.stfname;
stlist[6] = addStaffGUI.stlname;
stlist[7] = addStaffGUI.staddress2;
stlist[8] = addStaffGUI.stphone2;
I'm not entirely sure what your motiviation is here, but you need to get those four values in bounds.
stlist[0] = addStaffGUI.stfname;
stlist[1] = addStaffGUI.stlname;
stlist[2] = addStaffGUI.staddress2;
stlist[3] = addStaffGUI.stphone2;
Since you've also got other values commented out, it could be a simple matter of increasing the size of your array, too:
String[] stlist = new String[9];
...but then you have to be sure that you don't try to invoke any methods on any of the first five entries in the array.

You've got an array that holds 5 items and you're trying to get the value in the 6th spot. Don't do that.
String[] stlist = new String[5];
stlist[5] = addStaffGUI.stfname;
Also you're trying to hold different information in a single array, something that is a poor and brittle design. Instead create an array or better, an ArrayList of Staff items.
// declared as a field of the class:
private List<Staff> staffList = new ArrayList<>();
// elsewhere
submit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String stfname = stfnametb.getText();
String stlname = stlnametb.getText();
String staddress2 = staddresstb.getText();
String stphone2 = stphonetb.getText();
// use information obtained to create a Staff object
Staff staff = new Staff(stfname, stlname, staddress2, stphone2);
// maybe done here, maybe in staffStore
staffList.add(staff);
try {
// pass the Staff object into this method
staffstore.writestaff(staff);
} catch (IOException e1) {
e1.printStackTrace();
}
third.dispose();
}
});
The most important lessons to gain from this experience are:
Just because code compiles does not mean that it is correct.
The Exception stacktrace often contains key information that will tell you exactly what is wrong and where. Read it critically and look carefully at the lines it indicates to you.

Related

this code of mine has no error but it isnt showing any output [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
In this code the method setEid isn't working dont know what's the problem with while loop
this code of mine has no error but it isnt showing any output
public class Emp {
private String eid;
public String getEid() {
return eid;
}
public void setEid(String e) {
while (e.length() < 12) {
eid = e;
}
}
}
public class Test {
public static void main(String[] args) {
Emp z = new Emp();
z.setEid("rgrge");
System.out.println("\n" + z.getEid());
}
}
enter code here i expect the static initialization of setEid argument should not take more than 12 characters
Your setter method have a while loop if eid length is less than 12 then it always stuck in this method.
public void setEid(String e){
while(e.length()<12)
eid=e;
}
and In your main method
public static void main(String[] args) {
Emp z=new Emp();
z.setEid("rgrge"); // you call setter
System.out.println("\n"+z.getEid());
}
you pass "rgrge" in setter and its length is less than 12. Tht's why your program is stuck in loop and not showing any thing.
Change setter implementation to this.
public void setEid(String e){
if(e.length()<12) // change while to if
eid=e;
}
so first there should have had if instead of while.
Change:
while(e.length()<12) change this as if(e.length()<12)
Explanation:
your setEid method never going to run because there is no break condition there. your while loop condition tends to the infinite. your code gets stuck in that while loop.
here you passed z.setEid("rgrge");. in your example, Length of string e is 5 which is obviously less than 12, so the condition will always be satisfied and your program will be stuck in infinite loop.

Array does not show up when called? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
In my code I created a class called Inventory to store my information in an array. I created a method to add strings, and a method to display all the information stored in the array. Something went wrong along the way for my code will execute, but it will not show any of the information that I stored in the array, just a blank command window. Here is the man class.
public class Game {
public static void main(String[] args) {
Inventory playersInventory = new Inventory();
playersInventory.addInventory("Knife");
playersInventory.addInventory("Food");
playersInventory.addInventory("Water");
playersInventory.displayInventory();
}
}
and here is the Inventory class
public class Inventory {
private String[] inventoryItem = new String[10];
public void addInventory(String item){
int x = 0;
while (true) {
if (inventoryItem[x]== null){
item = inventoryItem[x];
break;
}
else {
x++;
}
}
}
public void displayInventory(){
int x = 0;
while (true){
if (inventoryItem[x] == null){
break;
}
else{
System.out.println(inventoryItem[x] + "\n");
x++;
}
}
}
}
The problem lies in this line:
item = inventoryItem[x];
The = evaluate the expression on the right and assigns the result to the variable on the left. So what you're doing there is assigning inventoryItem[x] to item.
In other words, you are not mutating the array, but assigning a new value to the parameter, which does practically nothing.
I guess you want to add the parameter into the array. So your assignment statement should be the other way around:
inventoryItem[x] = item;
Actually, to avoid confusion, just use an ArrayList!
public class Inventory {
private ArrayList<String> inventoryItem = new ArrayList<>();
public void addInventory(String item){
inventoryItem.add(item);
}
public void displayInventory(){
for (Sting item: inventoryItem) {
if (item != null) {
System.out.println(item + "\n");
}
}
}
}
Isn't that much cleaner?
Your line of code
item = inventoryItem[x];
should be
inventoryItem[x] = item;
You are assigning inventoryItem[x]; to item where as you need the reverse.
Assign value inventoryItem[x] = item;
You did not put the item in the array "inventoryItem", Hence no information was displayed.
Change your code to following to populate the array
if (inventoryItem[x]== null){
inventoryItem[x]=item ;
break;
}

Receiving parameter for an array of objects from another class in Java? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I am trying to create one array of objects of my class Percurso for another class Custos, but I don't know how to do this. Here is what is asking in the question:
Receives as parameter an array of path-type objects
My code :
Class Custos :
public class Custos {
public String calcularViagem(Percurso [] p) {
return "";
}
}
Class Percurso :
private double kmPercorrida;
private double valorCombustivel;
private double valorPedagio;
public double getKmPercorrida() {
return kmPercorrida;
}
public void setKmPercorrida(double kmPercorrida) {
this.kmPercorrida = kmPercorrida;
}
public double getValorCombustivel() {
return valorCombustivel;
}
public void setValorCombustivel(double valorCombustivel) {
this.valorCombustivel = valorCombustivel;
}
public double getValorPedagio() {
return valorPedagio;
}
public void setValorPedagio(double valorPedagio) {
this.valorPedagio = valorPedagio;
}
public Percurso() {
this(0,0,0);
}
public Percurso(double kmPercorrida, double valorCombustivel,
double valorPedagio) {
this.kmPercorrida = kmPercorrida;
this.valorCombustivel = valorCombustivel;
this.valorPedagio = valorPedagio;
}
How can I do this ? If someone can help, I will thanks.
PS: Before someone say that this post is similar to other questions about array, it's not,I looked for questions similar that could help and I didn't found any that really could help me.
Creating an array of Percurso objects is the same as creating an array of any object. To create the array, you will need to include a line like this:
Percurso[] percursoArray = new Percurso[LENGTH]; //with your own array name and length
However, that just creates an array; it doesn't put anything in it. To put Percurso objects in the array (or, more accurately references to the objects), you need code like this.
percusoArray[0] = new Percurso(5, 2, 1);
percusoArray[1] = new Percurso(1, 1, 1); //etc
Or, if the array is long, you could create the objects in a for loop:
for (int i = 0; i < LENGTH; i++){
percusoArray[i] = new Percurso(1,2,3); //with your own values
}
Of course, a question remains-- where should you put this code? Is the array of Percurso an attribute of Custos? If so, you might create the array as a class variable of Custos and populate it in the constructor for Custos. If it's not an attribute of Custos, but rather just a parameter for one of Custos methods, you'll need this code in whichever part of your code calls calcularViagem(), whether that is another method in Custos, a method in another class, or from inside your main method.

Why am i getting NoSuchElementException error in my class [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
I have this class who is supposed open a file with a nr of questions in it with a nr of answer.
The problem is when it get's in that for to write in the ArrayList. I have tried all type of ArrayLists,LinkedLists, even vectors.
The first parts of the file, like the question and nr of answer, it takes it without any problem. But when i want to store those answers in a list so i can save that list in an object it won't work.
If anyone could help with this or knows a better method so save an unknown nr of string into an object list it would be epic.
The file format is:
A question,3,yes,no,maybe
Another question,4,yes,maybe,no,why not
my class:
public class GetSurvey {
public static String intrebare;
static int raspunsuri;
public static int i = 1;
static String holder;
//static String[] rasp = new String[250];
static List<String> rasp = new LinkedList<String>();
public static SurveyClass[] obj = new SurveyClass[250];
public static void loadSurvey()
{
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)+File.separator+"Survey.dat");
if(!file.exists()){
try {
file.createNewFile();
}
catch (IOException e) {
e.printStackTrace();
}
}
if(file.exists()){
try {
Scanner read = new Scanner(file);
read.useDelimiter(",");
while (read.hasNext())
{
intrebare = read.next();
String raspunsuri1 = read.next();
//Log.w("Date",String.valueOf(raspunsuri));
//obj[i].setNrRasp(raspunsuri);
for(int j = 0;j < 3;j++)
{
Log.w("Date",String.valueOf(j));
rasp.add(j,read.next());
}
String[] stringArr = rasp.toArray(new String[rasp.size()]);
Log.w("Date",stringArr[i]);
//obj[i].setRaspunsuri(rasp);
rasp.clear();
i++;
}
}
catch (IOException e) {
e.printStackTrace();
}
}
}
You're using read.next() 3 times inside your loop, so that means that you get past the end of the input, hence NoSuchElementException.
Use it only once and assign it to a local variable inside the loop, so you can use that value whenever you need it again later in the loop.
I'd suggest you should perform only one read.next() inside your while(read.hasNext()) Loop . Analyse the read element, perform the neccessary task and rerun the loop until while(read.hasNext()) fails. This way you can be sure you'll never perform a read beyond the size of your List.

how can we compare two list? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 9 years ago.
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
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Improve this question
I have 2 lists of classes namely StuPersonal of Database1,StuPersonal of Database2 of different size.
public List<StuPersonal> stpers(){
int size=0;
Session s=getmSession();
Transaction tx=s.beginTransaction();
List<StuPersonal> splM=new ArrayList();
Query q=s.createQuery("from StuPersonal");
splM=q.list();
tx.commit();
s.close();
return splM;
}
public List<StuPersonal> stpersl(){
int size=0;
List<StuPersonal> splL=new ArrayList();
Session s=getlSession();
Transaction tx=s.beginTransaction();
List<StuPersonal> spl=new ArrayList();
Query q=s.createQuery("from StuPersonal");
splL=q.list();
tx.commit();
s.close();
return splL;
}
Now i have to compare both the lists and need to take the items which are not in the presented in the second list.i.e some objects are not in the class 2 list so it needs to be stored. I have written this code which is not working properly. Please advice.
for(StuPersonal cl:sp)
{
for(StuPersonal cl2:sp2)
{
if(cl.getid().equals(cl2.getid()))
{
//i++;
break;
}
else
{
fun.updatelist(cl.getid());
break;
}
}
}
You are Checking the ID of List object not the Class_1 Object Id
if(cl.getid() == cl2.getid())
{
//i++;
break;
} else
{
fun.updatelist(cl2.getid());
break;
}
And you are using equals method, considering id as long not String.
You're not helping yourself by choosing awful names for your variables and methods, not respecting the standard naming conventions, and not correctly indenting your code.
Anyway, you should try to write short methods that do one thing only, and that represent the steps in your task. Your task is to produce a list of objects that are present in list1 but are not in present in list 2. And "being present" here means "an object with the same ID exists in the list".
So start by writing a method isPresent():
/**
* Returns true if an object with the same ID as the ID of the given object is
* present in the given list
*/
private boolean isPresent(StuPersonal object, List<StuPersonal> list) {
for (StuPersonal candidate : list) {
if (candidate.getId().equals(object.getId()) {
return true;
}
}
return false;
}
Now you can use this method in your algorithm:
// start with an empty list
List<StuPersonal result = new ArrayList<>();
// add every element of list1 unless it's present in list2
for (StuPersonal s : list1) {
if (!isPresent(s, list2)) {
result.add(s);
}
}
Here is an example with String for your scenario.
List<String> firstList = Arrays.asList("obj1", "obj2", "obj3");
List<String> secondList = Arrays.asList("obj1", "obj2", "obj3", "obj4", "obj5");
List<String> storedList = new ArrayList<String>();
for (String obj2 : secondList) {
if (!firstList.contains(obj2)) {
storedList.add(obj2);
}
}

Categories