Ending Java War game with while loop

How would i go about ending a java war game witha while loop. I want the program to run until all of the values of one of the arrays of one of the players split decks has all null values.

GameObject[] theArrayInQuestion;
// populate array somehow or other
void methodWithLoop() {
   while(arrayNotNull(theArrayInQuestion)) {
   // do stuff
boolean arrayNotNull(Object[] array) {
  int len = array.length;
  for(int i = 0; i < len; i++) {
    if ( array[i] != null ) {
      return true;
  return false
}

Similar Messages

  • Probably simple problem with while loops

    I was programming something for a CS class and came across a problem I can't explain with while loops. The condition for the loop is true, but the loop doesn't continue; it terminates after executing once. The actual program was bigger than this, but I isolated my problem to a short loop:
    import java.util.Scanner;
    public class ok {
    public static void main(String[] args){
         Scanner scan = new Scanner(System.in);
         String antlol = "p";
         while(antlol == "p" || antlol == "P"){
              System.out.println("write a P so we can get this over with");
              antlol = scan.nextLine(); 
    //it terminates after this, even if I type "P", which should make the while condition true.
    }

    Thanks, that worked.
    I think my real problem with this program was my CS
    teacher, who never covered how to compare strings,Here's something important.
    This isn't just about comparing Strings. This applies to comparing ANY objects. When you use == that compares to see if two references refer to the same instance. equals compares objects for equality in the sense that equality means they have equal "content" as it were.

  • Time not stopping with while loop

    Hello,
    I've attached my VI.  I am having trouble with while loops.
    I want to turn on LEDs. The first LED should turn on after 3s.  The second LED should turn on after 5s.  The third LED will turn on later. 
    The LEDs turn on based on the following conditions:
    Case 0: numeric control > 10 then led_1 off, led_2 off, led_3 off
    Case 1: numeric control <= 10 then led_1 on, led_2 on, led_3 on
    Case 2: numeric control <=5 then led_3 on
    Because of the way I'm delaying time, I have the following problems
    Case 1 --> case 2: led_3 doesn't come on right away
    Case 2 --> case 1: led_3 doesn't turn off right away
    Putting probes in certain areas leads me to believe that these problems are due to the way the time delay is being generated.
    Thanks in advance.
    EDIT: Looking at it more...it seems to be that when the stop condition is true, the loop runs one more iteration. Is there a way to keep it from running that "one more iteration."
    Attachments:
    timing.vi ‏15 KB

    One of the problems is that your VI is not able to "breathe" because it is sometimes trapped inside inner loops that consume all CPU and step on each others toes. All you need is an single outer loop and a few shift registers.
    May of your specifications are still not clear, for example what should happen to LED 1&2 in case #3? Should they remain in the state they are in, or should they turn off, for example.
    Here is a simple rewrite that spins the outer loop at a regular rate, has no inner loop, and does not need any local variables or value property nodes. See if it makes sense. Also note that your code can be simplified dramatically by using arrays. Since the stop button is read with each of the regular interations, we don't need to worry about sequencing.
    Most likely you need to do a few simple modofications, because your specs are not clear.
    LabVIEW Champion . Do more with less code and in less time .
    Attachments:
    timingMODCA.vi ‏15 KB

  • Timing with while loop

    Hello,
    How can I do a time with while loop?. I want to read a data in the While- Loop for 1 sec and then go to B .. I added a pic,
    Attachments:
    while- loop.GIF ‏6 KB

    nichts wrote:
    Hello,
    How can I do a time with while loop?. I want to read a data in the While- Loop for 1 sec and then go to B .. I added a pic,
    I would use as GerdW has mentioned,"elapsed time.vi" in a statement 1st case structure, after set time has elapsed> goto 2nd case structure. try not to use flat sequences....this can be done with case statements with transitional coding. I have noticed young LV programmers like to use flat sequences...I think it's a trap set up by LV developers? 

  • Problem with while loop in thread: starting an audiostream

    Hello guys,
    I'm doing this project for school and I'm trying to make a simple app that plays a number of samples and forms a beat, baed on which buttons on the screen are pressed, think like fruity loops. But perhaps a screenshot of my unfnished GUI makes things a bit more clear:
    [http://www.speedyshare.com/794260193.html]
    Anyway, on pressing the play button, I start building an arraylist with all the selected samples and start playing them. Once the end of the "screen" is reached it should start playing again, this is the while loop:
    public void run(){
            //System.out.println("Wavfiles.size =" + getWavfiles().size());
            System.out.println(repeatperiod);
            if (getWavfiles() == null) {
                System.out.println("Error: list of Wavfiles is empty, cannot start playing.");
            else{
                if(!active) return;
                while(active){
                    System.out.println("Wavfiles.size =" + getWavfiles().size());
                    for (int i=0; i<getWavfiles().size(); i++){
                        Wavplayer filePlayer = new Wavplayer(getWavfiles().get(i).getStream());
                        Timer timer = new Timer();
                        //timer.scheduleAtFixedRate(filePlayer, getWavfiles().get(i).getStartTime(),repeatperiod);
                        timer.schedule(filePlayer, getWavfiles().get(i).getStartTime());
                    try {
                        Thread.sleep(repeatperiod);
                    } catch (InterruptedException ex) {
                        Logger.getLogger(LineBuilder.class.getName()).log(Level.SEVERE, null, ex);
        }But once the second iteration should begin, I'm getting nullpointerexceptions. These nullpointerexceptions come exactly when the second period starts so I suppose the sleep works :-) The nullpointerexception comes from the wavfile I try to play. Wavfile class:
    package BeatMixer.audio;
    import java.io.ByteArrayInputStream;
    import java.io.IOException;
    import java.util.TimerTask;
    import javax.sound.sampled.AudioFormat;
    import javax.sound.sampled.AudioInputStream;
    import javax.sound.sampled.AudioSystem;
    import javax.sound.sampled.DataLine;
    import javax.sound.sampled.LineUnavailableException;
    import javax.sound.sampled.SourceDataLine;
    import javax.sound.sampled.UnsupportedAudioFileException;
    public class Wavplayer extends TimerTask {
            private SourceDataLine auline;
            private AudioInputStream audioInputStream;
         private final int EXTERNAL_BUFFER_SIZE = 524288; // 128Kb
         public Wavplayer(ByteArrayInputStream wavstream) {
              try {
                   audioInputStream = AudioSystem.getAudioInputStream(wavstream);
              } catch (UnsupportedAudioFileException e1) {
                   e1.printStackTrace();
                   return;
              } catch (IOException e1) {
                   e1.printStackTrace();
                   return;
                    AudioFormat format = audioInputStream.getFormat();
              DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);
                    try {
                   auline = (SourceDataLine) AudioSystem.getLine(info);
                   auline.open(format);
              } catch (LineUnavailableException e) {
                   e.printStackTrace();
                   return;
              } catch (Exception e) {
                   e.printStackTrace();
                   return;
        @Override
         public void run() {
                    System.out.println(auline);
              auline.start();
              int nBytesRead = 0;
              byte[] abData = new byte[EXTERNAL_BUFFER_SIZE];
              try {
                   while (nBytesRead != -1) {
                        nBytesRead = audioInputStream.read(abData, 0, abData.length);
                        if (nBytesRead >= 0)
                             auline.write(abData, 0, nBytesRead);
              } catch (IOException e) {
                   e.printStackTrace();
                   return;
              } finally {
                   auline.drain();
                   auline.close();
    }auline is null on second iteration, in fact, getAudioInputStream doesn't really work anymore, and I don't know why because I don't change anything about my list of wavfiles as far as I know... Any thoughts or extra info needed?
    Edited by: Lorre on May 26, 2008 12:22 PM

    Is my question not clear enough? Do you need more info? Or is nobody here familiar with javax.sound.sampled?
    Edited by: Lorre on May 26, 2008 2:07 PM

  • Help needed with while loops please :)

    I'm beginning to study java at School.
    My assignment using while loops, to ask user to input 2 numbers.
    I have to output all odd number between the two.
    I have to output the sum of all even numbers between the two.
    Output all the numbers and their squares between 1-10.
    Output the squares of the odd numbers between the 2 numbers the user entered.
    Output all uppercase letters.
    If anyone can give me any help, I would appreciate it greatly.
    Thank you.
    Kelly.

    It would help if you put aside your code, and wrote out some pseudo-code first so that you understand the steps you will need to take. for example
    get input from user
    set counter to first number entered
    while counter less than/ equal to second number
          check if number is even
               if even, add to even_sum
               else output counter, along with its square
          increment counter by one
    end while
    output sum of evensthat block, when coded, will solve 3 of the problems, the other 2 will require separate loops
    Good Luck

  • Need help with while loop format

    I'm building a form - everything works but I would like to change the way the data is output into the table.
    In other scripting languages, like PHP, you had 2 different ways of dealing with a loop:
    <?
    do while xyz
    do something here
    ?>
    - OR -
    <? do while xyz:?>
    do something here
    <?end while ?>
    I would like to do something similar to the 2nd example in .jsp but I'm not sure of the format or how to stop the loop. From the tutorial, I'm using
    <%
    while(SQLResult.next())
    UId = SQLResult.getString("uid");
    FName = SQLResult.getString("fname");
    LName = SQLResult.getString("lname");
    out.println("<tr><td>" + UId + "</td><td>" + FName + "</td><td>" + LName
    + "</td></tr>");
    %>
    Could anyone point me in the right direction? I'd prefer it if I didn't have to build the table like this if I don't have to but haven't found anything anywhere telling me otherwise.
    Thanks so much.
    Bob

    Sorry - the answer was in JSP:Java Server Pages by Barry Burd. I had just gotten the output format wrong.

  • Problem with While Loop.

    Hi guys,
    i'm doing a pass exam java question, below is the question criteria.
    Write a program that allows a user to enter their mark attained in each unit and displays their grade. After all marks are entered the average mark is displayed.
    The main method should:
    Prompt the user to enter the number of units taken (check for NumberFormatException)
    Write a for loop to repeat for each subject, where each iteration
    Prompts the user to enter a mark ( a double) for unit 1, unit 2 etc. This should be in a while loop so if mark entered is less than 0 or greater than 100 the prompt will be repeated.
    Pass the mark to a method called getGrade.
    Display the returned grade
    Accumulate each mark
    Print the average mark to 2 decimal places
    The getGrade method should:
    Accept the parameter passed from the main method
    Determine the grade according to the following scale
    Return the grade
    The words that i highlighted in bold is the criteria.
    As you can see from the above question, i create an array , even though the question does not prompt me to create as what i know from tackling JavaQuestions "if it does not prompt me to add a criteria, it is ok to add it" :)
    below is my program code , in which the result i get is the same as the question result. BUT, from the above question it ask me to add a while loop, so if mark entered is less than 0 or greater than 100 the prompt will be repeated.
    But instead i use a do loop. :(
    so can anyone help me or show me how to create the while loop for mark entered is less than 0 or greater than 100 the prompt will be repeated, from my program code below. cause i want to know whether it possible to have a while loop instead of do loop for the my program and the while loop can work with an array criteria.
    thanks
    htw.
    import javax.swing.*;
    import java.text.DecimalFormat;
    public class Mark
        public static void main (String [] args)
            String unitStr;
            String markEnterStr;
            int validUnit;
            double total = 0;
            boolean validInput = true;
            DecimalFormat fmt = new DecimalFormat("#0.00");
            while (validInput)
            unitStr = JOptionPane.showInputDialog(null,"Enter number of units: ");
            try
            validUnit = Integer.parseInt(unitStr);
            double[] markArray = new double[validUnit];
            validInput = false;
            for (int index = 0;index < validUnit; index++)
                do
                markEnterStr = JOptionPane.showInputDialog("Please enter mark " +(index+1) +":");           
                markArray[index] = Double.parseDouble(markEnterStr);
                while(markArray[index] < 0 || markArray[index] >100);
                String correctMark = getGrade(markArray[index]);
                System.out.println(correctMark);
                total = total + markArray[index];       
            double average = (double)total / validUnit;
            System.out.println("Average = " +fmt.format(average));                   
            catch (NumberFormatException e)
            public static String getGrade(double x)
                String grade;
                if (x < 50)
                grade = "Fail";
                else if (x < 60)
                grade = "Pass";
                else if (x < 70)
                grade = "Credit";
                else if (x < 80)
                grade = "Distinction";
                else grade = "High distinction";
                return grade;
    }

    Hope u got it.
               markArray[index] = -1;
                while(markArray[index] < 0 || markArray[index] >100);
                markEnterStr = JOptionPane.showInputDialog("Please enter mark " +(index+1) +":");           
                markArray[index] = Double.parseDouble(markEnterStr);
                }VJ

  • SubVI with while loop + event structure not working in multi tab VI

    Hello Everyone,
    I am developing an interface for the control of a prober using Labview 2012, and I am stuck with some issue.
    To start with I provide you with a simplified version of my control interface VI, and with the sub-VI used to build and manage the wafer maps.
    The VI consists of several tabs: Prober Initialization, Wafer Handling, Wafer Map, Status, Error.
    The sub-VI can:
    1/ initialize the grid to display the map (sub VI Init Grid not provided here)
    2/ import XY coordinates from a txt file (sub VI Wafer Map Import)
    3/ display the coordinates and index of the die below the cursor
    4/ and when a die position is double clicked, and the boolean "Edit Wafer Map" is true, then the user can change the state (color) of the die between On-wafer die and Selected Die
    My issue:
    If I use the sub-VI by itself, it works fine. However when I use it as a sub-VI in the tab "Wafer Map", the map does not build up and I can no further use the embedded functionalities in the sub-VI.
    I suspect the while loop + event structure of the sub-VI to be the bottleneck here.
    However I don't know which way to go, that's why I'd be glad to have some advice and help here.
    Thank you.
    Florian
    Solved!
    Go to Solution.
    Attachments:
    Control Interface.zip ‏61 KB

    Hi NitzZ,
    Thank you for your reply.
    I tried to save the VIs in LV10, please tell me if you can open them now.
    Inside he event structure there is quite some code, and since I don't want to make the main vi too bulky, I would like to keep it as a sub-VI. 
    As you can see from the sub-VI, the event structure is used for extracting cursor position and tracking the double click action. These events are linked, through a property node, to the image "Wafer Map" which is passed to the main vi through connector pane.
    All values are passed this way as well (through connector pane). Is there another way?
    Maybe "refnum", but I don't really understand how to use them...
    If I use the event structure in the main vi, the wafer map is still not working. I tried it earlier.
    To implement the multi tab front panel, I used a tab control, and a for loop + case structure. For each element of the case structure, there is a corresponding action.
    For the case where I put the code (element=2) for Wafer Map, I also control the execution of the code with a case structure activated by the button "REFRESH". Otherwise I end up with a freezing of the panel right after the start.
    I hope these comments help you understand better.
    Regards,
    Florian
    Attachments:
    Control Interface.zip ‏104 KB

  • Need help with while loops

    Hello let me first explain what im trying to achive:
    I want a moving square that you control with the arrow keys on the keyboard. It has to be smooth ie able to move fast without looking like its jumping and it has to be able to move diagonaly aswell. Think of that arcade game Raiden ...you know the birds-eye view plane flying game...another thing! I'd prefer if it didnt use timers - i made one already using 4 timers and it works great but 4 timers is a little extreme - SO NO TIMERS !
    I was thinking while loops, but i cant seem to get it working. I dont want to put in all the code so ill just say that I have 4 booleans: up, down, left right and the following code:
    public void keyPressed(KeyEvent e) {
    if (e.getKeyCode() == KeyEvent.VK_UP) {
    up = true;
    if (e.getKeyCode() == KeyEvent.VK_DOWN) {
    down = true;
    if (e.getKeyCode() == KeyEvent.VK_LEFT) {
    left = true;
    if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
    right = true;
    repaint();
    For the KeyReleased part i have the same as above exept it sets the booleans to false.
    Soooo in theory if i set up a while loop like this (using the up direction as an example) :
    while (up == true) {
    [move square up]
    So therefore when i press and hold the up arrow the loop will keep going untill i realease it right? WRONG ! it just keeps repeating indefinatly and it doesnt even do the " [move square up] " bit. I put a System.out.print in the loop to test and it kept printing out the message but it still didnt do the actual " [move square up] " bit.
    Im not sure if im putting the while loop in the right place either....If anyone has any idea on how to use while loops in this way please heeeelp ! Its so annoying because it just doesnt work ive tried so many ways...
    any help would be greatly apreciated !!!!

    Maybe you want something like this? You have to pause during the loop to allow for other events to happen, like if y ou release a key or whatever.
    while( true )
       if( up ) moveUp();
       else if( down ) moveDown();
       if( left ) moveLeft();
       else if( right ) moveRight();
       try
          Thread.currentThread().sleep(10);
       catch( InterruptedException e )
          System.out.println( "Thread interrupted!");
    }

  • Running java process in a while loop using Runtime.exec() hangs on solaris

    I'm writting a multithreaded application in which I'll be starting multiple instances of "AppStartThread" class (given below). If I start only one instance of "AppStartThread", it is working fine. But if I start more than one instance of "AppStartThread", one of the threads hangs after some time (occasionaly). But other threads are working fine.
    I have the following questions:
    1. Is there any problem with starting a Thread inside another thread?. Here I'm executing the process in a while loop.
    2. Other thing i noticed is the Thread is hanging after completing the process ("java ExecuteProcess"). But the P.waitFor() is not coming out.
    3. Is it bcoz of the same problem as given in Bug ID : 4098442 ?.
    4. Also java 1.2.2 documentation says:
    "Because some native platforms only provide limited buffer size for standard input and output streams, failure to promptly write the input stream or read the output stream of the subprocess may cause the subprocess to block, and even deadlock. "
    I'm running this on sun Solaris/java 1.2.2 standard edition. If any of you have experienced the same problem please help me out.
    Will the same problem can happen on java 1.2.2 enterprise edition.?
    class AppStartThread implements Runnable
    public void run()
    while(true)
    try
    Process P=Runtime.getRuntime().exec("java ExecuteProcess");
    P.waitFor();
    System.out.println("after executing application.");
    P.destroy();
    P = null;
    System.gc();
    catch(java.io.IOException io)
    System.out.println("Could not execute application - IOException " + io);
    catch(java.lang.InterruptedException ip)
    System.out.println("Could not execute application - InterruptedException" + ip);
    catch (Exception e)
    System.out.println("Could not execute application -" + e.getMessage());

    I'm writting a multithreaded application in which I'll
    be starting multiple instances of "AppStartThread"
    class (given below). If I start only one instance of
    "AppStartThread", it is working fine. But if I start
    more than one instance of "AppStartThread", one of the
    threads hangs after some time (occasionaly). But other
    threads are working fine.
    I have the following questions:
    1. Is there any problem with starting a Thread inside
    another thread?. Here I'm executing the process in a
    while loop.Of course this is OK, as your code is always being run by one thread or another. And no, it doesn't depend on which thread is starting threads.
    2. Other thing i noticed is the Thread is hanging
    after completing the process ("java ExecuteProcess").
    But the P.waitFor() is not coming out.This is a vital clue. Is the process started by the Runtime.exec() actually completing or does the ps command still show that it is running?
    3. Is it bcoz of the same problem as given in Bug ID :
    4098442 ?.
    4. Also java 1.2.2 documentation says:
    "Because some native platforms only provide limited
    ed buffer size for standard input and output streams,
    failure to promptly write the input stream or read the
    output stream of the subprocess may cause the
    subprocess to block, and even deadlock. "These two are really the same thing (4098442 is not really a bug due to the reasons explained in the doc). If the program that you are exec'ing produces very much output, it is possible that the buffers to stdout and stderr are filling preventing your program from continuing. On Windows platforms, this buffer size is quite small (hundreds of characters) while (if I recall) on Solaris it is somewhat larger. However, I have seent his behavior causing problem on Solaris 8 in my own systems.
    I once hit this problem when I was 'sure' that I was emitting no output due to an exception being thrown that I wasn't even aware of - the stack trace was more than enough to fill the output buffer and cause the deadlock.
    You have several options. One, you could replace the System.out and System.err with PrintStream's backed up by (ie. on top of) BufferedOutputStream's that have large buffers (multi-K) that in turn are backed up by the original out and err PrintStream's. You would use System.setErr() and System.setOut() very early (static initializer block) in the startup of your class. The problem is that you are still at the mercy of code that may call flush() on these streams. I suppose you could implement your own FilterOutputStream to eat any flush requests...
    Another solution if you just don't care about the output is to replace System.out and System.err with PrintStreams that write to /dev/nul. This is really easy and efficient.
    The other tried and true approach is to start two threads in the main process each time you start a process. These will simply consume anything that is emitted through the stdout and stderr pipes. These would die when the streams close (i.e. when the process exits). Not pretty, but it works. I'd be worried about the overhead of two additional threads per external process except that processes have such huge overhead (considering you are starting a JVM) that it just won't matter. And it's not like the CPU is going to get hit much.
    If you do this frequently in your program you might consider using a worker thread pool (see Doug Lea's Executor class) to avoid creating a lot of fairly short-lived threads. But this is probably over-optimizing.
    Chuck

  • Problems with opening file with while loop

    Greetings everyone,
      This is probably a quick question, but I am familiarizing myself how to open data files in Labview. The attached code works if you enter a file from the folder button on the front panel. However, if the path is blank and you hit the run (arrow) button, a dialog box comes up and asks for the file.
       I select the file, but the dialog box keeps coming up. I think this has something to do with my while loop. Can anyone tell me where I am going wrong?
      Thanks!
       TheLT
    Solved!
    Go to Solution.
    Attachments:
    ReadingfromData.vi ‏27 KB

    TheLT,
    1. crossrulz was right. The Read FromSpreadsheet File.vi opens and closes the file each time it is called. If no file path is present at the input when it is called, it will pop up a file dialog.
    2. LabVIEW uses a dataflow paradigm. In your program the effect of this is that the File path control is read almost immediately when the program is started and never again after that. So, if the program is already running when the file is selected in that control, the new value is never read and the value (empty) in the control when the rpogram started is used.
    3. The fix is to use an event structure with a file path Value Changed event to detect when the control has a value entered and then read the file.
    4. Sequence structures obscure code, make it difficult to modify and extend code, and can almost always be eliminated by effective use of dataflow.  Local variables should not be used just to pass data around.  Wire is always the best way when possible. In your program adding a few wires allows elimination of the sequence structure and the local variables.
    5.  Your graph loop should have some kind of delay or wait.  No need for it to run as fast as the processor will allow - and to hog all the CPU time - to repeatedly put the same data onto the graph.  This is another place where an event structure is appropriate. Only update the graph when the X-Axis or Y-Axis selections have changed. Note: Accepted best practice is to use only one event structure in a program, although there are a few advanced cases where multiple event structures are appropriate.  You only need one.
    6. If the slected file does not contain the "endheader" string, the program will never stop.  Add a test for EOF to stop the program if the End of File is reached without finding the flag.
    Lynn
    Attachments:
    ReadingfromData.2.vi ‏27 KB

  • Problem with while loops, please help!

    I am having quite a bit of trouble with a program im working on. What i am doing is reading files from a directory in a for loop, in this loop the files are being broken into words and entered into a while loop where they are counted, the problem is i need to count the words in each file seperately and store each count in an array list or something similar. I also want to store the words in each file onto a seperate list
    for(...)
    read in files...
         //Go through each line of the first file
              while(matchLine1.find()) {
                   CharSequence line1 = matchLine1.group();
                   //Get the words in the line
                   String words1[] = wordBreak.split(line1);
                   for (int i1 = 0, n = words1.length; i1 < n; i1++) {
                        if(words1[i1].length() > 0) {
                             int count= 0;
                                           count++;
                             list1.add(words1[i1]);
              }This is what i have been doing, but with this method count stores the number of words in all files combined, not each individual file, and similarly list1 stores the words in all the files not in each individual file. Does anybody know how i could change this or what datastructures i could use that would allow me to store each file seperately. I would appreciate any help on this topic, Thanks!

    Don't try to construct complicated nested loops, it makes things a
    tangled mess. You want a collection of words per file. You have at least
    zero files. Given a file (or its name), you want to add a word to a collection
    associated with that file, right?
    A Map is perfect for this, i.e. the file's name can be the key and the
    associated value can be the collection of words. A separate simple class
    can be a 'MapManager' (ahem) that controls the access to this master
    map. This MapManager doesn't know anything about what type of
    collection is supposed to store all those words. Maybe you want to
    store just the unique words, maybe you want to store them all, including
    the duplicates etc. etc. The MapManager depends on a CollectionBuilder,
    i.e. a simple thing that is able to deliver a new collection to be associated
    with a file name. Here's the CollectionBuilder:public interface CollectionBuilder {
       Collection getCollection();
    }Because I'm feeling lazy today, I won't design an interface for a MapManager,
    so I simply make it a class; here it is:public class MapManager {
       private Map map= new HashMap(); // file/words association
       CollectionBuilder cb; // delivers Collections per file
       // constructor
       public MapManager(CollectionBuilder cb) { this.cb= cb; }
       // add a word 'word' given a filename 'name'
       public boolean addWord(String name, String word) {
          Collection c= map.get(name);
          if (c == null) { // nothing found for this file
             c= cb.getCollection(); // get a new collection
             map.put(name, c); // and associate it with the filename
          return c.add(word); // return whatever the collection returns
       // get the collection associated with a filename
       public Collection getCollection(String name) { return map.get(name); }
    }... now simply keep adding words from a file to this MapManager and
    retrieve the collections afterwards.
    kind regards,
    Jos

  • Trouble with while loop, not sure what to put in it in my project

    I'm making a class to a simple command line craps game. I must use a while loop to implement craps rules. The rules that i was given are:
    if your first roll is a 4, 5, 6, 8, 9, or 10, you roll again until either you get a 7 (you lose) or you get the number from your first roll. (i thought 7 or 11 wins, like in the next example)
    yeah, thats right, not very good directions. The first directions i had for a different way of doing it using if and else statements were:
    The player rolls the two dice.
    If the sum of the resulting die values is 7 or 11, the player wins.
    If the sum is 2, 3, or 12, the player loses.
    If something else is rolled, the player has to roll again to determine the outcome.
    If the sum of the second roll is the same as what the player rolled the first time, the player wins. Otherwise the player loses.
    (You might get a pair of dice and play a few rounds to try it.)
    here's my code that i have so far for my craps class, in the middle section, i have previous code that i used for if else statements, that is what im trying to replace: package games;public class Craps {
    private Dice dice1;
    private Dice dice2;
    private int gamesPlayed;
    private int gamesWon;
    private boolean lastGameWon;
    private boolean gameOver;
    private int firstRoll;
    private int secondRoll;
    public Craps() {
    dice1 = new Dice(6);
    dice2 = new Dice(6);
    gamesPlayed = 0;
    gamesWon = 0;
    lastGameWon = false;
    firstRoll = 1;
    secondRoll = 2;
         //returns firstroll
    public int getFirstRoll(){
    return firstRoll;
         //returns secondroll
    public int getSecondRoll(){
    return secondRoll;
    public int getGamesPlayed(){
    return gamesPlayed;
    public int getGamesWon(){
    return gamesWon;
    public boolean lastGameWon(){
    return lastGameWon;
         public int nextSum()
         dice1.roll();
         dice2.roll();
         return dice1.getSideUp() + dice2.getSideUp();
    public void play()
              firstRoll = nextSum();
    if (firstRoll == 7 || firstRoll == 11)
              gameOver = true;
              gamesWon++;
              if (firstRoll == 2 || firstRoll == 3 || firstRoll == 12)
              gameOver = true;
                   else{
                   gameOver = false;
              while (gameOver == false)
              secondRoll++;
    public String toString()
    return "games - " + gamesPlayed + ", won - " + gamesWon + ", last game won - " + lastGameWon + " First Roll - " + firstRoll +
    ", Second Roll - " + secondRoll;
    i'm really confused on how to get the while loop will keep starting the game over if it is false, am i using the right approach? Also i have to use a while loop, its for a school project.
    thanks.

    The code you asked for could be:
    package games;
    public class Craps {
        private Dice dice1;
        private Dice dice2;
        private int gamesPlayed;
        private int gamesWon;
        private boolean lastGameWon;
        private boolean gameOver;
        private int firstRoll;
        private int secondRoll;
        public Craps()
            dice1 = new Dice(6);
            dice2 = new Dice(6);
            gamesPlayed = 0;
            gamesWon = 0;
            lastGameWon = false;
            firstRoll = 1;
            secondRoll = 2;
         //returns firstroll
        public int getFirstRoll(){
            return firstRoll;
         //returns secondroll
        public int getSecondRoll(){
            return secondRoll;
        public int getGamesPlayed(){
            return gamesPlayed;
        public int getGamesWon(){
            return gamesWon;
        public boolean lastGameWon(){
            return lastGameWon;
        public int nextSum()
            dice1.roll();
            dice2.roll();
            return dice1.getSideUp() + dice2.getSideUp();
        public void play() {
            gamesPlayed++;
            firstRoll = nextSum();
            if (firstRoll == 7 || firstRoll == 11)
                gamesWon++;
                lastGameWon = true;
            else if (firstRoll == 2 || firstRoll == 3 || firstRoll == 12)
                lastGameWon = false;
            else
               secondRoll = nextSum();
               if (firstRoll == secondRoll)
                  gamesWon++;
                  lastGameWon = true;
               else
                  lastGameWon = false;
        public String toString()
            return "games - " + gamesPlayed + ", won - " + gamesWon + ", last game won - " + lastGameWon + " First Roll - " + firstRoll +
                    ", Second Roll - " + secondRoll;
    }I'm not sure of craps rules, the code above makes a first roll and if game isn't won or lose at once (7 and 11 wins, 2,3 or 12 lose) a second roll is done. If the second roll is equals to the first made then the game is won else the game is lose. Is it right?

  • Iteration non sequencial with While Loop

    I've a SubVi in while Loop. Iteration n+1 will execute when Iteration n finish.
    Can I execute this SubVi in paralel (no sequencial)?
    In Spanish:
    Tengo una SubVi dentro de un bucle while. Pero este bucle actúa de forma secuencial. No se cargará la iteración n+1 hasta que la n acabe.
    ¿Cómo puedo hacer para que se ejecuten las iteraciones de forma no secuencial? Es decir, que no haya que espera a que acabe una para que se ejecute la siguiente.

    Hello,
    it is not possible. The while loop works as follows: 1) execute the code inside 2) check the ternimation condition 3) depending on that, continues with the following iteration or exit from the while loop. So, it is not possible what you are asking for.
    Maybe you have to use two while loops.
    Regards
    rusC

Maybe you are looking for