Need help with random string arrays

Hi, I could really use some specific advice about how to randomize and display strings. I'm trying to create an applet that displays a list of 12 chores and a list of four people for whom the chores should be distributed to. So far I have set up the code to display the chores list in the first column and what I'm tring to do is then randomly assign each persons name 3 times in the second column. I'm not getting any error messages but the problem is that I can't seem to get the names to appear only 3 times.
// Random generator = new Random();
// JButton assignChores = new Button("Assign Chores")'
// JTextArea outputArea = new JTextArea("");
// ect....
public void actionPerformed(ActionEvent e) {
String[] chores = {"Living Room",
"Dining Room",
"Kitchen",
"Boy's Room",
"Garbage",
"Backyard",
"Pets",
"Front Bathroom",
"Back Bathroom",
"Laundry",
"Computer Room",
"Parent's Room"};
String[] person = {"Mom",
"Dad",
"Son",
"Daughter"};
int[] numIndex = new int[13];
String output = "Chores" + "\t" + "Person";
output += "\n________________________________\n";
// I feel relatively certain that a while statement should go
// here but I'm lost as to how I should go about this.
for (int i = 1; i < numIndex.length; i++) {
int arrayIndex = generator.nextInt(person.length); // generate a random number based on the number of people
output += "\n" + chores[numIndex[0]++] // display the chores list in column 1
+ "\t" + person[arrayIndex]; // then randomly display the names in column 2
output += "\n________________________________\n";
outputArea.setText(output);
JOptionPane.showMessageDialog (null, outputArea,
"Chores List", JOptionPane.INFORMATION_MESSAGE);
System.exit(0);

Hi,
Here's even a more elegant twist on the problem.
import java.util.*;
class FamilyMember
  private String name;
  private ArrayList chores;
  private final int MAX_CHORES = 3;
  public FamilyMember( String name )
    this( name, null );
  public FamilyMember( String name, Collection chores )
    this.name = name;
    setChores( chores );
  public String getName()
    return( name );
  public Collection getChores()
    return( chores );
  private void initArray()
    if( chores == null )
      chores = new ArrayList();
  public void setChores( Collection newChores )
    if( newChores != null )
      initArray();
      if( newChores.size() <= MAX_CHORES )
        Iterator it = newChores.iterator();
        while( it.hasNext() )
          chores.add( it.next() );
  public boolean addChore( String newChore )
    boolean outBool = false;
    initArray();
    if( chores.size() < MAX_CHORES )
      chores.add( newChore );
      outBool = true;
    return( outBool );
  public void setName( String newName )
    name = newName;
class Chore
  private String name;
  private boolean assigned;
  public Chore( String name )
    this.name = name;
  public String getName()
    return( name );
  public void setName()
    this.name = name;
  public void setAssigned( boolean newAssigned )
    assigned = newAssigned;
  public boolean isAssigned()
    return( assigned );
public class ChoreLister
  public static void main(String[] args)
    Chore[] chores = { new Chore( "Living Room" ),
                       new Chore( "Dining Room" ),
                       new Chore( "Kitchen" ),
                       new Chore( "Boy's Room" ),
                       new Chore( "Garbage" ),
                       new Chore( "Backyard" ),
                       new Chore( "Pets" ),
                       new Chore( "Front Bathroom" ),
                       new Chore( "Back Bathroom" ),
                       new Chore( "Laundry" ),
                       new Chore( "Computer Room" ),
                       new Chore( "Parent's Room" ) };
    FamilyMember[] fm = { new FamilyMember( "Mom" ),
                          new FamilyMember( "Dad" ),
                          new FamilyMember( "Son" ),
                          new FamilyMember( "Daughter" ) };
    Random generator = new Random();
    System.out.println( "Chores\tPerson" );
    System.out.println( "________________________________" );
    // Loop through all chores assigning them as we go.
    for( int j = 0; j < chores.length; ++j )
      int arrayIndex = generator.nextInt( fm.length );
      while( !chores[j].isAssigned() )
        while( !fm[arrayIndex].addChore( chores[j].getName() ) )
          arrayIndex = generator.nextInt( fm.length );
        chores[j].setAssigned( true );
      System.out.print( chores[j].getName() + "\t" );
      if( chores[j].getName().length() < 8 )
        System.out.print( "\t" );
      System.out.println( fm[arrayIndex].getName() );
    System.out.println( "________________________________" );
}Enjoy,
Manfred.

Similar Messages

  • I need help with a Object Array

    I am having trouble and this maybe really simple seeing that I am fairly new to java but I have text that is being broken down in to preset part with those parts stored in Object arrays.
    Now I also have a object array inside my object array. Within the second object array are the broken down parts of the text and I want to compare this text with another string so for example this is what I am trying
    boolean found = false;
    for (int i = 0; i < FirstObjectArray.length ;i++)
         Object[] SecondObjectArray = (Object[]) FirstObjectArray;
         if(SecondObjectArray[0] == "string")
              found = true;
              break;
         else
              found = false;
    }Help would be very appreciated.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

    astlanda wrote:
    Sure, you're right.
    [public boolean equals(Object obj)|http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Object.html#equals%28java.lang.Object%29]
    sharkura said all the OP needs at the moment. I just wanted to clarify a bit why You don't use == 99.999% of the time with objects, and never with String.
    I have argued elsewhere in these forums that it is inappropriate to tell anyone that you never use == to compare objects. This has not always been accepted. I have, on rare occasions, known experienced developers to blindly compare two objects with equals(), and cite the professor that taught them, 15 years iin the past, that object references are never compared using ==, but always with equals().
    However, the cases where == is appropriate and equals() is not are indeed rare, but not, in my experience, non-existent. In my statement, I probably exaggerated. And String is a case where I can probably accept that you will probably never go wrong with equals(). If the String has been pooled (see String::intern()), you can actually use either. From the javadocs: "*It follows that for any two strings s and t, s.intern() == t.intern() is true if and only if s.equals(t) is true.*"
    ¦ {Þ                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Still Need Help with this String Problem

    basically, i need to create a program where I input 5 words and then the program outputs the number of unique words and the words themselves. for example, if i input the word hello 5 times, then the output is 1 unique word and the word "hello". i have been agonizing over this dumb problem for days, i know how to do it using hashmap, but this is an introductory course and we cannot use more complex java functions, does ANYONE know how to do this just using arrays, strings, for loops, if clauses, etc. really basic java stuff. i want the code to be able to do what the following program does:
    import java.io.*; import java.util.ArrayList;
        public class MoreUnique {
           public static void main(String[] args) throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String str[] = new String[5]; int uniqueEntries = 0; ArrayList<String> ue = new ArrayList<String>();
             for (int i = 0; i < 5; i++) { System.out.print((i +1) + ": "); str[i] = br.readLine(); }
             for (int j = 0; j < 5; j++) {
                if (!ue.contains(str[j].toLowerCase())) { ue.add(str[j].toLowerCase()); } } uniqueEntries = ue.size(); System.out.print("Number of unique entries: " + uniqueEntries + " { ");
             for (int q = 0; q < ue.size(); q++ ) { System.out.print(ue.get(q) + " "); } System.out.println("}"); } } but i need to find how to do it so all 5 words are put in at once on one line, and without all the advanced java functions that are in here, can anyone help out?

    you have to compare string 0 to strings 1-4, then
    string 1 with strings 2-4, then string 2 with strings
    3 and 4 then string 3 with string 4....right???Here's a way to do it:
    public class MoreUnique {
        public static void main(String[] args) throws IOException {
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            final int NUM_WORDS = 5;
            String[] words = new String[NUM_WORDS];
            int uniqueEntries = 0;
            for(int i = 0; i < NUM_WORDS; i++) {
                System.out.print((i+1)+": ");
                String temp = br.readLine();
                if(!contains(temp, words)) {
                    words[uniqueEntries++] = temp;
            System.out.print("Number of unique entries: "+uniqueEntries+" { ");   
            for (int i = 0; i < uniqueEntries; i++ ) {   
                System.out.print(words[i]+" ");
            System.out.println("}");
        private static boolean contains(String word, String[] array) {
                 Your code here: just a simple for-statement to
                 loop through your array and to see if 'word'
                 is in your 'array'.
    }Try to fill in the blanks.
    Good luck.

  • Help with comparing string array with parameters

    I've posted my code in full so hopefully everyone can see exactly what I have been doing.
    Note - my code uses the observer/observable model. The method I am having the problem with the if statement is in the class HSBC.
    Basically when the pin count reaches 4 (in the atm class) it sends the userid & pincode) over to the checkPinAndUserId(String pinCode, String userCode) method. Here the if statement should check the userid to see if the string parameter matches a string in the array. If it does it should check in the same position in the pin array to check the pin no is correct and then return true.
    * @(#)BankAssignment.java 1.0 03/04/06
    * This apllication l
    package myprojects.bankassignment;
    import java.awt.*; // import the component library
    import java.awt.event.*; // import the evnet library
    import javax.swing.*;
    import java.util.*;
    class Correct1v16 extends Frame // make a new application
         public Correct1v16() // this is the constructor method
              HSBC HSBCobj = new HSBC();
         public static void main(String args[]) // this invokes the constructor of the class and creates a runable object 'mainframe'
              Correct1v16 mainFrame = new Correct1v16(); // the constructor call of the class which creates an object of that class
    class HSBC implements Observer,  ActionListener
              Frame f5;
              JLabel refill, launch;
              TextField tRefill, tLaunch;
              JButton refillbut, launchbut;
              int count;
              String [] userId=new String [10];
              String [] pin=new String [10];
              public boolean authenticate = false;
              int i;
                   public HSBC()
                   drawFrame();
                   Atm Atmobj = new Atm(this);
                   System.out.println("Starting HSBC constructor");     
              public void drawFrame()
                   System.out.println("Start HSBC drawframe method...");
                   f5=new Frame("HSBC");
                   f5.setLayout(new FlowLayout());
                   f5.setSize(200, 200);
                   f5.addWindowListener(new WindowAdapter()
                        public void windowClosing(WindowEvent e)     
                             f5.dispose();
                             System.exit(0);     
                   refill=new JLabel("Refill ATM");
                   launch=new JLabel("Launch new ATM");
                   tRefill=new TextField(20);
                   tLaunch=new TextField(10);
                   refillbut=new JButton("Refill ATM");
                   refillbut.addActionListener(this);
                   launchbut=new JButton("Launch new ATM");
                   launchbut.addActionListener(this);
                   f5.add(refill);
                   f5.add(tRefill);
                   f5.add(refillbut);
                   f5.add(launch);
                   f5.add(tLaunch);
                   f5.add(launchbut);
                   f5.setVisible(true);
    //*********** POPULATE THE ARRAYS     */
                   pin[0]="1234";
                   pin[1]="2345";
                   pin[2]="3456";
                   pin[3]="4567";
                   pin[4]="5678";
                   pin[5]="6789";
                   pin[6]="7890";
                   pin[7]="8901";
                   pin[8]="9012";
                   pin[9]="0123";
                   userId[0]="0";
                   userId[1]="1";
                   userId[2]="2";
                   userId[3]="3";
                   userId[4]="4";
                   userId[5]="5";
                   userId[6]="6";
                   userId[7]="7";
                   userId[8]="8";
                   userId[9]="9";
              }// end drawframe method
              //     public Atm atmLink = (Atm)o;
                   public void update(Observable gm1, Object o)
                        Atm atmLink = (Atm)o;
                        tRefill.setText("Refill ATM ?");
                        atmLink.refill();
                   }//end update method
                   public void actionPerformed(ActionEvent ae)
                        if(ae.getSource() == refillbut)
    //                         Atm Atmobj.refill();
                        //     tRefill.setText("text area");     
                        //     atmLink.refill();
    //                         Atmobj.refill();
    //                         setChanged();
    //                         notifyObservers();
                        if(ae.getSource() == launchbut)
                             tLaunch.setText("new ATM opened");
                             Atm Atmobj1 = new Atm(this);
    //******** THIS METHOD RECEIVES THE PARAMETERS FROM THE ATM METHOD (LINE 580) (PINCODE AND USERCODE) BUT
    //******** IT ONLY THE ARRAY CALLED USERID (WHICH HOLDS THE USER CODE MATCHES ONE OF THE USERID'S)
    //******** I DO WANT IT TO DO THIS BUT I ALSO WANT IT TO MOVE ON AND CHECK THE PINCODE WITH THE PIN ARRAY)
    //******** IF THEY ARE BOTH TRUE I WANT IT TO RETURN TRUE - ELSE FALSE.          */               
                   public boolean checkPinAndUserId(String userCode, String pinCode)
                        boolean found = false;
                        System.out.println("in checkpin method");
                        System.out.println("userCode = "+ userCode);
                        System.out.println("pinCode = " + pinCode);
                        for (int i = 0; i < userId.length; i++)
                        System.out.println("in the userid array" + userId);
                             if (userCode.equals(userId[i]))
                                  System.out.println("checking user code array");
                                  if (pinCode.equals(pin[i]))
                                       System.out.println("checking the pin array" + pinCode);
                                       System.out.println("pin[i] = "+pin[i]);
                                  found = true;
                        return found;
         }// end HSBC class
    class Atm extends Observable implements ActionListener
              Frame f1;
              TextField t3, t5;
              JTextArea display = new JTextArea("Welcome to HSBC Bank. \n Please enter your User Identification number \n", 5, 40);
              JPanel p1, p2, p3,p4;
              private JButton but1, but2, but3, but4,but5,but6,but7,but8,but9,but0,enter,
              cancel,fivepounds,tenpounds,twentypounds,fiftypounds,clearbut, refillbut;
              int state = 1;                                        
              public String pinCode ="";
              public      String userCode ="";
              int userCodeCount = 0;
              int PINCount = 0;
              String withdrawAmount = "";
              int atmBalance =200;
              private HSBC HSBCobj;     
              //ATM constructor that receives the HSBCobj g1 reference to where the HSBC class
              // in in the program
              // Calls the drawATMFrame method
              // add the observer to the HSBCobj reference so that the ATM can tell HSBC that
              // something has changed
              public Atm(HSBC g1)
                   HSBCobj = g1;
                   drawATMFrame();
                   System.out.println("Starting Atm constructor");
                   addObserver(HSBCobj);     
              // this is the method that draws the ATM interface
              // also apply the Border Layout to the frame
              public void drawATMFrame()
                   f1=new Frame("ATM");
                   f1.setLayout(new BorderLayout());
                   f1.setSize(350, 250);
                   f1.addWindowListener(new WindowAdapter()
                        public void windowClosing(WindowEvent e)     
                             f1.dispose();
                             System.exit(0);     
                   // declare & instantiate all the buttons that will be used on the ATM
                   but1 =new JButton("1");
                   but1.addActionListener(this);
                   but2 =new JButton("2");
                   but2.addActionListener(this);
                   but3 =new JButton("3");
                   but3.addActionListener(this);
                   but4 =new JButton("4");
                   but4.addActionListener(this);
                   but5 =new JButton("5");
                   but5.addActionListener(this);
                   but6 =new JButton("6");
                   but6.addActionListener(this);
                   but7 =new JButton("7");
                   but7.addActionListener(this);
                   but8 =new JButton("8");
                   but8.addActionListener(this);
                   but9 =new JButton("9");
                   but9.addActionListener(this);
                   but0 =new JButton("0");
                   but0.addActionListener(this);
                   enter=new JButton("Enter");
                   enter.addActionListener(this);
                   cancel=new JButton("Cancel/ \n Restart");
                   cancel.addActionListener(this);
                   fivepounds =new JButton("?5");
                   fivepounds.addActionListener(this);
                   tenpounds = new JButton("?10");
                   tenpounds.addActionListener(this);
                   twentypounds = new JButton("?20");
                   twentypounds.addActionListener(this);
                   fiftypounds = new JButton("?50");
                   fiftypounds.addActionListener(this);
                   clearbut = new JButton("Clear");
                   clearbut.addActionListener(this);
                   refillbut = new JButton("Refill");
                   refillbut.addActionListener(this);
                   //declare & instantiate a textfield               
                   t3=new TextField(5);
                   // instantiate 4 JPanels     
                   p1=new JPanel();
                   p2=new JPanel();
                   p3=new JPanel();
                   p4=new JPanel();
                   // add some buttons to p1
                   p1.add(but1);
                   p1.add(but2);
                   p1.add(but3);
                   p1.add(but4);
                   p1.add(but5);
                   p1.add(but6);
                   p1.add(but7);
                   p1.add(but8);
                   p1.add(but9);               
                   p1.add(but0);
                   //add the text area field to p2
                   p2.add(display);
                   // apply the grid layout to p3
                   GridLayout layout3 = new GridLayout(4,1,5,5);
                   p3.setLayout(layout3);
                   p3.add(fivepounds);
                   p3.add(tenpounds);
                   p3.add(twentypounds);
                   p3.add(fiftypounds);
                   // apply grid layout to p4
                   GridLayout layout4 = new GridLayout(4,1,5, 5);
                   p4.setLayout(layout4);
                   p4.add(clearbut);
                   p4.add(enter);
                   p4.add(cancel);
                   p4.add(refillbut);
                   //add the panels to the different parts of the screen
                   f1.add("North", display);
                   f1.add("Center", p1);
                   f1.add("East", p4);
                   f1.add("West", p3);
                   f1.setVisible(true);
              }// end drawATMframe method
         public void actionPerformed(ActionEvent ae)
                   if(state == 1)
                             getUserIdNo(ae);
              else     if(state == 2)
                             doPINInput(ae);
                        else
                             withdrawCash(ae);     
         }// end action performed method               
    //******** STATE 1 events*/
    //******** USER ID INPUT*/
              public void getUserIdNo (ActionEvent ae)
                   if (ae.getSource() == but1)
                        display.append("*");
                        userCode = userCode + "1";
                        userCodeCount++;
                   if (ae.getSource() == but2)
                        display.append("*");
                        userCode = userCode + "2";
                        userCodeCount++;
                   if (ae.getSource() == but3)
                        display.append("*");
                        userCode = userCode + "3";
                        userCodeCount++;
                        System.out.println("user id ="+userCode);
                   if (ae.getSource() == but4)
                        display.append("*");
                        userCode = userCode = "4";
                        userCodeCount++;
                        System.out.println("user id ="+userCode);
                   if (ae.getSource() == but5)
                        display.append("*");
                        userCode = userCode + "5";
                        userCodeCount++;
                        System.out.println("user id ="+userCode);
                   if (ae.getSource() == but6)
                        display.append("*");
                        userCode = userCode + "6";
                        userCodeCount++;
                        System.out.println("user id ="+userCode);
                   if (ae.getSource() == but7)
                        display.append("*");
                        userCode = userCode + "7";
                        userCodeCount++;
                        System.out.println("user id ="+userCode);
                   if (ae.getSource() == but8)
                        display.append("*");
                        userCode = userCode + "8";
                        userCodeCount++;
                        System.out.println("user id ="+userCode);
                   if (ae.getSource() == but9)
                        display.append("*");
                        userCode = userCode + "9";
                        userCodeCount++;
                        System.out.println("user id ="+userCode);
                   if (ae.getSource() == but0)
                        display.append("*");
                        userCode = userCode + "0";
                        userCodeCount++;
                        System.out.println("user id ="+userCode);
                   if (ae.getSource() == cancel)
                        display.setText("Welcome to HSBC Bank.\n Please enter your User Identification number \n");
                        userCode = "";
                        state = 2;
                   if (ae.getSource() == clearbut)
                        display.setText("Please enter your user ID number again\n");
                        userCode = "";
                        userCodeCount = 0;
                   if (ae.getSource() == refillbut)
                        refill();
                   if (ae.getSource() == enter)
                        display.setText("Please enter your PIN \n");
                        state = 2;
                        System.out.println(" User id enter button = " + userCode);
                   if (userCodeCount == 1)
                        display.setText("Please enter your PIN \n");
                        //userCode = "";
                        userCodeCount = 0;
                        state = 2;          
    //******** STATE 2               */
    //******** PIN INPUT*/
                   public void doPINInput(ActionEvent ae)
                        if (ae.getSource() == but1)
                             {      pinCode = pinCode.concat("1");
                                  display.append("*");
                                  PINCount++;     
                        if (ae.getSource() == but2)
                             {      pinCode = pinCode.concat("2");
                                  display.append("*");
                                  PINCount++;     
                        if (ae.getSource() == but3)
                             {      pinCode = pinCode.concat("3");
                                  display.append("*");
                                  PINCount++;     
                        if (ae.getSource() == but4)
                             {      pinCode = pinCode.concat("4");
                                  display.append("*");
                                  PINCount++;     
                        if (ae.getSource() == but5)
                             {      pinCode = pinCode.concat("5");
                                  display.append("*");
                                  PINCount++;     
                        if (ae.getSource() == but6)
                             {      pinCode = pinCode.concat("6");
                                  display.append("*");
                                  PINCount++;     
                        if (ae.getSource() == but7)
                             {      pinCode = pinCode.concat("7");
                                  display.append("*");
                                  PINCount++;     
                        if (ae.getSource() == but8)
                             {      pinCode = pinCode.concat("8");
                                  display.append("*");
                                  PINCount++;     
                        if (ae.getSource() == but9)
                             {      pinCode = pinCode.concat("9");
                                  display.append("*");
                                  PINCount++;     
                        if (ae.getSource() == but0)
                             {      pinCode = pinCode.concat("0");
                                  display.append("*");
                                  PINCount++;     
                        if (ae.getSource() == clearbut)
                                  display.setText("Please enter your PIN number again \n");
                                  pinCode = "";     
                                  PINCount = 0;
                        if (ae.getSource() == cancel)
                                  display.setText("Welcome to HSBC Bank.\n Please enter your User Identification number \n");
                             state = 1;
                                  pinCode ="";
                                  PINCount = 0;                         
                        if (ae.getSource() == refillbut)
                                  refill();
    /// ************************ THIS BUTTON SENDS THE PIN & USER CODE OVER TO THE MAIN BANK*/
    /// ************************ (LINE 152)               */
                        if (ae.getSource() == enter)
    //                         if(HSBCobj.checkPinAndUserId(pinCode, userCode))
    //                              display.setText("How much would you like to withdraw \n");
    //                    else
    //                         display.setText("Your UserId and Pin code do not match");
                        if(PINCount ==4)
                        if(HSBCobj.checkPinAndUserId(userCode,pinCode))
                                  display.setText("Enter the amount you \n want to withdraw \n ?");
                                  PINCount=0;
                        else
                        display.setText("Your User Identification Number \n and PIN number do not match! \n please try again\n");     
    //*********** STATE 3 events*/
    //*********** withdrawCash*/
         public void withdrawCash(ActionEvent ae)
    //               if (ae.getSource() == but1)
    //                    display.append("1");
    ///                    withdrawAmount = withdrawAmount+1;
         //               pinCode = pinCode.concat("2");
         //               System.out.println("Withdrawal Amount = "+withdrawAmount);
                   if(ae.getSource( ) == but1)
                        withdrawAmount = withdrawAmount + "1";
                        display.setText(withdrawAmount);
                   if(ae.getSource( ) == but2)
                        withdrawAmount = withdrawAmount + "2";
                        display.setText(withdrawAmount);
                   if(ae.getSource( ) == but3)
                        withdrawAmount = withdrawAmount + "3";
                        display.setText(withdrawAmount);
                   if(ae.getSource( ) == but4)
                        withdrawAmount = withdrawAmount + "4";
                        display.setText(withdrawAmount);
                   if(ae.getSource( ) == but5)
                        withdrawAmount = withdrawAmount + "5";
                        display.setText(withdrawAmount);
                   if(ae.getSource( ) == but6)
                        withdrawAmount = withdrawAmount + "6";
                        display.setText(withdrawAmount);
                   if(ae.getSource( ) == but7)
                        withdrawAmount = withdrawAmount + "7";
                        display.setText(withdrawAmount);
                   if(ae.getSource( ) == but8)
                        withdrawAmount = withdrawAmount + "8";
                        display.setText(withdrawAmount);
                   if(ae.getSource( ) == but9)
                        withdrawAmount = withdrawAmount + "9";
                        display.setText(withdrawAmount);
                   if(ae.getSource( ) == but0)
                        withdrawAmount = withdrawAmount + "0";
                        display.setText(withdrawAmount);
                   if (ae.getSource() == fivepounds)
                        withdrawAmount = withdrawAmount + "5";
                        display.setText(withdrawAmount);
                        atmBalance();
                   if (ae.getSource() == tenpounds)
                        withdrawAmount = withdrawAmount + "10";
                        display.setText(withdrawAmount);
                        atmBalance();
                   if (ae.getSource() == twentypounds)
                        withdrawAmount = withdrawAmount + "20";
                        display.setText(withdrawAmount);
                        atmBalance();
                   if (ae.getSource() == fiftypounds)
                        withdrawAmount = withdrawAmount + "50";
                        display.setText(withdrawAmount);
                        atmBalance();
         //          if (ae.getSource() == tenpounds)
         //               display.append("10");
         //               withdrawAmount = 10;
         //               pinCode = pinCode.concat("2");
         //               System.out.println("10 pound button pressed");
         //               atmBalance();
                   if (ae.getSource() == enter)
                        atmBalance();
                   if (ae.getSource() == refillbut)
                        System.out.println("refill but pressed");
                        refill();     
                   if (ae.getSource() == clearbut)
                        System.out.println("clear but pressed");
                        display.setText("Enter the amount you want to withdraw \n ?");
                        withdrawAmount="";
                   if (ae.getSource() == cancel)
                        display.setText("Welcome to HSBC Bank.\n Please enter your User Identification number \n");
                        withdrawAmount="";
                   pinCode ="";
                        PINCount = 0;
                        userCode = "";
                        userCodeCount = 0;
                        state = 1;
         }// end withdraw cash input method
         // checks balace of atm and withdraws cash. Also notifies onserver if atm balance is low     
              public void atmBalance()
                   String s = withdrawAmount;
                   int n = Integer.parseInt(s);
                   if ( atmBalance >= n)
                        atmBalance = atmBalance - n;
                        System.out.println("atm balance = "+ atmBalance);
                        display.setText("Thankyou for using HSBC. \nYou have withdrawn ?"+n);
                        if     (atmBalance<40)
                             System.out.println("atm balance is less than 40 - notify HSBC" );
                             setChanged();
                             notifyObservers(this);
                             /// note the refil should send a message to the controller
                             // advising a refil is needed. The Bank will send an engineer
                             // out who will fill the atm up
              }// end atmBalance method
              /// note the refil should send a message to the controller
              /// then th coontroller will send a message to this method to fill machine
              /// (this is simulating a clerk filling atm)
                   public void refill()
                        System.out.println("in refill method" );
                        atmBalance = 200;
                        System.out.println("Atm has been refilled. Atm balance = " + atmBalance);
                   //     setChanged();
                   //     notifyObservers(this);
                   }// end refill method
    // NOTE SURE ABOUT THIS - DO I USE THE UPDATE METHOD TO NOTIFY HSBC THAT ATM REQUIRES FILLING
    // THIS IS THE WRONG PART OF THE PROGRAM (SHOULD BE IN HSBC) - IGNORE
                   public void update(Observable gm1, Object gameObj)
                        display.setText("Congratulations");               
                   }//end update method
         }// end Atm method
    }// end Assignment2 clas
    [\code]

    I wasn't trying to annoy anyone at all.
    I'm new to java and have been told that using the observer/observable model is not considered basic java. So that is the only reason I posted it in this section. At the same time i feel that the bit I'm struggling with is actually basic - hence posting it in the basic section. I'm not sure if people of all abilities check all forums or just the ones they feel at at their standard.
    So appologies if you've taken offence.

  • Need help with random numbers

    hi i need to generate 2 random numbers from array list . and then take out that two numbers from list.
         String[] plcard = { "AC", "KC", "QC", "JC",
              "10C", "9C", "8C", "7C","6C","5C","4C","3C","2C", "AD", "KD", "QD", "JD",
              "10D", "9D", "8D", "7D","6D","5D","4D","3D","2D", "AS", "KS", "QS", "JS",
              "10S", "9S", "8S", "7S","6S","5S","4S","3S","2S", "AH", "KH", "QH", "JH",
              "10H", "9H", "8H", "7H","6H","5H","4H","3H","2H",};
    this is the list if someone can help me i would appreciate
    thanks in advance

    haha, never noticed the .shuffle(List) method!
    maybe java is getting too convenient (just kidding)?
    i never wrote a card game.
    how would the more programmingly gifted of us do this?
    this is my shot at it for what its worth...
    public class Card{
    public Card(int rank, int suit){
    this.rank = rank;
    this.suit = suit;
    int rank (or String i suppose)
    int suit;
    static final club = 1;
    static final spade = 2;
    static final heart = 3;
    static final diamond = 4;
    public class Shuffler{
    public Shuffler(){
    int NumOfDecks = 1;
    Vector ShuffledDeck;
    // num of decks
    for(int i = 0; i < NumOfDecks){
    // 4 suits
    for(int j = 0; j < 4; j++){
    // 13 ranks
    for(int k = 0; k < 13; k++){
    ShuffledDeck.add(new Card(k, j));
    } // suits
    } // num of decks
    Collections.shuffle(ShuffledDeck);
    // Done?
    }

  • Need Help with a String Binary Tree

    Hi, I need the code to build a binary tree with string values as the nodes....i also need the code to insert, find, delete, print the nodes in the binarry tree
    plssss... someone pls help me on this
    here is my code now:
    // TreeApp.java
    // demonstrates binary tree
    // to run this program: C>java TreeApp
    import java.io.*; // for I/O
    import java.util.*; // for Stack class
    import java.lang.Integer; // for parseInt()
    class Node
         //public int iData; // data item (key)
         public String iData;
         public double dData; // data item
         public Node leftChild; // this node's left child
         public Node rightChild; // this node's right child
         public void displayNode() // display ourself
              System.out.print('{');
              System.out.print(iData);
              System.out.print(", ");
              System.out.print(dData);
              System.out.print("} ");
    } // end class Node
    class Tree
         private Node root; // first node of tree
         public Tree() // constructor
         { root = null; } // no nodes in tree yet
         public Node find(int key) // find node with given key
         {                           // (assumes non-empty tree)
              Node current = root; // start at root
              while(current.iData != key) // while no match,
                   if(key < current.iData) // go left?
                        current = current.leftChild;
                   else // or go right?
                        current = current.rightChild;
                   if(current == null) // if no child,
                        return null; // didn't find it
              return current; // found it
         } // end find()
         public Node recfind(int key, Node cur)
              if (cur == null) return null;
              else if (key < cur.iData) return(recfind(key, cur.leftChild));
              else if (key > cur.iData) return (recfind(key, cur.rightChild));
              else return(cur);
         public Node find2(int key)
              return recfind(key, root);
    public void insert(int id, double dd)
    Node newNode = new Node(); // make new node
    newNode.iData = id; // insert data
    newNode.dData = dd;
    if(root==null) // no node in root
    root = newNode;
    else // root occupied
    Node current = root; // start at root
    Node parent;
    while(true) // (exits internally)
    parent = current;
    if(id < current.iData) // go left?
    current = current.leftChild;
    if(current == null) // if end of the line,
    {                 // insert on left
    parent.leftChild = newNode;
    return;
    } // end if go left
    else // or go right?
    current = current.rightChild;
    if(current == null) // if end of the line
    {                 // insert on right
    parent.rightChild = newNode;
    return;
    } // end else go right
    } // end while
    } // end else not root
    } // end insert()
    public void insert(String id, double dd)
         Node newNode = new Node(); // make new node
         newNode.iData = id; // insert data
         newNode.dData = dd;
         if(root==null) // no node in root
              root = newNode;
         else // root occupied
              Node current = root; // start at root
              Node parent;
              while(true) // (exits internally)
                   parent = current;
                   //if(id < current.iData) // go left?
                   if(id.compareTo(current.iData)>0)
                        current = current.leftChild;
                        if(current == null) // if end of the line,
                        {                 // insert on left
                             parent.leftChild = newNode;
                             return;
                   } // end if go left
                   else // or go right?
                        current = current.rightChild;
                        if(current == null) // if end of the line
                        {                 // insert on right
                             parent.rightChild = newNode;
                             return;
                   } // end else go right
              } // end while
         } // end else not root
    } // end insert()
         public Node betterinsert(int id, double dd)
              // No duplicates allowed
              Node return_val = null;
              if(root==null) {       // no node in root
                   Node newNode = new Node(); // make new node
                   newNode.iData = id; // insert data
                   newNode.dData = dd;
                   root = newNode;
                   return_val = root;
              else // root occupied
                   Node current = root; // start at root
                   Node parent;
                   while(current != null)
                        parent = current;
                        if(id < current.iData) // go left?
                             current = current.leftChild;
                             if(current == null) // if end of the line,
                             {                 // insert on left
                                  Node newNode = new Node(); // make new node
                                  newNode.iData = id; // insert data
                                  newNode.dData = dd;
                                  return_val = newNode;
                                  parent.leftChild = newNode;
                        } // end if go left
                        else if (id > current.iData) // or go right?
                             current = current.rightChild;
                             if(current == null) // if end of the line
                             {                 // insert on right
                                  Node newNode = new Node(); // make new node
                                  newNode.iData = id; // insert data
                                  newNode.dData = dd;
                                  return_val = newNode;
                                  parent.rightChild = newNode;
                        } // end else go right
                        else current = null; // duplicate found
                   } // end while
              } // end else not root
              return return_val;
         } // end insert()
         public boolean delete(int key) // delete node with given key
              if (root == null) return false;
              Node current = root;
              Node parent = root;
              boolean isLeftChild = true;
              while(current.iData != key) // search for node
                   parent = current;
                   if(key < current.iData) // go left?
                        isLeftChild = true;
                        current = current.leftChild;
                   else // or go right?
                        isLeftChild = false;
                        current = current.rightChild;
                   if(current == null)
                        return false; // didn't find it
              } // end while
              // found node to delete
              // if no children, simply delete it
              if(current.leftChild==null &&
                   current.rightChild==null)
                   if(current == root) // if root,
                        root = null; // tree is empty
                   else if(isLeftChild)
                        parent.leftChild = null; // disconnect
                   else // from parent
                        parent.rightChild = null;
              // if no right child, replace with left subtree
              else if(current.rightChild==null)
                   if(current == root)
                        root = current.leftChild;
                   else if(isLeftChild)
                        parent.leftChild = current.leftChild;
                   else
                        parent.rightChild = current.leftChild;
              // if no left child, replace with right subtree
              else if(current.leftChild==null)
                   if(current == root)
                        root = current.rightChild;
                   else if(isLeftChild)
                        parent.leftChild = current.rightChild;
                   else
                        parent.rightChild = current.rightChild;
                   else // two children, so replace with inorder successor
                        // get successor of node to delete (current)
                        Node successor = getSuccessor(current);
                        // connect parent of current to successor instead
                        if(current == root)
                             root = successor;
                        else if(isLeftChild)
                             parent.leftChild = successor;
                        else
                             parent.rightChild = successor;
                        // connect successor to current's left child
                        successor.leftChild = current.leftChild;
                        // successor.rightChild = current.rightChild; done in getSucessor
                   } // end else two children
              return true;
         } // end delete()
         // returns node with next-highest value after delNode
         // goes to right child, then right child's left descendents
         private Node getSuccessor(Node delNode)
              Node successorParent = delNode;
              Node successor = delNode;
              Node current = delNode.rightChild; // go to right child
              while(current != null) // until no more
              {                                 // left children,
                   successorParent = successor;
                   successor = current;
                   current = current.leftChild; // go to left child
              // if successor not
              if(successor != delNode.rightChild) // right child,
              {                                 // make connections
                   successorParent.leftChild = successor.rightChild;
                   successor.rightChild = delNode.rightChild;
              return successor;
         public void traverse(int traverseType)
              switch(traverseType)
              case 1: System.out.print("\nPreorder traversal: ");
                   preOrder(root);
                   break;
              case 2: System.out.print("\nInorder traversal: ");
                   inOrder(root);
                   break;
              case 3: System.out.print("\nPostorder traversal: ");
                   postOrder(root);
                   break;
              System.out.println();
         private void preOrder(Node localRoot)
              if(localRoot != null)
                   localRoot.displayNode();
                   preOrder(localRoot.leftChild);
                   preOrder(localRoot.rightChild);
         private void inOrder(Node localRoot)
              if(localRoot != null)
                   inOrder(localRoot.leftChild);
                   localRoot.displayNode();
                   inOrder(localRoot.rightChild);
         private void postOrder(Node localRoot)
              if(localRoot != null)
                   postOrder(localRoot.leftChild);
                   postOrder(localRoot.rightChild);
                   localRoot.displayNode();
         public void displayTree()
              Stack globalStack = new Stack();
              globalStack.push(root);
              int nBlanks = 32;
              boolean isRowEmpty = false;
              System.out.println(
              while(isRowEmpty==false)
                   Stack localStack = new Stack();
                   isRowEmpty = true;
                   for(int j=0; j<nBlanks; j++)
                        System.out.print(' ');
                   while(globalStack.isEmpty()==false)
                        Node temp = (Node)globalStack.pop();
                        if(temp != null)
                             System.out.print(temp.iData);
                             localStack.push(temp.leftChild);
                             localStack.push(temp.rightChild);
                             if(temp.leftChild != null ||
                                  temp.rightChild != null)
                                  isRowEmpty = false;
                        else
                             System.out.print("--");
                             localStack.push(null);
                             localStack.push(null);
                        for(int j=0; j<nBlanks*2-2; j++)
                             System.out.print(' ');
                   } // end while globalStack not empty
                   System.out.println();
                   nBlanks /= 2;
                   while(localStack.isEmpty()==false)
                        globalStack.push( localStack.pop() );
              } // end while isRowEmpty is false
              System.out.println(
         } // end displayTree()
    } // end class Tree
    class TreeApp
         public static void main(String[] args) throws IOException
              int value;
              double val1;
              String Line,Term;
              BufferedReader input;
              input = new BufferedReader (new FileReader ("one.txt"));
              Tree theTree = new Tree();
         val1=0.1;
         while ((Line = input.readLine()) != null)
              Term=Line;
              //val1=Integer.parseInt{Term};
              val1=val1+1;
              //theTree.insert(Line, val1+0.1);
              val1++;
              System.out.println(Line);
              System.out.println(val1);          
    theTree.insert(50, 1.5);
    theTree.insert(25, 1.2);
    theTree.insert(75, 1.7);
    theTree.insert(12, 1.5);
    theTree.insert(37, 1.2);
    theTree.insert(43, 1.7);
    theTree.insert(30, 1.5);
    theTree.insert(33, 1.2);
    theTree.insert(87, 1.7);
    theTree.insert(93, 1.5);
    theTree.insert(97, 1.5);
              theTree.insert(50, 1.5);
              theTree.insert(25, 1.2);
              theTree.insert(75, 1.7);
              theTree.insert(12, 1.5);
              theTree.insert(37, 1.2);
              theTree.insert(43, 1.7);
              theTree.insert(30, 1.5);
              theTree.insert(33, 1.2);
              theTree.insert(87, 1.7);
              theTree.insert(93, 1.5);
              theTree.insert(97, 1.5);
              while(true)
                   putText("Enter first letter of ");
                   putText("show, insert, find, delete, or traverse: ");
                   int choice = getChar();
                   switch(choice)
                   case 's':
                        theTree.displayTree();
                        break;
                   case 'i':
                        putText("Enter value to insert: ");
                        value = getInt();
                        theTree.insert(value, value + 0.9);
                        break;
                   case 'f':
                        putText("Enter value to find: ");
                        value = getInt();
                        Node found = theTree.find(value);
                        if(found != null)
                             putText("Found: ");
                             found.displayNode();
                             putText("\n");
                        else
                             putText("Could not find " + value + '\n');
                        break;
                   case 'd':
                        putText("Enter value to delete: ");
                        value = getInt();
                        boolean didDelete = theTree.delete(value);
                        if(didDelete)
                             putText("Deleted " + value + '\n');
                        else
                             putText("Could not delete " + value + '\n');
                        break;
                   case 't':
                        putText("Enter type 1, 2 or 3: ");
                        value = getInt();
                        theTree.traverse(value);
                        break;
                   default:
                        putText("Invalid entry\n");
                   } // end switch
              } // end while
         } // end main()
         public static void putText(String s)
              System.out.print(s);
              System.out.flush();
         public static String getString() throws IOException
              InputStreamReader isr = new InputStreamReader(System.in);
              BufferedReader br = new BufferedReader(isr);
              String s = br.readLine();
              return s;
         public static char getChar() throws IOException
              String s = getString();
              return s.charAt(0);
         public static int getInt() throws IOException
              String s = getString();
              return Integer.parseInt(s);
    } // end class TreeApp

    String str = "Hello";
              int index = 0, len = 0;
              len = str.length();
              while(index < len) {
                   System.out.println(str.charAt(index));
                   index++;
              }

  • Need Help with random numbers, please help

    Hi guys;
    I need your help for a school project. I need to generate a random number from 1.0 to 2.0. How would I do that?
    Regards,

    http://java.sun.com/j2se/1.3/docs/api/java/util/Random.html#nextFloat()

  • Need help with attributed string in NSMenuItem

    I'm trying to implement a contextual menu for a view in one of my applications. I want it to be dynamic, based on where you click in the view. It works fine if I don't try to mess with the font size of the menu. If I try to make the menu font smaller, the menu will appear blank, and its action won't get triggered, but only if there's only one menu item. If there are two or more, they'll all show up.
    I've done a bunch of searching, and found some code examples where they put in a dummy item, then remove it later, but so far, that hasn't helped me, either. I've posted an example project (~44KB) on my web site that illustrates this, if you'd like to see it in action (the example doesn't include the "dummy fix", by the way, but it's easy enough to add).
    Here's the code where I customize the menu:
    <pre class="command">-(NSMenu *)menuForEvent:(NSEvent *)theEvent
    NSPoint mouseLoc = [self convertPoint:[theEvent locationInWindow] fromView:nil];
    NSLog(@"Raw Mouse Location: %2.1f, %2.1f", mouseLoc.x, mouseLoc.y);
    // Get my blank menu:
    NSMenu *tzMenu = [self defaultMenu];
    // Set up my string attributes:
    NSMutableDictionary *menuAttributes = [[NSMutableDictionary alloc] init];
    [menuAttributes setObject:[NSFont fontWithName:@"Lucida Grande" size:11] forKey:NSFontAttributeName];
    if (mouseLoc.x < 220) // Make just one menu item.
    int i;
    for (i=0; i<1; i++)
    [tzMenu addItemWithTitle:@"Item" action:@selector(changeMapDot:) keyEquivalent:@""];
    NSMenuItem *lastItem = [tzMenu itemAtIndex:[tzMenu numberOfItems] - 1];
    NSAttributedString *attrString = [[NSAttributedString alloc] initWithString:@"Item" attributes:menuAttributes];
    // Comment out this next line and the menu item appears in the default font:
    [lastItem setAttributedTitle:attrString];
    [attrString release];
    else
    int i;
    for (i=0; i<3; i++) //Make three items. These always appear.
    [tzMenu addItemWithTitle:@"Item" action:@selector(changeMapDot:) keyEquivalent:@""];
    NSMenuItem *lastItem = [tzMenu itemAtIndex:[tzMenu numberOfItems] - 1];
    NSAttributedString *attrString = [[NSAttributedString alloc] initWithString:@"Item" attributes:menuAttributes];
    [lastItem setAttributedTitle:attrString];
    [attrString release];
    [menuAttributes release];
    return tzMenu;
    }</pre>Any tips that anyone has would be most apprecitated.
    I'm not unalterably opposed to the regular system menu font if there's no way around this (the menus are pretty short: usually less then a dozen items), but aesthetically it looks nicer with a smaller font.
    charlie

    Hi,
    You can use SUBSTR and INSTR
    This should work in Oracle 9:
    WITH     cntr     AS
         SELECT     LEVEL     AS n
         FROM     dual
         CONNECT BY     LEVEL <= 3
    ,     got_pos          AS
         SELECT     x.txt
         ,     c.n
         ,     INSTR (x.txt, '[', 1, c.n)     AS l_pos
         ,     INSTR (x.txt, ']', 1, c.n)     AS r_pos
         FROM           table_x  x
         CROSS JOIN    cntr     c
    SELECT        txt
    ,        n
    ,        SUBSTR ( txt
                   , l_pos + 1
                , r_pos - (l_pos + 1)
                   )     AS sub_txt
    FROM        got_pos
    ORDER BY   txt
    ,             n
    ;Sorry, I don't have an Oracle 9 database available now; I had to test this in Oracle 10.
    jimmy437 wrote:
    ... I have tried the "REGEXP_SUBSTR" but my database version is 9i, and it is available only from 10g.That's true. Regular expressions are very useful, but they're not available in Oracle 9 (or earlier).
    Oracle 9 does have an Oracle-supplied package, OWA_PATTERN, that provides some regular expression functionality:
    http://docs.oracle.com/cd/B12037_01/appdev.101/b10802/w_patt.htm
    I know that's the Oracle 10, documentation, but it exists in Oracle 9, too.
    Oracle 9 is very old. You should consider upgrading.

  • Need Help with Random Events in Actionscript 2

    I'm working on a game in flash right now, written in actionscript 2, where bottles fall from above at random speeds, and the object is to shoot the bottles as they fall, and every time you hit a bottle a different message appears on the screen for a brief period of time before disappearing.  So far I'm able to make the bottles fall and I'm able to shoot and break them, but I don't know how to work it so a different message appears each time you shoot a bottle. 
    Can anyone help me with this problem?  I'm attaching the file of what I have so far.

    My first question would be, when you say "different message appears" each time you hit a bottle.
    What are the messages and do you want them to be random, and where will they appear.
    After looking at your code, the best place I can see to place your message trigger is within the hit test. From there its a somple case of calling a function to display your message.

  • I need help with random number in GUI

    hello
    i have home work about the random number with gui. and i hope that you can help me doin this application. and thank you very much
    Q1)
    Write an application that generates random numbers. The application consists of one JFrame,
    with two text fields (see the figures) and a button. When the user clicks on the button, the
    program should generate a random number between the minimum and the maximum numbers
    entered in the text fields. The font of the number should be in red, size 100, bold and italic.
    Moreover, if the user clicks on the generated number (or around it), the color of the background
    should be changed to another random color. The possible colors are red, green blue , black ,cyan
    and gray.
    Notes:
    �&#61472;The JFrame size is 40 by 200
    �&#61472;The text fields size is 10
    this is a sample how should the programe look like.
    http://img235.imageshack.us/img235/9680/outputgo3.jpg
    Message was edited by:
    jave_cool

    see java.util.Random

  • Need help with returning an array of object

    hello, i've been trying to make a method that returns bot ha boolean and a colour for a render for a Jtable and the code for the method is:
         public Object[] isHighlightCellsWithColour(int xInternal, int colInternal) {
              Object[] returnWithTwoValue;
              boolean isHighLight = false;
              returnWithTwoValue = new Object[2];
              returnWithTwoValue[0] = isHighLight;
              returnWithTwoValue[1] = null;
              if (colourPassed == true && this.foundDupeInternal > -1) {
                   for (int c6 = 0; c6 < foundDupeInternal; c6++) {
                        if (this.rows[c6] == xInternal && this.cols[c6] == colInternal) {
                             isHighLight = true;
                             Color colourToSet = errorColourList[c6];
                             returnWithTwoValue = new Object[2];
                             returnWithTwoValue[0] = isHighLight;
                             returnWithTwoValue[2] = colourToSet;
                             return returnWithTwoValue;
              } else {
                   return returnWithTwoValue;
              return null;
         }and when i go and try to use it at
              check = new Object[2];
              check = isHighlightCellsWithColour(xCurrentlyDrawing, colCurrentlyDrawing);
              boolean z = false;
              try {
                   z = (Boolean) check[0];
              } catch (NullPointerException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
              Color x = Color.white;
              try {
                   x = (Color)check[1];
              } catch (NullPointerException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
              it gives me a nullpointerexception, which i try to catch, but it STILL gives me that error, i have no clue on how to cast from object back to boolean or colour after they are cast into objects
    or else is there a way to pass two different types of data back from a method? Other than using static variables that is, since that gave me problems, it only draws the first cell in colum that is in error in the colour specified , not the rest...
    thanks for your time
    Edited by: TheHolyLancer on Mar 8, 2008 12:42 AM

    yay that got it working, but the method still only draws the first cell with the colour only, need another way to do this one...
    now comes another puzzeling question, it is giving me an null pointer exception again in:
    System.out.println("setting colour "+ x.getBlue() + " On cell " + xCurrentlyDrawing + colCurrentlyDrawing);when i add that to the part where i set the colour, and colour is set to x (which is a color that is passed down by the method) and this will only run if it is determined that a colour is already passed, but it still gives me null pointer error?
    maybe i'll take this to the swing forum tommrow
    Edited by: TheHolyLancer on Mar 8, 2008 2:17 AM
    Edited by: TheHolyLancer on Mar 8, 2008 2:19 AM

  • Need help with codings on generating random words

    hi guys.. i need help with generating random words from a list of array. please help me with the codings.. let me know the other variables that are needed if required as well.. thanks a million..
    private String wordList[] = { "abstraction", "command", "arithmetic", "backslash" };

    Hi,
    You can use the Random class to generate Random number between 0 to the array length and use the generated random number as index in to the Strign array.
    To generate Random number use the following code
    Random r = new Random();
    num = ((r.nextInt() >>> 1) % wordList.length);
    num will have the randomly generated number.

  • Need help with connecting file inputs to arrays

    In this assignment I have a program that will do the following: display a list of names inputed by the user in reverse order, display any names that begin with M or m, and display any names with 5 or more letters. This is all done with arrays.
    That was the fun part. The next part requires me to take the names from a Notepad file, them through the arrays and then output them to a second Notepad file.
    Here is the original program: (view in full screen so that the code doesn't get jumbled)
    import java.io.*;       //Imports the Java library
    class progB                    //Defines class
        public static void main (String[] arguments) throws IOException
            BufferedReader keyboard;                                  //<-
            InputStreamReader reader;                                 //  Allows the program to
            reader = new InputStreamReader (System.in);               //  read the the keyboard
            keyboard = new BufferedReader (reader);                  //<-
            String name;                 //Assigns the name variable which will be parsed into...
            int newnames;               //...the integer variable for the amount of names.
            int order = 0;              //The integer variable that will be used to set the array size
            String[] array;             //Dynamic array (empty)
            System.out.println (" How many names do you want to input?");   //This will get the number that will later define the array
            name = keyboard.readLine ();
            newnames = Integer.parseInt (name);                                         // Converts the String into the Integer variable
            array = new String [newnames];                                               //This defines the size of the array
            DataInput Imp = new DataInputStream (System.in);       //Allows data to be input into the array
            String temp;                                       
            int length;                                                                  //Defines the length of the array for a loop later on
                for (order = 0 ; order < newnames ; order++)                                //<-
                {                                                                           //  Takes the inputed names and
                    System.out.println (" Please input name ");                            //  gives them a number according to
                    temp = keyboard.readLine ();                                           //  the order they were inputed in
                    array [order] = temp;                                                  //<-
                for (order = newnames - 1 ; order >= 0 ; order--)                                //<-
                {                                                                                //  Outputs the names in the reverse 
                    System.out.print (" \n ");                                                   //  order that they were inputed
                    System.out.println (" Name " + order + " is " + array [order]);             //<-
                for (order = 0 ; order < newnames ; order++)                                  //<-
                    if (array [order].startsWith ("M") || array [order].startsWith ("m"))     //  Finds and outputs any and all
                    {                                                                         //  names that begin with M or m
                        System.out.print (" \n ");                                            //
                        System.out.println (array [order] + (" starts with M or m"));         //
                    }                                                                         //<-
                for (order = 0 ; order < newnames ; order++)                                            //<-
                    length = array [order].length ();                                                   //
                    if (length >= 5)                                                                    //  Finds and outputs names
                    {                                                                                  //  with 5 or more letters
                        System.out.print (" \n ");                                                      //
                        System.out.println ("Name " + array [order] + " have 5 or more letters ");      //<-
    }The notepad file contains the following names:
    jim
    laruie
    tim
    timothy
    manny
    joseph
    matty
    amanda
    I have tried various methods but the one thing that really gets me is the fact that i can't find a way to connect the names to the arrays. Opening the file with FileInputStream is easy enough but using the names and then outputing them is quite hard. (unless i'm thinking too hard and there really is a simple method)

    By "connect", do you just mean you want to put the names into an array?
    array[0] = "jim"
    array[1] = "laruie"
    and so on?
    That shouldn't be difficult at all, provided you know how to open a file for reading, and how to read a line of text from it. You can just read the line of text, put it in the array position you want, until the file is exhausted. Then open a file for writing, loop through the array, and write a line.
    What part of all that do you need help with?

  • I need help with 2 arrays

    I need help with this portion of my program, it's supposed to loop through the array and pull out the highest inputted score, currently it's only outputting what is in studentScoreTF[0].      
    private class HighScoreButtonHandler implements ActionListener
               public void actionPerformed(ActionEvent e)
              double highScore = 0;
              int endScore = 0;
              double finalScore = 0;
              String tempHigh;
              String tempScore;
              for(int score = 0; score < studentScoreTF.length; score++)
              tempHigh = studentScoreTF[score].getText();
                    tempScore = studentScoreTF[endScore].getText();
              if(tempHigh.length() <  tempScore.length())
                   highScore++;
                   finalScore = Double.parseDouble(tempScore);
             JOptionPane.showMessageDialog(null, "Highest Class Score is: " + finalScore);This is another part of the program, it's supposed to loop through the student names array and pull out the the names of the students with the highest score, again it's only outputting what's in studentName[0].
         private class StudentsButtonHandler implements ActionListener
               public void actionPerformed(ActionEvent e)
              int a = 0;
              int b = 0;
              int c = 0;
              double fini = 0;
              String name;
              String score;
              String finale;
              String finalName = new String();
              name = studentNameTF[a].getText();
              score = studentScoreTF.getText();
              finale = studentScoreTF[c].getText();
              if(score.length() < finale.length())
                   fini++;     
                   name = finalName + finale;
         JOptionPane.showMessageDialog(null, "Student(s) with the highest score: " + name);
                   } Any help would be appreciated, this is getting frustrating and I'm starting to get a headache from it, lol.
    Edited by: SammyP on Oct 29, 2009 4:18 PM
    Edited by: SammyP on Oct 29, 2009 4:19 PM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    Heres a working example:
    class Compare {
        public int getHighest(int[] set) {
            int high = set[0];
            for(int i = 0; i < set.length; i++) {
                if(set[i] > high) {
                    high = set;
    return high;

  • I need help with event structure. I am trying to feed the index of the array, the index can vary from 0 to 7. Based on the logic ouput of a comparison, the index buffer should increment ?

    I need help with event structure.
    I am trying to feed the index of the array, the index number can vary from 0 to 7.
    Based on the logic ouput of a comparison, the index buffer should increment
    or decrement every time the output of comparsion changes(event change). I guess I need to use event structure?
    (My event code doesn't execute when there is an  event at its input /comparator changes its boolean state.
    Anyone coded on similar lines? Any ideas appreciated.
    Thanks in advance!

    You don't need an Event Structure, a simple State Machine would be more appropriate.
    There are many examples of State Machines within this forum.
    RayR

Maybe you are looking for