Why is Java giving my ArrayList an IndexOutOfBoundsException? [duplicate] - java

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 2 years ago.
Why is Java giving me an error message?
Im using JavaSE-12 and don't understand why I have an IndexOutOfBoundsException.
Do I have to specify the index of the ArrayList or what am I missing?
import java.util.ArrayList;
public class DSArrayList {
public static void main(String[] args) {
// TODO Auto-generated method stub
ArrayList<String> namensListe = new ArrayList<String>();
namensListe.add("Hans");
namensListe.add("Peter");
for(int i = 0; i <= namensListe.size(); i++) {
System.out.println("Name: " + namensListe.get(i));
}
}
}

for(int i = 0; i < namensListe.size(); i++)
(note the < operator)
To explain, arrays and like structures are indexed from zero, not one. Obviously we count, however, from one, not zero. So the length of an array is always one greater than the index of the last item it contains.

Related

My array gives me a list of random letters, symbols and numbers [duplicate]

This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
Closed 5 years ago.
I am trying to create a program that takes a array of 7 random numbers from 1-10 and puts them in a array and prints it,but whenever I run it I get this same result [I#6d06d69c.
import java.util.Random;
public class DiversCalc {
public static void main(String[] args){
int[] myList = new int[7];
Random rand = new Random();
for (int positionInArray = 0; positionInArray < myList.length;
positionInArray++) {
int diverScore1 = rand.nextInt(10);
myList[positionInArray] = diverScore1;
}
System.out.println(myList);
}
}
System.out.println(myList); is evaluated like myList.toString() and it will only print out the memory address which you are getting ([I#6d06d69c).
So, you should use Arrays.toString() to print array for per item;
System.out.println(Arrays.toString(myList));

ArrayIndexOutOfBoundsException at JavaApplication1.promptTemp(JavaApplication1.java:11) at JavaApplication1.main(JavaApplication1.java:41) [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 5 years ago.
i am working to get the average of the temperature input given by user and this is my code so far but i am getting "Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1" , i don't understand where did i do wrong.
import javax.swing.JOptionPane;
public class JavaApplication1 {
static double [] weekdays= new double[6];
static String[] weekdaysNames = new String[]{"Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"};
public static void promptTemp(){
for(int i=0;i<weekdays.length;i++){
for(int j=6;j<weekdaysNames.length;j--){
weekdays[i] =Double.valueOf(JOptionPane.showInputDialog(null, "Please enter" + weekdaysNames[j] + "temperature?",
"TempApp", JOptionPane.QUESTION_MESSAGE));
}
}
}
public static double calcAverage(double [] value){
double sum=0.0;
for(int i=0;i<value.length;i++){
sum=sum+value[i];
}
double average = sum/(value.length);
return average;
}
public static void main(String[] args) {
promptTemp();
double k=calcAverage(weekdays);
System.out.println(k);
}
}
The second for loop is the problem. j is starting at 6 and counting down. But j will always be less than weekdaysNames.length and it will go to -infinity, so that's why you're getting an ArrayIndexOutOfBounds
for(int i=0;i<weekdays.length;i++){
for(int j=6;j<weekdaysNames.length;j--){
problem in your 2nd for loop which is always less than weekdaysName.length which cause ArrayIndexOutOfBounds.
one simple solution to get ride this problem is to change the size of weekdays array into [7] and use only one for loop.

Removing element from arraylist [duplicate]

This question already has answers here:
Remove Item from ArrayList
(11 answers)
Closed 6 years ago.
Actually I want to do to set the pointer of arraylist to index which I will give, and my program will check if there's still elements then it will remove all from that index which I have given.
public void removefromindex(int index)
{
for (int j = notes.size(); j >notes.size(); j++)
{
notes.remove(j);
}
}
public void deleteAll(){
for (Iterator<Note> it = notes.iterator(); it.hasNext(); )
{
Note note = it.next();
it.remove();
}
}
You are giving an index and then not even using it and just looping through the ArrayList and removing some elements. What you are looking for is:
public void removefromindex(int index)
{
notes.remove(index);
}
To remove all of them, you can simply use:
public void deleteAll()
{
notes.clear();
}

Filling an array using a method [duplicate]

This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Closed 7 years ago.
I'm stuck with a revision question from a lab. The question is:
Write a static method to initialize an array of integers called numList. The size of the array should be passed as an int to the method and the array should be returned. Each odd index position should contain the value -1 and each even numbered position should contain the index value. Thus, such an array might contain {0,-1,2,-1,4,-1,6,-1}.
My code is currently :
public class initializeArray{
public static void main (String [] args) {
int [] numList = new int [6];
alterArray(numList);
}
public static void alterArray (int [] numList)
{
for( int i = 0; i<numList.length; i++)
{
if (i == 0)
{
numList[i] = i;
} else{
numList[i] = -1;
}
}
System.out.println( "The array is: " + numList);}
}
The return that I'm getting is :
"The array is: [I#1ef856c"
Thanks.
Updated to:
System.out.println(Arrays.toString(numList));
Error now occuring:
"Cannot find symbol - variable Arrays"
Try this:
System.out.println(Arrays.toString(numList));

Converting ArrayList to Array - not sure about how using it [duplicate]

This question already has answers here:
How to convert an ArrayList containing Integers to primitive int array?
(19 answers)
Closed 9 years ago.
This is my second program in Java, and its the first time I'm using an arrayList.
I searched about how to convert it, and used the methods i found, but I get an error...
package eliminarepetidos;
import java.util.ArrayList;
import java.util.Random;
public class Eliminarepetidos {
public static ArrayList<Integer> eliminaRepetidos (int[] vet){
ArrayList<Integer> retorna = new ArrayList<>();
for(int i = 0; i<vet.length; i++){
for (int j = i + 1; j < vet.length; j++)
if ((vet[i] == vet[j])&&(vet[i]!=0)) vet[j]=0;
if(vet[i]!=0) retorna.add(vet[i]); }
return retorna;
}
public static void imprime (int[] vet, int numElem){
System.out.print("Vetor resultante:");
for (int i = 0;i<numElem;i++)
System.out.print(" " +vet[i]);
}
public static void main(String[] args) {
int[] t;
t = new int[10];
Random generator = new Random();
for(int i = 0; i<10; i++)
t[i] = generator.nextInt(12) +9;
ArrayList<Integer> temporario = new ArrayList<>();
temporario = eliminaRepetidos(t);
int [] vetfinal = temporario.toArray(new int[temporario.size()]); //line with error
imprime(vetfinal,vetfinal.length);
}
}
How should I be using the command to make it work properly?
Thanks!
Any ArrayList can be converted to a simple array using toArray(<Type> t) (ArrayList<Thing> list -> Thing[] arr = list.toArray(new Thing[0])), but that's likely not your real question.
Your real question, based on the code you've shown, is far more likely: "how do I iterate over an arraylist?", to which the answer is: "the same as for arrays or any other collection, use the for loop in its foreach pattern":
int[] numbers = {...}
ArrayList<Thing> things = new ArrayList<Thing>();
thing.add(new Thing(...));
...
for(int i: numbers) {
System.out.println(i); // will print each element in the array
}
for(Thing t: things) {
System.out.println(t); // will print each element in the arraylist
}
This use of the for loop has been part of plain Java since v1.5 =)

Categories

Resources