How to use the random generator in java

hey peeps, this is the class in which i am trying to implement the random generator in;
public class Matchlist
    private studentdetails sd = new studentdetails();
    /** matchList StringBuilder stores the match list in progress */
    private StringBuilder matchList = new StringBuilder();
    private int loop = 0;
    private int matches = 0;
    public Matchlist()
        sd.createstudentdetails();
    /** Method to create the actual match list, returns the list as a string */
    public String CreateMatch()
        int g;
        int y;
            for (g = 0; g < 4; g++)//g = game
                for (y = 17; y > -1; y--)//y = green house
                    /** Check to see if the game is empty */
                    if (sd.getgh(y).getGame(g).equalsIgnoreCase(""))
                        for (int x = 0; x < 18; x++) //x = yellow house
                            if (sd.getyh(x).getGame(g).equalsIgnoreCase(""))
                                if (sd.getgh(y).getC_lass() != sd.getyh(x).getC_lass())
                                    /** Check to see if the person has played the other person */
                                    if (sd.getgh(y).checkPlayed(sd.getyh(x).getName()) == false)
                                        /** Set the game to the name of the opponent played */
                                        sd.getyh(x).changeGame(g, sd.getgh(y).getName());
                                        sd.getgh(y).changeGame(g, sd.getyh(x).getName());
                                        /** Build the match list step by step using append with \n at the end to create a new line */
                                        matchList.append(sd.getyh(x).getName() + " vs " + sd.getgh(y).getName() + "\n");
                                        matches++;
                                        break;
            /** Convert the stringbuilder into an actual string, then return it */
            String completeMatchList = matchList.toString();
            System.out.println(matches);
            for (int i = 0; i <18; i++)
                sd.getyh(i).getEmptyMatches();
                sd.getgh(i).getEmptyMatches();
            return completeMatchList;
    }what i dont understand is how to implement it to pick my matches at random using the http://java.sun.com/j2se/1.4.2/docs/api/java/util/Random.html java tutorials from here
regards

How to use Random ?
First you open API then you read it, then you use it.
You mention you try to use it but i just see a horrible nested for for for if if if loop.
Restructure code and question and maybe it makes more sense.
Edited by: pgeuens on 10-mrt-2008 22:58

