I am new to Java, please help me.
My program is
import java.util.*;
import java.lang.*;
class Test
{
public static void main(String[] args)
{
ArrayList al=new ArrayList();
al.add("a");
al.add("b");
for(int i=1;i<=10;i++)
{
al.add(i);
}
al.remove("a");
al.set(1,"c");
for(int j=3;j<=al.size();j++)
{
al.set(j,"z");
}
System.out.println(al);
}
};
in above any mistake........plz help me
a) You need to make the class public to run it:
public class Test
{
b) the last semi-colon is a syntax error No it's not, it's just unnecessary noise.
c) This fails with an IndexOutOfBoundsException:
for(int j = 3; j <= al.size(); j++){
al.set(j, "z");
}
It needs to be:
for(int j = 3; j < al.size(); j++){
al.set(j, "z");
}
Explanation: List Indexes are zero-based, so the highest position in a List with n elements is n-1
BTW, the above code can be written in a more elegant way like this:
Collections.fill(al.subList(3, al.size()), "z");
Reference:
Collections.fill(List<T>, T)
List.subList(from, to)
This code will throw an IndexOutOfBounds exception because of the line:
for (int j = 3; j <= al.size(); j++) {
to fix it, you need to change it to:
for (int j = 3; j < al.size(); j++) {
This is because the <= means that your for loop iterates over the end of the list.
List~ and Arrayindices start at 0, not 1. So if you have a list of 3 Elements, they go from index: 0, 1, 2. So you normally iterate from (i = 0; i < list.size (); ++i). Less than, not less/equal.
for (int j=3; j < al.size (); j++)
1.The semicolon in the last line
2.change the code from
for(int j=3;j<=al.size();j++)
to
for(int j=3;j<al.size();j++)
Arraylist are always accessed from from 0th index to less than the size of the array.
I think it is necessary to change also the start index from 3 to 2:
for (int j=2; j < al.size (); j++)
Related
I'm working on a code for a requirement. If for example I have this test data:
multiple variable:
3
Context Change (next in array)
1
Context Change (next in array)
2
Repeat variable:
TESTA
Context change (next in array)
TESTB
Context change (next in array)
TESTC
Code:
I've tried using j as the array. Both i and j are failing since if for example i is 3 in the 1st array, then multiple[i] will be multiple[3] which is out of bounds already.
for(int j=0; j <= multiple.length - 1; j++) {
for(int i=0; i < Integer.parseInt(multiple[i]); i++) {
result.addValue(Repeat[i]);
}
}
Output should be this one:
TESTA
TESTA
TESTA
Context change (next in array)
TESTB
Context change (next in array)
TESTC
TESTC
This is the only thing wrong about your code with a first look:
for(int j = 0; j <= multiple.length - 1; j++) {
for(int i = 0; i < Integer.parseInt(multiple[j]); i++) {
result.addValue(Repeat[i]);
}
}
You should be using multiple[j] instead of multiple[i] since your are looping in that loop. Other thing is why are you doing multiple.length - 1? Also please clarify what you want to do because your answer doesn't make that much sense, at least to me. What are you trying to do? If this helps, than great! Otherwise clarify the problem. Hope it helps.
I don't understand what you are asking for, but I guess you're asking the question about multidimensional arrays traversal.
this is the code for example, maybe can help you:
int[][] arr = {{23, 45, 123}, {545}, {124,543}};
for (int i = 0; i < arr.length; i++) {
System.out.println("-------" + i + "-------");
for (int j = 0; j < arr[i].length; j++) {
System.out.println(arr[i][j]);
}
}
I'm trying to compare elements in an array. When I use a variable within a loop, I get an out of bounds error. Yet when I use explicit values in place of the variables, with the same value, it works fine.
What am I missing?
The problem line is:
int result = (myList[j]).compareToIgnoreCase(myList[j + 1]);
But if I use this, it works (values should be identical):
int result = (myList[0]).compareToIgnoreCase(myList[1]);
Have searched high and dry for this. Other posters had different issues. Would appreciate any input! Here's the example with dummy content:
public class methodSortTest
{
public static void main(String[] args)
{
// Create and load data into array
String[] myList = new String[2];
myList[0] = "Charlie";
myList[1] = "Bravo";
// Compare, positive/negative
for (int j = 0; j < myList.length; j++)
{
int result = (myList[j]).compareToIgnoreCase(myList[j + 1]);
System.out.println("Result is: " + result);
}
}
}
Try this:
change this:
for (int j = 0; j < myList.length; j++)
to this:
for (int j = 0; j < myList.length-1; j++)
problem is inside this statement:
int result = (myList[j]).compareToIgnoreCase(myList[j + 1]);
because you are accessing the j+1
Simple Helping material:
https://www.geeksforgeeks.org/understanding-array-indexoutofbounds-exception-in-java/
When j equals 1, myList[j + 1] evaluates to myList[2] which throws an ArrayIndexOutOfBoundsException. There is no item at index 2 because you have only inserted items at index 0 and 1.
Reference: https://docs.oracle.com/javase/7/docs/api/java/lang/ArrayIndexOutOfBoundsException.html
Change your for loop from
for (int j = 0; j < myList.length; j++)
To
for (int j = 0; j < myList.length-1; j++) // note the "-1"
This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 5 years ago.
When the below method is run it throws an ArrayIndexOutOfBoundsException at line 179, which is the if statement in the nested loop.
I was thinking it had something to do with the index of j-1. So I took the -1 out and just had j in the brackets, but it threw the same exception at the first line of the swap. I've looked for bubble sort syntax and from what I can tell is I'm good. I'm close, I know. Any suggestions to fix this?
public static void bubbleSort(int[]array1){
int temp = 0;
for(int i = 0; i < array1.length; i++){
for(int j = 0; j < (array1.length - i); j++){
if(array1[j-1] > array1[j]){
//swap
temp = array1[j-1];
array1[j-1] = array1[j];
array1[j] = temp;
}
}
}
}
The only problem because of which you are getting this error is the case when j = 0, because at that time j-1 = -1. Which is not a valid index value in java and hence arrayIndexOutOfBounds exception. I have made the necessary change in the code. Have a look in the snippet below.
public static void bubbleSort(int[]array1){
int temp = 0;
for(int i = 0; i < array1.length; i++){
for(int j = 0; j < (array1.length - i-1); j++){
if(array1[j] > array1[j+1]){
//sawp
temp = array1[j];
array1[j] = array1[j+1];
array1[j+1] = temp;
The first element of the array is 0. With j-1 you get -1 and this is not in the range of the array.
You tried to put just "j". But, I think that you put "j+1" to compare. And the arrayIndexOutOfBounds exception was throwed because of the "j+1".
Try to use this at the second loop:
(array1.length - i - 1)
You are getting this exception because you have initiated j=0 and doing j-1. In that case it is going out of bound and hence giving exception. Code below will work fine.
public static void bubbleSort(int[] array1){
int temp = 0;
for(int i = 0; i < array1.length; i++){
for(int j = 1; j < array1.length-i; j++){
if(array1[j-1] > array1[j]){
//sawp
temp = array1[j-1];
array1[j-1] = array1[j];
array1[j] = temp;
}
}
}
For first iteration of inner loop when j=0, j-1 becomes -1 and arr[-1] is index out of bound exception.
Now when you change j-1 to j in if condition
if(array1[j-1] > array1[j]) // j-1 to j
Still in the first line swap arr[j-1] is arr[-1] which throws index out of bound exception.
Please follow the below code to avoid index out of bound exception.
Start j's iteration from 1.
`public static void bubbleSort(int[]array1){
int temp = 0;
for(int i = 0; i < array1.length; i++){
for(int j = 1; j < (array1.length - i); j++){ //initialize j=1 instead 0
if(array1[j-1] > array1[j]){
//sawp
temp = array1[j-1];
array1[j-1] = array1[j];
array1[j] = temp;
}
}
}
}`
I want to print out the elements of this multidimensional array but I get the index out of range error.
public class test {
public static void main(String[] args) {
int array1[][]={{1,2,3,4},{5},{6,7}};
for (int i=0; i<3;i++){
for (int j=0; j<4;j++){
System.out.println(array1[i][j]);
}
}
}
}
The problem is that with the loop, written like this, you assume that the nested arrays are all of length of 4 (and they are not). You'd better do:
for (int i=0; i < array1.length;i++) {
for (int j=0; j < array1[i].length;j++) {
...
}
}
Yes, because the second "subarray" doesn't have 4 elements. It would be better to do this dynamically:
// Note preferred syntax for array types - keep all the type info in one place.
int[][] array1 = {{1,2,3,4},{5},{6,7}};
for (int i = 0; i < array1.length; i++) {
for (int j = 0; array1[i].length; j++) {
System.out.println(array1[i][j]);
}
}
This way the iteration count of the inner loop depends on the array being iterated over.
An alternative is to use the enhanced for loop:
for (int[] subarray : array1) {
for (int value : subarray) {
System.out.println(value);
}
}
2 points regarding the following solution (and the other similar answers):
for (int i=0; i < array1.length;i++) {
for (int j=0; j < array1[i].length;j++) {
...
}
}
Here it wont make much difference, as the code is very short, but for better performance you should always avoid repeated calculations if the result never changes. array1's length wont change so calculating its length every iteration is not efficient. This would be improved solution.
int array1Length = array1.length;
for (int i=0; i < array1Length;i++){
int array1InnerLength = array1[i].length;
for (int j=0; j < array1InnerLength;j++){
...
}
}
Some people may suggest using ++j / ++i instead of i++ and j++ for better performance, you can read more about it here: What is the difference between ++i and i++?. Its not that critical imo, but it improves understanding of the code you're writing.
i have a problem that return me the follow error
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 2, Size: 1
at java.util.ArrayList.RangeCheck(ArrayList.java:547)
at java.util.ArrayList.get(ArrayList.java:322)
at graphsshahar.TestDijkstra.main(TestDijkstra.java:38)
my program get a list of objects and i need to find in the list the equal to one
and then print it , here is the code
public static void main (String [] args){
System.out.println("begin");
int one = 2;
int two = 10;
List<Conniction> tempDeal = ConnictionDAO.getInstance().findPath(one, two);
List<String> oneid = new ArrayList<String>();
List<String> twoid = new ArrayList<String>();
for (int j = 1; j <= tempDeal.size(); j++) {
System.out.println("get");
if( Integer.parseInt(tempDeal.get(j).getOneid()) == one )
{
oneid.add(tempDeal.get(j).getOneid());
System.out.println(oneid.get(j));
}
}
System.out.println("end");
what should i fix ?
i dont know what is wrong with the if statement
Just change yours with this j < tempDeal.size() Numbering starts from 0 not from 1.
for (int j = 0; j < tempDeal.size(); j++) { ... }
If you would use j = 1 you are not able to get item at 0 position.
Update:
You can use also iterator like meant #AVD.
for(Conniction member: tempDeal) {
// do work
}
for (int j = 1; j < tempDeal.size(); j++)
If it is not intentional, 'j' should start from '0'
for (int j = 0; j < tempDeal.size(); j++)
List index starts with '0'
If index isn't matter then you may use iterator for loop.
for(Conniction obj: tempDeal){
if(obj!=null) {
if(Integer.parseInt(obj.getOneid())==one){
oneid.add(obj.getOneid());
}
}
}
Change this :
for (int j = 0; j < tempDeal.size(); j++) {
Lists indexes starts at 0 and ends at size() - 1
you need different counter for the oneid array. If the if-statement return false once, the next time you enter here you'll get IndexOutOfBounds.
int oneIdCount = 0;
and increment it inside the if
if( Integer.parseInt(tempDeal.get(j).getOneid()) == one )
{
oneid.add(tempDeal.get(j).getOneid());
System.out.println(oneid.get(oneIdCount));
oneIdCount++;
}
and as the above answers - start the for from int j=0
And if you want to print the last element only you can use oneid.size()-1 instead of variables.