The loop needs to scan an external file, from the bottom to the top. BUT...
When the loop has scanned 6 items from the external file, it needs to stop.
Then, IF there are less than 6 items to scan from the list on the external file it needs to print all of the those items to the screen.
I know how to do a loop that can scan the file from top to bottom using inFile.hasNext(); etc. I just don't know how to do from bottom to top and then define how many iterations I want the loop to actually do, with an if statement that is something like:
if (number of iterations < 6 print all)
{
JOptionPane.showMessageDialog(iteration1, iteration2, etc...)
}`
else if (number of iterations >= 6 only show the first 6 the loop has scanned)
{
JOptionPane.showMessageDialog(iteration1, iteration2, etc...)
}
Sorry about my awful pseudo code, just really stuck and this is the last part I need to do to finish my system!
any help would be brilliant!
I would recommend using a predefined class for reading backward. As to looping:
for(int i = 0; i < 6 && /* test for more input*/; i++)
{
JOptionPane.showMessageDialog( /*next input*/ );
}
I'd try instantiating an array with 6 empty strings and then concatenate the item you get in each iteration of the loop with the corresponding empty string in your array.
Afterwards you can check for your < 6 condition and depending on the result concatenate the string you want to give to your JOptionPane
You can't read a file from bottom to top. Instead, read the file (top to bottom) keeping the last (up to) 6 items read. When you hit the end if the file, test if you you have 6 items or not and act accordingly.
Use a LinkedList object, which allows removal of the element of the list via removeFist().
You could just store all items and use only the last 6, but that may mean using a lot of memory if the file is very large.
Related
I have a ArrayList from 1 - 9 that is randomly ordered and will be represented in three rows like this order for example:
6,5,7
4,8,1
9,2,3
It should be noted that I'm working with just a flat list, but I intend to represent it like above later on.
What I need is to be able to always swap the 9 element with the one above it. So for the configuration above I would need to swap the 9 and the 4. This needs to be done for any order where the 9 element might appear.
I've already created a switch statement that should do this when a user presses a key on the keyboard. So the logic of this swap should go in that switch case.
I wrote this code to try and achieve this goal, but it doesn't work as intended.
case 'u' :
int nineIndex = temp.indexOf(9);
int nine = 9;
int indexToSwapTo = temp.indexOf(9) - 3 % 9;
System.out.println("index of 9: " + nineIndex);
System.out.println("index to swap to : " + indexToSwapTo);
temp.remove(nineIndex);
temp.add(nineIndex, indexToSwapTo);
temp.remove(indexToSwapTo);
temp.add(indexToSwapTo, nine);
break;
The idea is, I first get the index of the 9 and then to get the index of the item above it I do the index at 9 - 3. I then perform some adds and removes. I should also note that the temp is an ArrayList that holds the random configuration of numbers. However this code doesn't work quite as intended. It does this instead:
The randomly order array list produces the following:
[6,1,8,3,7,**4**,2,5,**9**]
And after a swap occurs as described above, the ArrayList turns into this:
[6,1,8,3,7,**9**,2,5,**5**]
The printout says this as well which is useful:
index of 9: 8 index to swap to : 5. As you can see although it does swap the items in the correct place it for some reason puts index 5 as the item to be swapped rather than the actual value of index 5 which is 4. It also sometimes runs with out of bounds exceptions.
Use Collections.swap
You're way overthinking the problem. Just use the API available to you.
int nineIndex = temp.indexOf(9);
int indexToSwapTo = (nineIndex + 6) % 9;
Collections.swap(temp, nineIndex, indexToSwapTo);
Note this assumes that when 9 is on the top line, the "above" line is the bottom one, as in a circular way.
First off, the % operator in Java has a higher precedence than - so your line 4 is
equivalent to
int indexToSwapTo = temp.indexOf(9) - 3;.
This will work, but only for the last two rows. You should add some parentheses around the right hand side to cover every case, like this:
int indexToSwapTo = (temp.indexOf(9) - 3 ) % 9;
Secondly, there is a logical error in your code. In particular, in the first code block that adds and removes the ArrayList entries:
temp.remove(nineIndex);
temp.add(nineIndex, indexToSwapTo);
The second line is wrong, as it attempts to insert the index of the entry that you're meant to swap with, and not the value of that entry. In your example, the program correctly realises that it needs to swap the ArrayList entries at indices 5 and 8. However, in your code, you are telling the program to store 5 in the position of 9, instead of telling it to store the contents of index 5 in the position of 9 (which in this case, is the 8th entry of the ArrayList).
To fix your code, you should replace the code block above with this:
int value_to_be_swapped = temp.get(indexToSwapTo)
temp.remove(nineIndex);
temp.add(nineIndex, value_to_be_swapped);
I'm having trouble wrapping my head around how to implement a method that starts with an int[][] input and a predefined sum value that returns an int[][] output that only displays the adjacent values in the row that add up to the sum. For example, if the input array was
int[][] input = new int[][]{
{3,4,4,2,7},
{2,3,2,8,6},
{1,4,2,1,2}
}
when the sum is set to 7, it would yield an output array with the following values
{3,4,0,0,7},
{2,3,2,0,0},
{1,4,2,1,0}
}
The output array should only display values that add up to a set number (7) with their neighbors, or if its a number from 0-9 values that are the desired sum (when you search for 7 it displays all 7s). To further clarify, as you can see in the output array, it displays the first two values, 3 and 4, because they add to 7. It displays 2,3,2 because they also add to 7. It prints out 1,4,2,1 on the bottom because 1,4,2 add to 7 and 4,2,1 add to 7. To summarize, it displays only values which are 7 or add up to 7 with the numbers next to them, and otherwise displays 0. Also the input values must be <0.
After brainstorming for a while I know that the code will need a number of nested loops: one to loop through the rows, inside that one to loop through the columns, inside that a loop to update the sum which stops when the sum equals the preset sum (7 in this case), and finally a loop to update the output[][]. However, I'm having a great deal of trouble on writing code that implements all of these loops correctly. I am planning on doing the same thing with numbers that add up vertically, but want to focus on horizontal as of now.
This can be done in O(NxM) complexity.
For each row, you keep two indexes (say, iLow and iHigh initialised to the first item input [i][0]) and a sumSoFar variable. At each iteration, if the sumSoFar < 7 you increment iHigh. If it is > 7 then you increment iLow and iHigh. If It is == 7 then you've found one combination + increment iLow and iHigh.
This should give the high-level idea of the algorithm and I'm sure that a lot of details are missing/incomplete but you should be able to put that in code.
You need three nested loops. Or really, three levels of nested loops with two loops after each other on the innermost level, but I will return to that in the end.
Before any loops, create the backbone of your result array. It’s OK if it’s an array of null references to arrays at this point.
Outer loop: loop through the outer array. A classical for loop is one option. For each entry, create an inner array of the correct length in the result, filled with zeroes for a start.
Middle loop, loop through the entries in the inner array. Again a classical for loop is fine. Your goal is that each iteration will determine if a series of adjacent values with the sum 7 begins at this entry, and if so, find out how long it is, and copy the entries in question to the result array.
Inner loop (first inner loop, that is) is for adding adjacent entries to find out if the sum is 7. You start from the entry from the middle loop and add up the values. This loop has a double stop condition: you stop when the sum is 7 or greater (assuming all values are positive), but obviously you also stop when reaching the end of the inner array. A while loop would be for my taste. Only if the sum hits exactly 7, do you use a new inner loop to copy the values to the result.
PS If you assume all values are positive, you shouldn’t just assume, you should check. In the middle loop, if the value in that entry is 0 or negative, throw an IllegalArgumentException.
So basically, I have a programming assignment, and it involves two lines at an airline, one for frequent flyers and one for regular flyers. I have a for loop set up that, each time it runs, it determines whether some amount of frequent flyers gets in, some amount of regular flyers, or no one. For a frequent flyer, it is supposed to take 3 minutes to service a flyer, with one "minute" being a single iteration of the loop. For the regular flyers, it will take 5 minutes to service one person, again, with one iteration of the loop being a single minute. How can I determine when someone in the line has been serviced? As in, how can I pull someone out of the line whenever 3 or 5 iterations of the loop have occured, respectively. I'm utilizing a linked list.
I'm not sure I entirely understand your question, but I think I got the idea.
You could use break; to exit the loop (if that's what you're trying to do), and to test the amount of times the loop has been executed, you can use an int. It will look something like this:
int i = 0;
for(initialization, condition, iteration){
//Your code
if(i == 3 | i == 5){
break; //If you have your own method to "pull someone out of the line",
//then insert it here instead of using break, and also insert i = 0.
}
i++;
}
This question already has answers here:
Generating Unique Random Numbers in Java
(21 answers)
Closed 7 years ago.
I'm creating a 50 states study app (To help me for school), and I want each choice of a state to have it's own random option. So I have an Array holding all of the state's. Is there anyway I can select randomly select a variable from this Array then drop the variable I just used (That way it's not used again). But I want It to take the minimum amount of data, because It will be in my game loop. Which is run 60 times per second (60 FPS). Any Ideas? Here is what I'v thought of:
String.valueOf(stateVariables.get(random.nextInt(3))) //It has four variables in it, so three is the max.
But this doesn't stop the variable it selects from being used again. Please Help!
If i understand you right, you are concerned about the performance during your game loop. I have a performant idea in mind. You could create an array with all indices and shuffle it randomely before running the game loop. Safe that array as some subclass of java.util.Queue. Then when the game loop runs you can just remove the first element of that Queue and select it from the array.
As every index is only once in the Queue it will not be reselected and the remove function from a Queue is pretty performant therefore you will not have to worry about that. Only the initialization of that Queue is relatively performance intense, however still in milliseconds.
Not sure if understood your question, but after selecting a array position, you want to exclude it and never be selected again?
If so, you can't delete an array position. What you can do is set this position to null, so when you pick it again, it'll return null and you'll know it have already been selected.
public int getRandom(int i) {
int randomNumber = array[i];
array[i] = null;
return randomNumber;
}
int selectedNumber = getRandom(3);
if (selectedNumber == null)
System.out.println("Number already selected");
else
System.out.println("Number never selected; can be used");
It must be really basic but I need help. For example, you store monster information in an array, and do for~loop to make each monster attacks/moves in their turn like this
for( i <- 0 to monsters.length-1) monsters(i).act
Then some monsters die during the loop and you have to delete some elements in the array while the loop is still on going. Then the next item in the array could be not really the the next one you want to process.
is there any fast/smart way to make sure each item in an array will be proceed once and only once within the loop, even if you really had to make change to the array during loop?
Scala's collections generally don't assume that you'll be manipulating them while they're using a method like foreach (or executing a for loop). If you want to do things that way, the easiest class to use is Java's java.util.concurrent.ConcurrentSkipListMap.
// This helps you use Java collections like Scala ones
import collection.JavaConversions._
case class Monster(name: String, hp: Int) {}
val horde = new java.util.concurrent.ConcurrentSkipListMap[Int,Monster]
horde put (0, Monster("wolf",7))
horde put (1, Monster("orc",3))
for (h <- horde) println(h) // Prints out both
Iterator.iterate(Option(horde.firstEntry)) {
case None => None
case Some(e) =>
val m = e.getValue
if (m.name=="wolf") horde.remove(1) // Kill the orc
else if (m.name=="orc") horde.remove(0) // Kill the wolf
Option(horde.higherEntry(e.getKey))
}.takeWhile(_.isDefined).foreach(_=>())
for (h <- horde) println(h) // Prints out just the wolf
Now, granted, this is rather a mess, but it does work, and it gives nice random access to your monsters. You have to maintain the keys in a sensible order, but that's not too hard.
Alternatively, as others have indicated, you could add an isAlive or isDead method, and only act on monsters that are alive. Then, after you've passed through the list once, you .filter(_.isAlive) to throw away all the dead monsters (or .filter(! _.isDead)), and run it again.
I would either use a conditional statement to check the monster's isAlive property in the loop before I called act, or do that check inside the act method itself.
I imagine that your monster[i] is not going to die on his turn, but rather off some other hapless monster?
If you're hooked on arrays, or don't mind the processing time (and for what you're doing, i reckon you don't care), just keep a boolean on each monster of isDead.
If a monster dies due to some ... i dunno, reason, just mark the "isDead" as true.
Then, in your monster "act" method, just check if the monster "isDead" or not.
After each loop, you can just prune the list to keep the alive monsters (move all the ones that are alive to a new list and begin again, prune the list in place, whatever is easier for you).
EDIT: This first graph misinterperets your question. However, my solution should still work for you.
What you're asking for is a thread-safe array - one that can be accessed by multiple "threads" of execution at a time. Seeing as you're new to Java, my guess is that your game is not going to be multithreaded, and so if you delete an item in an array, that's going to happen for sure before your next loop runs.
That said, if you really want to, you can add a "monster.dead" boolean function to your array, and set that to true whenever a monster dies. In your loop, then, you'd say:
for( i <- 0 to monsters.length-1)
if (monsters[i].dead == false)
monsters(i).act
Most likely, though, you won't run into this issue.
Edit: just reread your post, and realized that you'll be deleting monsters as your array is running. Remember that each line you execute happens sequentially, so when you remove monsters[i], it will be gone the next time the for loop is evaluated. If you have an array of monsters with 5 monsters in it and you delete the second one, when the loop executes again,
monsters.length - 1
is going to evaluate to 3 now. You'll never run into a moment where you hit a deleted array element.
If you delete an entry in an array, this element would be null.
Therefore you should check every element of your array, e.g.:
for(int i = 0; i <= array.lenght - 1; i++) {
// check null
if(array[i] != null) {
// do stuff
}
}
Hope this helped, have Fun!
make a copy of the original array, and traverse the copy.
if a monster would remove a monster, it would be removed only from the original
Deleting elements from an array while looping over it is generally a horrible idea. What if you delete an element before you reach it in the loop? Should you not actually delete it until the end of the loop, or should you skip over it?
I recommend something more like this:
var monsters = ... initial list of monsters ...
monsters = for (m <- monsters; if m.alive) yield { m.act; m }
Take advantage of yield and if in conjunction with the for loop, which allows you to build a new list.