Similar Messages

  • How to use the TCP/IP in Java?Thanks!

    How to use the TCP/IP in Java?Thanks!

    Look at the java.net package, more specifically to classes ServerSocket (The server TPC conection) and Socket (the client TCP conection)
    Abraham

  • How to use the program "Generate test data for BAI bank statement" ?

    Hi all,
    I use the program RFEBKAT5 to create an Electronic Bank Statement file in BAI format ,but it doesn't generate the file .
    I don't know how to generate the file.
    Please help me !
    Thanks all !

    You need to suitably adjust your GL accounts for "Posting Offset Account" (Whisch is defaulted as ++++++++19" and Checkout/Funds Out/Funds IN GL accounts to your configuration.
    Once you do this try generating the file again.

  • How to use the path generated by A star to guide the robot to move?

    I now know how to use A star path planning on Voronoi and I can run this program successfully.\  
    however, my problem now is how i can use the path data (generated by the A* path planning algorithm) to guide the robot to drive along this path?   well, i suppose i can get a series of dots (denoted by x and y coordinates) from the path, and use these dots to guide the robot ?  
    can anyone please help?  
     thank you very much
    Solved!
    Go to Solution.

    Ravens Fan wrote:
    You can't.
    My post above will point everyone to the other post so that we don't have people trying to assist you in two different places without knowledge of the other thread.
    thank you 

  • How to using the executable software in Java

    I got a software named: pdf to text convertor; which can format the text interface from the pdf, for example, you need add the page number with a4 paper, then the convertor can change the pdf into text with page numbers. it is running on the doc, the command like: c:\pdfconvertor\xpdfrc.exe "c:\filename\name.pdf", after the text file will exist in the same directory with the pdf file.
    so my problem is how to use java to call this DOS command to execute the program, and then java can read the text file, does some one give me some idea? better with simple java code!! Thanks very much! I will pay dollar for the solutions

    You can use:
    String[] cmd = {"c:\\pdfconvertor\\xpdfrc.exe", "c:\\filename\\name.pdf"};
    Process p = Runtime.getRuntime().exec(cmd);Wait for the process to finish:
    p.waitFor()and do your thing with the output file.
    Note there are mechanisms for capturing the input and output of the subprocess; see java.lang.Process javadoc.

  • How to use the Worklist API from Java (classpath ??)

    Hi all,
    Sorry for a novice question but I couldn't find the way to go about this (probably because it's such common knowldge...)
    I would like to try and use the Worklist API from my Java code in Eclipse, and according to the BPEL dev-guide I need to add an Import command for oracle.tip.pc.api.worklist. Where do I find these classes ?????
    I guess I need to change my CLASSPATH but I couldn't find a single word about this in the BPEL dev-guide (chapter 17), BPEL installation guide or elseware.
    thanks.

    Hi all,
    Ok now.
    To summarize - I was trying the code from BPEL developer guide, chapter 17, page 40 for using the Worklist local API's.
    Only after adding the following JAR's to the build path, was I able to compile it:
    orabpel-common.jar
    orabpel.jar
    bpm-infra.jar
    bpm-services.jar
    So, these 4 JAR's are required for using the Worklist local API's (not a clue in the dev guide itself for this requirement though...)
    Thank you very much for your help,
    assaf.

  • How to use the Rc4DLL.dll with java (jre1.4 )

    I am not able to use Rc4DLL.dll with java, there are some characters (encrypted using Rc4DLL.dll) that java is not able to identify. So while decrypting in java using Rc4DLL I am not getting the desired output (as some character java tries to decrypt are not supported with java). Could some one give a solution of using Rc4DLL with java jre 1.4

    RC4 cipher is supported by 1.4.
    And surely you can turn a link to the 1.5.0 JCE Reference Guide into a link to the 1.4.2 Reference Guide? I did. Took me 5 seconds to check that. As opposed to wasting a day and a half in forums like you just did.

  • How to use the result from a taglib?

    Hi people.
    I've been looking arround for some feedback on how to use the output generated by a taglib on jsp code but I haven't been able to find any.
    Could somebody tell me how to do that please?

    It works something like this:
    The tab library consists of a class library and a tag libraray descriptor file. In your jsp header you include a taglib directive which associated athe TLD with a particular name prefix. Then you can include XML tags with that prefix and the tag library class to which they are connected will be invoked from the servlet that is generated from the JSP. This tag code can do pretty much anything, but usually what it mostly does is write HTML to the response stream. Opening tags and closing tags can both add whatever text they like to the stream which is sent to the client.
    So including the tag in you JSP will usually suffice to cause generated output, it's up to the taglib.

  • How to use the java class created by  "CONTIVO" as web sevrvice?

    Hi All,
    We are creating the java class by the Contivo mapping tool, how to use that class as a web serivce?
    Very thankful if anyone gives some light on this.
    Thanks in advance.....
    rgds,
    Rajeev Pariyadathu

    com.contivo.runtime.dom.Transform
    Transform.transform(     "Transform_HotelAvailRQ_",file1, file2);, like this we can use the contivo generated class

  • How to Use the JAVA SCRIPT code in .htm page of the component

    Hi .
    In my requirement i have to use Java Script Function in .htm code ..how to use the java script code and functions in .htm???
    thank you
    B.Mani

    Check this document  [Arun's Blog|http://wiki.sdn.sap.com/wiki/display/CRM/CRMWebClientUI-TalkingwithJava+Script]
    Regards
    Kavindra

  • How to use the Java embedding activity in BPel

    hi all,
    How to use the java embedding activity in BPEL
    pls can u provide sample example

    1 Use [Oracle BPEL Process Manager Client Java API Reference|http://download-uk.oracle.com/docs/cd/B31017_01/integrate.1013/b28986/overview-summary.html] and especially [com.collaxa.cube.engine.ext|http://download-uk.oracle.com/docs/cd/B31017_01/integrate.1013/b28986/com/collaxa/cube/engine/ext/BaseBPELXExecLet.html]
    Instead of System.Out.println use addAuditTrailEntry(java.lang.String message)
    2. If you want to import a package write in code (Source View) of bpel process
    +<bpelx:exec import="package_name"/>+ for example +<bpelx:exec import="java.util.regex.Matcher"/>+
    example 1:
    String bodyAsString;
    StringBuffer myStringBuffer = new StringBuffer();
    try {
    bodyAsString = (String)getVariableData("BodyString");
    addAuditTrailEntry("bodyAsString1: "+ bodyAsString);
    Pattern pattern = Pattern.compile("goodDay");
    Matcher matcher= pattern.matcher(bodyAsString);
    while (matcher.find()) {   
    matcher.appendReplacement(myStringBuffer, "shitDay");
    matcher.appendTail(myStringBuffer);
    bodyAsString = myStringBuffer.toString();
    addAuditTrailEntry("bodyAsString2: "+ bodyAsString);
    } catch (Exception ex) {
    addAuditTrailEntry("Failed+bodyAsString",ex.getMessage());
    I put in code (Source View) the following
    <bpelx:exec import="java.util.regex.Matcher"/>
    <bpelx:exec import="java.util.regex.Pattern"/>
    example2:
    Object temp;
    try {
    temp = ((XMLElement)getVariableData("inputVariable","payload","/ns2:FiscalisMessage/ns2:Body")).getChildNodes().item(1);
    setVariableData("AdjReceipt",temp);
    addAuditTrailEntry("ok",temp.toString());
    catch (Exception ex) {
    addAuditTrailEntry("Failed :",ex);
    I put in code (Source View) the following
    <bpelx:exec import="oracle.xml.parser.v2.XMLElement"/>

  • How to use the DLLs which created from c++ in Java?

    And How to use the DLLs which created from JNI in C++?

    Huh?
    Are you asking how to do JNI - you should read the tutorial.
    Are you asking how to load it - then use System.loadLibrary()
    Are you asking what to do with the output from javah - put it in a C file and write some code, compile it into a dll.

  • JNI - How to use the error reporting mechanism?

    I've developed a C++ DLL which is loaded from a commercial Win32 application (not written by me) as a plug-in for external calculations. On its initialization the C++ DLL launches the Java VM via the JNI invocation interface. When the DLL functions are called by the application, they forward the calls to Java objects inside the Java VM, again via JNI invocation interface.
    This works well, but I have encountered a weird error.
    From Java I open a JFrame containing a JTextArea as small console for debug output messages. If I turn output to this debug console off (my printToConsole routine checks whether a boolean flag is set), the string concatenation operator may lead to a crash of the Java VM.
    For example, if in one of the Java functions called from the
    DLL via JNI invocation interface the following is the first statement,
    it leads to a crash of the Java VM and the application that loaded the C++ proxy DLL.
    String test=""+Math.random(); // String test not used later
    Interestingly, if I comment this statement out, the Java code works fine WITHOUT any crash. I've already thought about potential races and synchronization issues in my code, but I don't see where this is the case. And the string concatenation error fails as well, if I insert sleep() statements in front of it and at other places in the code. However, if I turn on log messages printed to my JFrame debug console (containing a JTextArea), the String concatenation works without problems.
    So maybe the JNI interface has a bug and affects the Java VM; I don't see where my JNI code is wrong.
    One problem is that I do not get any stdout output, as the C++ proxy DLL is loaded by the Windows application, even if I start the Windows application from the DOS command line (under Windows).
    Does anyone know how to use the error reporting mechanism?
    http://java.sun.com/j2se/1.4.2/docs/guide/vm/error-handling.html
    Is it possible that the JVM, when it crashes, writes debug information about the crash into a file instead of stdout/stderr?
    My C++ proxy DLL was compiled in debug mode, but the commercial application (which loaded the DLL) is very likely not.
    I do not know hot to find the reason why the String concatenation fails inside the Java function called from the C++ DLL via JNI.

    Yes, I've initially thought about errors in the C++ code too. But the C++ code is actually very simple and short. It doesn't allocate anything on the C++ side. It allocates a couple of ByteBuffers inside the Java VM however via JNI invocation interface calls of env->NewDirectByteBuffer(). The native memory regions accessed via the ByteBuffers are allocated not by my own C++ code, but by the program that calls my DLL (the program is Metastock).
    The interesting thing is that everything works fine if output to my debug console is enabled, which means that in the Java print routine getConsoleLoggingState() returns true and text is appended to the jTextArea.
    static synchronized void print(String str)
    { MetaStockMonitor mMon=getInstance();
    if ( mMon.getFileLoggingState() && mMon.logFileWriter!=null) {
    mMon.logFileWriter.print(str);
    mMon.logFileWriter.flush();
    if ( mMon.getConsoleLoggingState() ) {
    mMon.jTextArea1.append(str);
    Only if output to the JTextArea is turned off (ie. getConsoleLoggingState()==false), the crash happens when the FIRST statement in the Java routine called via JNI invocation interface is a (useless) String concatenation operation, as described above.
    String test=""+Math.random(); // String test not used later
    Moreover, the crash happens BEFORE the allocated ByteBuffer objects are accessed in the Java code. But again, if console output is turned on, it works stable. If console output is turned off, it works when the (useless) String concatenation operation is removed in the Java routine called from C++.
    I've already thought about potential races (regarding multiple threads), but this can be ruled out in my case. It almost appears as if the JVM can have problems when called by the invocation interface (I tested it with Java 1.4.2 b28).
    All the calls between C++ and Java go ALWAYS in the direction from C++ code to Java. Unfortunately, there is no special JRE version with extensive logging capabilities to facilitate debugging. And the problem is not easily reproducible either.
    JNIEnv* JNI_GetEnv()
    JNIEnv *env;
    cached_jvm->AttachCurrentThread((void**)&env,NULL);
    fprintf(logfile,"env=%i\n",env);
    fflush(logfile);
    return env;
    // function called by Metastock's MSX plug-in interface
    BOOL __stdcall createIndEngine (const MSXDataRec *a_psDataRec,
    const MSXDataInfoRecArgsArray *a_psDataInfoArgs,
    const MSXNumericArgsArray *a_psNumericArgs,
    const MSXStringArgsArray *a_psStringArgs,
    const MSXCustomArgsArray *a_psCustomArgs,
    MSXResultRec *a_psResultRec)
    a_psResultRec->psResultArray->iFirstValid=0;
    a_psResultRec->psResultArray->iLastValid=-1;
    jthrowable ex;
    jmethodID mid;
    JNIEnv* env=JNI_GetEnv();
    jobject chart=getChart(env, a_psDataRec);
    if ( chart==NULL) {
    return MSX_ERROR;
    jobject getChart (JNIEnv* env, const MSXDataRec *a_psDataRec)
    jthrowable ex;
    jmethodID mid;
    int closeFirstValid, closeLastValid;
    closeFirstValid=a_psDataRec->sClose.iFirstValid;
    closeLastValid=a_psDataRec->sClose.iLastValid;
    long firstDate, firstTime;
    if (closeFirstValid>=1 && closeFirstValid<=closeLastValid) {
    firstDate = a_psDataRec->psDate[closeFirstValid].lDate;
    firstTime = a_psDataRec->psDate[closeFirstValid].lTime;
    } else {
    firstDate=0;
    firstTime=0;
    jclass chartFactoryClass = env->FindClass("wschwendt/metastock/msx/ChartFactory");
    if (ex= env->ExceptionOccurred() ) {
    env->ExceptionDescribe();
    env->ExceptionClear();
    sprintf(sbuf, "DLL: Cannot find class ChartFactory\n");
    printSBufViaJava(sbuf);
    return NULL;
    mid = env->GetStaticMethodID(chartFactoryClass, "getInstance", "()Lwschwendt/metastock/msx/ChartFactory;");
    if (ex= env->ExceptionOccurred() ) {
    env->ExceptionDescribe();
    env->ExceptionClear();
    sprintf(sbuf, "DLL: Cannot find method ID for ChartFactory.getInstance()\n");
    printSBufViaJava(sbuf);
    return NULL;
    jobject chartFactory=env->CallStaticObjectMethod(chartFactoryClass, mid);
    if (ex= env->ExceptionOccurred() ) {
    env->ExceptionDescribe();
    env->ExceptionClear();
    sprintf(sbuf, "DLL: Exception while calling ChartFactory.getInstance()");
    printSBufViaJava(sbuf);
    return NULL;
    mid = env->GetMethodID(chartFactoryClass, "getChartID", "(Ljava/nio/ByteBuffer;Ljava/nio/ByteBuffer;Ljava/nio/ByteBuffer;Ljava/nio/ByteBuffer;IIIIIII)F");
    if (ex= env->ExceptionOccurred() ) {
    env->ExceptionDescribe();
    env->ExceptionClear();
    sprintf(sbuf, "DLL: Cannot find method ID for ChartFactory.getChartID()\n");
    printSBufViaJava(sbuf);
    return NULL;
    jobject symbolBuf=env->NewDirectByteBuffer(a_psDataRec->pszSymbol, strlen(a_psDataRec->pszSymbol) );
    if (ex= env->ExceptionOccurred() ) {
    env->ExceptionDescribe();
    env->ExceptionClear();
    sprintf(sbuf, "DLL: Cannot allocate symbolBuf\n");
    printSBufViaJava(sbuf);
    return NULL;
    jobject securityNameBuf=env->NewDirectByteBuffer(a_psDataRec->pszSecurityName, strlen(a_psDataRec->pszSecurityName) );
    if (ex= env->ExceptionOccurred() ) {
    env->ExceptionDescribe();
    env->ExceptionClear();
    sprintf(sbuf, "DLL: Cannot allocate securityNameBuf\n");
    printSBufViaJava(sbuf);
    return NULL;
    jobject securityPathBuf=env->NewDirectByteBuffer(a_psDataRec->pszSecurityPath, strlen(a_psDataRec->pszSecurityPath) );
    if (ex= env->ExceptionOccurred() ) {
    env->ExceptionDescribe();
    env->ExceptionClear();
    sprintf(sbuf, "DLL: Cannot allocate securityPathBuf\n");
    printSBufViaJava(sbuf);
    return NULL;
    jobject securityOnlineSourceBuf=env->NewDirectByteBuffer(a_psDataRec->pszOnlineSource, strlen(a_psDataRec->pszOnlineSource) );
    if (ex= env->ExceptionOccurred() ) {
    env->ExceptionDescribe();
    env->ExceptionClear();
    sprintf(sbuf, "DLL: Cannot allocate onlineSourceBuf\n");
    printSBufViaJava(sbuf);
    return NULL;
    // Java Function call leads to crash, if console output is turned off and
    // the first statement in the Java routine is a (useless) string concatenation.
    // Otherwise it works stable.
    jfloat chartID=env->CallFloatMethod(chartFactory, mid, securityNameBuf, symbolBuf,
    securityPathBuf, securityOnlineSourceBuf, (jint)(a_psDataRec->iPeriod),
    (jint)(a_psDataRec->iInterval), (jint)(a_psDataRec->iStartTime),
    (jint)(a_psDataRec->iEndTime), (jint)(a_psDataRec->iSymbolType),
    (jint)firstDate, (jint)firstTime );
    if (ex= env->ExceptionOccurred() ) {
    env->ExceptionDescribe();
    env->ExceptionClear();
    sprintf(sbuf, "DLL: Exception while calling ChartFactory.getChartID()");
    printSBufViaJava(sbuf);
    return NULL;

  • How to use a random number equal another number. (with my source code)

    hi, i'm having trouble with this assignment.
    3. Determine how many times a die must be rolled in order to
    win a prize. (This represents one trial.) Print this value to a
    text file.
    4. Conduct at least 1,000 trials.
    5. Read the data back in from all of the trials.
    6. Calculate the average number of times a die must be rolled in order to win a prize.
    7. Print the result to the screen
    This is what I have so far.
    But I get a "int cannot be dereferenced" error
    * Write a description of class BottleCapPrize here.
    * @author (your name)
    * @version (a version number or a date)
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.util.Scanner;
    import java.util.Random;
    import java.io.File;
    public class BottleCapPrize
    public static void main (String [ ] args) throws IOException
    PrintWriter outFile = new PrintWriter(new File("bah.txt"));
    Random randomGenerator = new Random();
    int random = randomGenerator.nextInt(5);
    int count = 0;
    for (int loop = 1; loop <= 1000; loop++)
    if(random.equals("3"))
    outFile.println("Congratulations, both pairs matched.");
    count++;
    outFile.close ( );
    }

    And the random generator can only choose a 1 or 2 or 3 or 4 or 5. This is then randomly chosen 1000 times like 400 2s and 200 5s for example.I think you have still to appreciate that the task is not to roll a dice 1000 times and see how many of each number you get.
    Tackle it one step at a time:
    3. A - Determine how many times a die must be rolled in order to win a prize. (This represents one trial.)
    B - Print this value to a text file.
    Even the first part of the problem can be broken down into two parts. I strongly suggest to get step 3A working correctly before you move any further. Notice that this step does not involve 1000 rolls of the dice. Rather it asks you to roll the dice as many times as needed until you get a three. Start there: write a method that does no more than report the number of times it had to roll the dice in order to get a three.
    import java.util.Random;
    public class BottleCapPrize
        public static void main (String [ ] args) throws IOException
            Random randomGenerator = new Random();
            int count = 0;
             * Your code here.
             * At the end of it count should be equal to the number of
             * dice rolls it took to get a three.
            System.out.println("It took " + count + "dice rolls to get a three");
    }Once you have this method working correctly - that is you run it lots of times and it agrees with what you find experimentally with an actual dice - then you can move on to saving this result to a file (step 3B). The steps of the assignment provide a framework that makes sense - follow them one at a time.
    but only thing is that the random number is all a certain number.That's a fairly major defect in a randomly generated number ;). Read the API documentation for the [nextInt(n)|http://java.sun.com/javase/6/docs/api/java/util/Random.html#nextInt(int)] method. It should be clear that this is the method that randomly generates a number. So if you want lots of randomly generated numbers (rather than one randomly generated number lots of times) then you have to call this method lots of times. A call to nextInt(n) is the programming equivalent to rolling a dice.

  • How to use the adapter framework sample_ra.

    hi..
    I have deployed the sample_ra adapter framework code through NWDS. Now how to use the adapter framework into my scenario.Please answer elaborately .How to call this adapter framework while configuring the communication channel.

    hi
    Follow these links I think it will helps you
    http://www.sap-hefte.de/download/dateien/1241/140_leseprobe.pdf
    NWDS and  generate java proxy
    http://help.sap.com/saphelp_nw2004s/helpdata/en/32/43d84072378031e10000000a1550b0/content.htm
    http://msdn2.microsoft.com/en-us/library/ms944509.aspx
    thanks and regards
    santosh

Maybe you are looking for

  • Problem while updating multiple records through standard RFC

    HI all, I am doing multiple  object updation using a standard RFC(BAPI_PROJECT_MAINTAIN). The RFC i am calling from Enterprise portal. I am sending data to RFC one by one. But the error i am getting is object is locked by user so data can't be save.

  • Error while Copy Item Category

    Dear Gurus, I'm facing a problem in SPRO. When I'm trying to copy Item Category "BVN" to a new one ie ZB14(for example) ,I gets an error stating that "Billing Plan Type is invalid". Could anyone please help me what is the reason for the error as well

  • Missing pointbase folder in my java sdk install

    Hello I downloaded j2ee v1.4. I set the environment variables correctly(those JAVA_HOME, JAVA_EE, %PB_TOOLS%, etc.) i tried asadmin start-domain domain1 and it's all ok. but when i run into command prompt: %PB_TOOLS%\startserver i got that the path c

  • Hide a data column in combo box?

    I want to load a combo box from a database with two values per row (add.Item ?) but I only want one value to be see by the end-user. Example: Hidden | Shown 12320  |  Green 19210  |  Red 72622  |  Yellow The user will see the colors but not the numer

  • Quicktime export still uses reference movie!

    I am trying to export a file to deliver to a client. It plays in QT player 7 fine--so I go to Export... and choose my settings, then click OK. Then I burn the resulting file to a DVD. When I try to play this file on another computer, I get an error s