Exception like java.lang.IllegalArgumentException: fromIndex(XXX) > toIndex(XX) [closed] - java

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 9 years ago.
Improve this question
I have a jqgrid, with pagination. User can enter data by themselves to neviaget between pages.
I am getting error if user enter more than available pages on line 199 as shown in the above example. How to solve this issue?
if(noOfRows != null && !recipeList.isEmpty())
if ((noOfRows * pageNo) < recipeList.size()) {
recipeList = recipeList.subList((noOfRows * (pageNo - 1)),
(noOfRows * pageNo));
} else {
recipeList = recipeList.subList((noOfRows * (pageNo - 1)),
recipeList.size()); //line 199: giving error
}
for (Recipe recp : recipeList) {
..............
..............
I tried to change the else part of code where on line 199 :
int totalCustomPagesNums=noOfRows * (pageNo - 1);
int firstIndex=totalCustomPagesNums < recipeIdList.size()?totalCustomPagesNums:1;
recipeList = recipeList.subList(firstIndex,
recipeList.size());

I would simplify it to:
Work out the lower bound, which must be at least 0 and at most recipeList.size()
Work out the exclusive upper bound, which must be at least 0 and at most recipeList.size()
Take the sublist
So:
int start = Math.min(Math.max(noOfRows * (pageNo - 1), 0), recipeList.size());
int end = Math.min(Math.max(noOfRows * pageNo, start), recipeList.size());
recipeList = recipeList.subList(start, end);
Now you know for sure that 0 <= start <= end <= recipeList.size(), so it'll be fine, even if the user specifies bizarre row counts or page numbers.

You are trying to create a sublist that starts at index 100 and ends at index 72. Since the beginning of your list is behind the end, you are getting the IllegalArgumentException.
Add another check, if (noOfRows*pageNo < recipeList.size()).

I would add two extra blocks, to the beginning of your code.
if (pageNo < 1) {
pageNo = 1;
}
if ((pageNo - 1) * noOfRows >= recipeList.size()) {
pageNo = 1 + ( recipeList.size() - 1 ) / noOfRows;
}
The first block fixes things if the page number is too low. The second block fixes things if the page number is too high.
The check at the beginning of the second block is making sure that the index of the first recipe to be displayed (which is (pageNo - 1) * noOfRows) is within the range of recipeList. The assignment inside is setting pageNo to the highest value for which this is true.

Related

My code reaches a loop then stops working [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 2 years ago.
Improve this question
I'm not sure why, but the code stops when it reaches the loop portion. I waited for 10 minutes...but still, absolutely nothing changed. It's not an infinite loop.
PrintWriter out = new PrintWriter(new File("CollectingTheData.txt"));
File dataCollection = new File("CollectingTheData.txt");
Scanner inF = new Scanner(dataCollection);
System.out.println("\nSimulating Trials Now...One Moment Please...");
RandomSquirels = (int)(Math.random() * 11 + 1);
while (RunCount <= TrialNumber) {
while (RandomSquirels != 10) {
out.println(RandomSquirels);
}
out.close();
RunCount++;
}
while (inF.hasNextLine()) {
NumRead = Integer.parseInt(inF.nextLine());
SquirelTotal += NumRead;
}
inF.close();
CalculationsForAv = (double)SquirelTotal / (double)TrialNumber;
System.out.println("The results! \nThe Average Number of \nSquirels Observed until Observing a Fox Squirrel: " + CalculationsForAv);
I only included the relevant portion of code. Everything necessary is imported and all the variables are defined.
while (RandomSquirels != 10) {
out.println(RandomSquirels);
}
You never change RandomSquirels value inside the while, I guess that what you wanted to do is:
while (RandomSquirels != 10) {
out.println(RandomSquirels);
RandomSquirels = (int)(Math.random() * 11 + 1);
}
I also noticed that you run out.close() inside a while, so you will try to close it over and over again... You shouldn't close a stream more then once.
Java is an imperative language. You appear to think that this:
RandomSquirels = (int)(Math.random() * 11 + 1);
is like a macro, you think it means: "Everytime I write RandomSquirels, assume I wrote (int)(Math.random() * 11 + 1). That is not how java works.
It means: Run the expression (int)(Math.random() * 11 + 1) right now, once, and assign the result of this to the variable RandomSquirels.
You then loop while RandomSquirels is not 10 and print it to the file. Forever, except once in every 11 runs, when the value so happens to resolve to 10.

Why do I get IndexOutOfBoundsException error in lowpass-filter loop?

I am trying to implement the Pan Tompkins algorithm in my first Java application. I have made the following loop for the lowpass-filter, based on the original article but I keep getting IndexOutOfBoundsException error when I try to run it. Can someone see where I go wrong?
I don't want to make the filter with coefficients, I just need help to get the formula to work, please.
/**
* Lowpass filter
* lpfilt() implements the digital filter represented by the difference equation:
* y(nT) = 2y(nT - T) - y(nT - 2 T) + x(nT)- 2x(nT- 6T)+x(nT- 12T)
*/
public static ArrayList<Double> lpfilter(ArrayList<Double> ecg) {
int N = ecg.size();
ArrayList<Double> ecgLP = new ArrayList<Double>();
for (int n = 0; n < N; n++) {
if (n - 12 < 0) {
ecgLP.set(n, ecg.get(n));
} else {
ecgLP.set(n, 2 * ecgLP.get(n - 1) - ecgLP.get(n - 2) + ecg.get(n) - 2 * ecg.get(n - 6) + ecg.get(n - 12));
}
}
return ecgLP;
}
It happens in the first iteration. Look at the following line:
ecgLP.set(n, ecg.get(n));
For n=0 you try to set the key 0 with with a value of ecg.get(0). But 0 has not been set so far. Therefore you get the IndexoutofBounds-Error. As far as I see the first 12 (0..11) iterations should fill the ArrayList, but your code will fail with errors every time because you try to use a member which has not been initialized yet.
I would suggest you do the initialisation in a separate loop and start with n=12 afterwards.
In for loop take case when n is 0, in this case you can not call ecgLP.get(n - 1) as it becomes ecgLP.get(-1), negative index gives you Exception.

Printing "*" with recursion [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 6 years ago.
Improve this question
I would need some help to solve one exercise. In this method I have to print the number of asterisks ("*") that are equal of 2 of power of x.
For example, if I have 2 of power of 2 it should print 4 asterisks ("****");
I have a method that returns me the right number, but I have problems using that number for printing those asterisks.
Here is my code:
public static int writeStars(int number) {
if (number == 0) {
return 1;
} else {
int number2 = 2 * writeStars(number - 1);
System.out.println(" number " + number2);
return number2;
}
}
Here's one idea for solving the problem, without giving away the solution in code.
Your thoughts are on the right track, realizing that 2x = 2 * 2x-1. To print 2x * characters, you can print 2x-1 twice. In your recursive method, have your base case print one * character, and have your recursive case make the recursive call twice, passing the appropriately adjusted value.
One way to do it is to create a string of 2^(i-1) stars at the i-th iteration. So, for 4 iterations (x=4), you will have 8,4,2,1 stars for each iteration. You can return the string of stars for each iteration and concatenate them to get the final string.
The terminating condition will be when the input size is 0. This code might help:
public static String writeStars(int y) {
//y is 2^x
if( y == 0)
return "";
int num_stars = y - y/2;
StringBuffer stars_Buffer = new StringBuffer(num_stars);
for (int i = 0; i < num_stars; i++){
stars_Buffer.append("");
}
return stars_Buffer.toString() + writeStars(y/2);
}
Call writeStars with input 2^x:
writeStars(Math.pow(2, x));
Because it is a return method in your client you should have
int num = writeStars(someNum);
Then to print, you just need a simple for loop
for(int i=0; i < num; i++)
System.out.print("*");

what is wrong with this code in projectEuler 10? [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 7 years ago.
Improve this question
i wrote this code for project Euler problem 10 . but in line 24 it has an error. how to fix it?
public static void main(String[] args) {
int i;
int b = 2000;
List<Integer> notPrime = new ArrayList<Integer>();
notPrime.add(2);
notPrime.add(3);
notPrime.add(5);
notPrime.add(7);
for (i = 2; i < b; i++) {
if (i % 2 != 0 && i % 3 != 0 && i % 5 != 0 && i % 7 != 0) {
notPrime.add(i);
}
}
for(int primesNum:notPrime){
int dd = (int) Math.pow(primesNum, 2);
int indexofdd = Arrays.asList(notPrime).indexOf(dd);
//here is the error
notPrime.remove(indexofdd);
}
int summy = notPrime.stream().mapToInt(Integer::intValue).sum();
System.out.println(summy);
}
The type of Arrays.asList(notPrime) is List<List<Integer>>, meaning that Arrays.asList(notPrime).indexOf(<some int>) is always going to be -1 (not found), because a List<List<Integer>> cannot contain an Integer.
Hence the call to List.remove will fail, since as the Javadoc states:
Throws IndexOutOfBoundsException - if the index is out of range (index < 0 || index >= size()).
You can simply write:
notPrime.remove(Integer.valueOf(dd));
(No need for separate indexOf call)
You need the Integer.valueOf in order to ensure that List.remove(Object) is invoked, rather than List.remove(int): the latter removes the element at the given index, whereas the former removes the list element with the given value.
However, the logic of this code looks more generally faulty.

Is putting an assignment statement in an if statement bad practice? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
Based on the code snippets below (they have been shortened for clarity).
The purpose of the scoreBoardState method is to be used to determine a score for the state of the game at the leaf nodes in a minimax algorithm that will be passed up to determine the best move for the AI to make.
The hasThreeInARowAndTwoOpenSpaces_Horizontal is one of many similar methods that is called by scoreBoardState to determine whether some condition is met (such as a player having 3 token in a row). If it is true it returns the number of the player that fulfills that conditions then increases the score of that player (either the human player or the AI).
The method needs to be called in an if statement to check if the value returned isn't zero (which means some score should be added). I can either set the value returned by the method within the if statement (Which I did in the code snippet), or I can call the method again if it doesn't return 0 and then set it into the variable. Obviously the second method is less efficient, but it is more human readable and easier to notice what is happening.
The question is, is setting the variable returned by the method called within the if statement considered bad practice? Or is it ok since it is more efficient?
Note: The inefficiency of the second method grows fairly quickly since it is within a for-loop and this situation will arise many times as each condition is tested. It is also done for each leaf node in a minimax algorithm (each node can have 7 branches) means a depth of only 3 (the minimum I'm using) there are 343 leaf nodes andbuta depth of 7 (the highest I'm currently using) there are almost 825,000 leaf nodes.
/* scores the board state of a root node in a minimax algorithm
* #gameState a 2 dimensional array that stores values for each space on the
* board. Stores 0 for empty or 1 or 2 if position is taken by a player
*/
int scoreBoardState (int[][] boardState) {
int aiScore = 0;
int playerScore = 0;
int player = -1;
for (int i = 0; i < boardState.length; i++) {
for (int j = 0; j < boardState[i].length - 4; j++) {
if (j < boardState[i].length - 5 && (player = hasThreeInARowAndTwoOpenSpaces_Horizontal(boardState, i, j)) != 0) {
if (player == AI)
aiScore += 1000; //magic number entered for clarity
else if (player == PLAYER)
playerScore += 1000;
}
else if (i < boardState.length - 4 && j > 2 && (player = hasThreeInARowAndOneOpenSpace_Diagonal_UpperRightToLowerLeft(boardState, i, j)) != 0) {
if (player == AI)
aiScore += SCORE_THREE_IAR_ONE_OS;
else if (player == PL)
playerScore += SCORE_THREE_IAR_ONE_OS;
}
}
}
return aiScore - playerScore;
}
/*
* checks if, starting from the passed in coordinates, whether there are 3
* spaces taken by the same player with an empty space on either side in a horizontal direction (left to right).
*
* returns the player number if the result is true. returns 0 if the result
*is false or all spaces are empty
*/
int hasThreeInARowAndTwoOpenSpaces_Horizontal(int[][] boardState, int row, int col) {
if (boardState[row][col] == 0
&& boardState[row][col + 1] == boardState[row][col + 2] && boardState[row][col + 2] == boardState[row][col + 3]
&& boardState[row][col + 4] == 0)
{
return boardState[row][col + 1];
}
return 0;
}
It certainly runs the risk of being unexpected by anybody reading the code, which makes the code more difficult to support. That's often a worthy thing to avoid.
In both cases if there is a performance cost to be avoided then you could modify the condition to become nested conditions. So instead of this:
if (j < boardState[i].length - 5 && (player = hasThreeInARowAndTwoOpenSpaces_Horizontal(boardState, i, j)) != 0) {
you might have something like this:
if (j < boardState[i].length - 5) {
player = hasThreeInARowAndTwoOpenSpaces_Horizontal(boardState, i, j);
if (player != 0) {
That way the performance penalty of the operation is still only incurred when it otherwise logically would be in the original code. But the existence of the operation, and its subsequent assignment to a local variable, becomes a lot more obvious. Anybody browsing the code will be able to immediately see what's going on with very little thought.
The benefit here is that the conditionals themselves are very clear and concise. Having long conditional comparisons can make code very difficult to follow, but a simple comparison is straightforward.
The drawback here is that you're creating nested conditionals. People tend not to like those. (Though in this case my personal opinion is that it's the much lesser of two evils.) But that can be addressed by refactoring the operations inside of each conditional into their own aptly-named methods, if the readability of that is preferred.
I would not say that it is bad practice. As long as it is used correctly. In your case the usage is fine since there is a valid condition that needs to be met before a variable needs to be set. In the top method where it is the one or the other option, you might consider using the following, but it is just a personal taste thing:
condition ? true value : false value
The usage of if statements are fine as long as they are used with else statements to stop additional if statements from being executed then all is well.

Categories