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.

Similar Messages

  • Search given string array and replace with another string array using Regex

    Hi All,
    I want to search the given string array and replace with another string array using regex in java
    for example,
    String news = "If you wish to search for any of these characters, they must be preceded by the character to be interpreted"
    String fromValue[] = {"you", "search", "for", "any"}
    String toValue[] = {"me", "dont search", "never", "trip"}
    so the string "you" needs to be converted to "me" i.e you --> me. Similarly
    you --> me
    search --> don't search
    for --> never
    any --> trip
    I want a SINGLE Regular Expression with search and replaces and returns a SINGLE String after replacing all.
    I don't like to iterate one by one and applying regex for each from and to value. Instead i want to iterate the array and form a SINGLE Regulare expression and use to replace the contents of the Entire String.
    One Single regular expression which matches the pattern and solve the issue.
    the output should be as:
    If me wish to don't search never trip etc...,
    Please help me to resolve this.
    Thanks In Advance,
    Kathir

    As stated, no, it can't be done. But that doesn't mean you have to make a separate pass over the input for each word you want to replace. You can employ a regex that matches any word, then use the lower-level Matcher methods to replace the word or not depending on what was matched. Here's an example: import java.util.*;
    import java.util.regex.*;
    public class Test
      static final List<String> oldWords =
          Arrays.asList("you", "search", "for", "any");
      static final List<String> newWords =
          Arrays.asList("me", "dont search", "never", "trip");
      public static void main(String[] args) throws Exception
        String str = "If you wish to search for any of these characters, "
            + "they must be preceded by the character to be interpreted";
        System.out.println(doReplace(str));
      public static String doReplace(String str)
        Pattern p = Pattern.compile("\\b\\w+\\b");
        Matcher m = p.matcher(str);
        StringBuffer sb = new StringBuffer();
        while (m.find())
          int pos = oldWords.indexOf(m.group());
          if (pos > -1)
            m.appendReplacement(sb, "");
            sb.append(newWords.get(pos));
        m.appendTail(sb);
        return sb.toString();
    } This is just a demonstration of the technique; a real-world solution would require a more complicated regex, and I would probably use a Map instead of the two Lists (or arrays).

  • Essbase export with a "string" appended with all account dimension members

    Hi Everyone ,
    can any one please suggest , how i can do my essbase export with a string appended with all account dimension members.
    i have tried more options but it doesn't looks working. i tried it by report scripts using RENAME function , but it works for 1 member at a time..
    please suggest !
    thanks
    Edited by: Vivek on Jun 19, 2012 6:55 PM

    Hi,
    If you're looking for the ability to append different strings, then you should probably be looking to an external process.
    If you're looking to append the same string, I can think of one way. Make your report script fixed-width (that way you always know which character in the line you're changing) and then utilize the MASK command. (you can find it in the Tech Ref under Report Commands)
    Robert

  • How to compare 2 arrays with different operator options using parameters in Teststand

    Pls let me know how to compare 2 arrays using different operators like <= or >= or ==......

     I am using TS 2010. FYI
    ex:
    Array XX [ A_Temp,
                   B_Temp,
                   C_Oil Pressure,
                   D_Oilpressure,
    Note : A_Temp, B_Temp,C_Oil Pressure,D_Oilpressure all these parameters will be getting  numerical values (dynamically) from the simulink models and also in future I may need to add parameters to this array.
    Array YY [A_Temp_1,
                   B_Temp_2,
                   C_Oil Pressure_3,
                   D_Oilpressure_4,
    Note : A_Temp_1, B_Temp_2,C_Oil Pressure_3,D_Oilpressure_4 all these parameters will be getting  numerical values (dynamically) from the simulink models
    So my question :
    I would like to verify A_Temp >= A_Temp_1
                                B_Temp >= B_Temp_2
                                C_Oil Pressure  >= C_Oil Pressure_3  etc

  • Initialising with a String Array

    My question ist probably very simple for you :-) But not for me at this time ...
    That's my class myAuto:
    class myAuto {
        String manufacturer;
        String model;
        String yearOfConstruction; // yyyy-MM-dd
        Double price;
        String optionalEquipment[];
        public myAuto(String ma, String mo, String yoc, Double pr, String oe[]) {
            this.manufacturer = ma;
            this.model = mo;
            this.yearOfConstruction = yoc;
            this.price = pr;
            this.optionalEquipment = oe;
    }I (unsuccessfully) am trying to initialise an object of this class:
    public class TestProgram {
        public static void main(String args[]) {
            myAuto ma = new myAuto("Mercedes", "SLK", "2010-04-08", "60000.0", {"leather","xenon","navi"});
    }This obviously is wrong ! How is it right?
    The String-Array optionalEquipment[] ist my problem.
    thank you

    The simple syntax for arrays (without the "new String[]") only works in initialization statements:
    String[] foo = {"bar", "baz" }; // OK!
    String[] bar;
    bar = { "quux", "frob" }; // NOT OK!
    bar = new String[] { "quux", "frob" }; // OK!Also: your classes should begin with a upper-case letter. Otherwise its not as easy to see which names are classes and which ones are methods/fields.

  • Trying to compare string array using equals not working

    Hi,
    im prolly being really dumb here, but i am trying to compare 2 string arrays using the following code:
    if(array.equals(copymearray))
    System.out.println("they match");
    else
    {System.out.println("dont match");}
    the trouble is that even though they do match i keep getting dont match, can anyone tell me why?

    try
    if (Arrays.equals(array, copymearray))
    System.out.println("they match");
    else
    {System.out.println("dont match");}

  • 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.

  • How can i combine a string array with a waveform array and write this to a file.

    I am trying to set my VI up so that I can enter test information (notes to myself) and combine that with the time and date then write this as well as the waveform data from the daq to a spreadsheet file.  I am sure this is a simple task but I am new to LabView so any help would be very appreciated.

    An XML file is not a spreadsheet-formatted file, so that's not likely to help...
    Simply call the Write To Spreadsheet File twice. The first time you wire in a 1D array of strings
    which is your test information. Then, you call it when you're writing out
    your data. Make sure you wire a True constant to the "append" input for
    that function.

  • Help with DIgital Output Array with 6062E DAQ CARD...

    Good morning, folks... I need some help with digital output of the 6062E PCMCIA card... I can output 1 line without problems... I need to control a 4066 with my digital outputs... I am doing this without greater problems... but there's something... I need that when one of my outputs is high, the others become low, unchangeably... so I tried to use an array to control my output and I couldn't do that... some errors showed up... can you help me please? Maybe there's any errors at my software, then I thank you if you help me... the vi is anexed...
    Best Regards...
    Attachments:
    Untitled 3.vi ‏20 KB

    See below for one of many methods. Change the "lines" string for your setup.
    Also, please explore the Examples that ship with LabVIEW, and read your card's manual.
    Richard

  • Strange issue with POF: byte array with the value 94

    This is a somewhat strange issue we’ve managed to reduce to this test case. We’ve also seen similar issues with chars and shorts as well. It’s only a problem if the byte value inside the byte array is equal to 94! A value of 93, 95, etc, seems to be ok.
    Given the below class, the byte values both in the array and the single byte value are wrong when deserializing. The value inside the byte array isn’t what we put in (get [75] instead of [94]) and the single byte value is null (not 114).
    Pof object code:
    package com.test;
    import java.io.IOException;
    import java.util.Arrays;
    import com.tangosol.io.pof.PofReader;
    import com.tangosol.io.pof.PofWriter;
    import com.tangosol.io.pof.PortableObject;
    public class PofObject1 implements PortableObject {
         private byte[] byteArray;
         private byte byteValue;
         public void setValues() {
              byteArray = new byte[] {94};
              byteValue = 114;
         @Override
         public void readExternal(PofReader reader) throws IOException {
              Object byteArray = reader.readObjectArray(0, null);
              Object byteValue = reader.readObject(1);
              System.out.println(Arrays.toString((Object[])byteArray));
              System.out.println(byteValue);
              if (byteValue == null) throw new IOException("byteValue is null!");
         @Override
         public void writeExternal(PofWriter writer) throws IOException {
              writer.writeObject(0, byteArray);
              writer.writeObject(1, byteValue);
    Using writer.writeObjectArray(0, byteArray); instead of writer.writeObject(0, byteArray); doesn't help. In this case byteArray would be of type Object[] (as accessed through reflection).
    This is simply put in to a distributed cache and then fetched back. No EPs, listeners or stuff like that involved:
         public static void main(String... args) throws Exception {
              NamedCache cache = CacheFactory.getCache("my-cache");
              PofObject1 o = new PofObject1();
              o.setValues();
              cache.put("key1", o);
              cache.get("key1");
    Only tried it with Coherecne 3.7.1.3.
    Cache config file:
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE cache-config SYSTEM "cache-config.dtd">
    <cache-config>
         <caching-scheme-mapping>
              <cache-mapping>
                   <cache-name>my-cache</cache-name>
                   <scheme-name>my-cache</scheme-name>
              </cache-mapping>
         </caching-scheme-mapping>
         <caching-schemes>
              <distributed-scheme>
                   <scheme-name>my-cache</scheme-name>
                   <service-name>my-cache</service-name>
                   <serializer>
                        <class-name>
                             com.tangosol.io.pof.ConfigurablePofContext
                        </class-name>
                        <init-params>
                             <init-param>
                                  <param-type>string</param-type>
                                  <param-value>pof-config.xml</param-value>
                             </init-param>
                        </init-params>
                   </serializer>
                   <lease-granularity>thread</lease-granularity>
                   <thread-count>10</thread-count>
                   <backing-map-scheme>
                        <local-scheme>
                        </local-scheme>
                   </backing-map-scheme>
                   <autostart>true</autostart>
              </distributed-scheme>
         </caching-schemes>
    </cache-config>
    POF config file:
    <?xml version="1.0"?>
    <pof-config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://xmlns.oracle.com/coherence/coherence-pof-config"
         xsi:schemaLocation="http://xmlns.oracle.com/coherence/coherence-pof-config coherence-pof-config.xsd">
         <user-type-list>
              <!-- coherence POF user types -->
              <include>coherence-pof-config.xml</include>
              <user-type>
                   <type-id>1460</type-id>
                   <class-name>com.test.PofObject1</class-name>
              </user-type>
         </user-type-list>
    </pof-config>

    Hi,
    POF uses certain byte values as an optimization to represent well known values of certain Object types - e.g. boolean True and False, some very small numbers, null etc... When you do read/write Object instead of using the correct method I suspect POF gets confused over the type and value that the field should be.
    There are a number of cases where POF does not know what the type is - Numbers would be one of these, for example if I stored a long of value 10 on deserialization POF would not know if that was an int, long double etc... so you have to use the correct method to get it back. Collections are another - If you serialize a Set all POF knows is that you have serialized some sort of Collection so unless you are specific when deserializing you will get back a List.
    JK

  • Problem with comparing text item with hidden item

    Hi all,
    I have two items, one text field which has a user name and other item which is hidden which also has a username input from a file.
    I want to compare these two items.
    But when both items are text fileds am able to compare, but when one is made hidden unable to compare.
    Please help on this......
    thanks,
    Srini

    Hi Srini,
    As long as you understand that the user can change the value of ANY field, even it is hidden, then I would suggest something like:
    1 - Hide your existing Login button. On the button definition, in "Button Display Attributes" add the following into the Attributes setting:
    style="display:none"2 - In the Login region's Region Footer, create a new button:
    &lt;input type="button" class="t12Button" value="Login" onclick="javascript:checkNames();"&gt;(Note that I have used a class name of "t12Button" - change this to match your current theme)
    3 - Underneath that, add in your javascript:
    &lt;script type="text/javascript"&gt;
    function checkNames()
    if ($v('field1name') == $v('field2name'))
      doSubmit('loginbuttonname');
    &lt;/script&gt;Then, when the user clicks the new Login button, this triggers your javascript. This checks that the values for field1name and field2name match. If they do, if fires the normal submit for the page (the same as if you clicked the original Login button)
    Andy

  • Searching two dimensional string arrays

    Hello, I'm very new to Java. I would like some advice on the code below. What I'm trying to do is: I want the user to enter a 9 digit number which is already stored in an two dimensional array. The array is to be searched and the 9 digit number and corresponding name is to be printed and stored for future reference. Something is wrong with my array checking. If I enter the nine digit number, the program errors and asks me again for the number. If I enter 0-4, I receive an output. I just don't know how to compare string array values. Could someone please help me with this?
    import java.io.*;
    import java.util.*;
    public class SocialSn2
         public static void main(String args[]) throws Exception
              boolean validSSAN = false;
              Ssn(validSSAN);
              if (validSSAN)
                   //Ssn(false);//write the code here to continue processing
         }//end main
         public static void Ssn(boolean Validated)
              String[][] employees =
                   {{"333333333", "Jeff"},
                   {"222222222", "Keith"},
                   {"444444444", "Sally"},
                   {"555555555", "Kaylen"},
                   {"111111111", "Sheriden"}     };
              boolean found = false;
              while (!found)
                   System.out.println("Enter the employee's Social Security number.");
                   BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
                   try
                        String line = in.readLine();
                        int input = Integer.parseInt(line); //added
                        found = false;
                        for(int j = 0; j < 5; j++)
                        if(input >= 0 && input <= employees.length)
                             //if(employees[j][0].equals(input))
                                  //System.out.println(employees[input][0] + employees[input][1]);
                                  found = true;
                             System.out.println(employees[input][0] + " " + employees[input][1]);
                   catch (Exception exc)
                        System.out.println("error");
                        found = false;
              Validated = found;
         }//end Ssn
    }//end class

    There seems to be some problem with your loop for checking those values
    if you had used System.err.println() in your catch block you would see that you were getting an ArrayIndexOutOfBoundsException
    The following works for me.
    import java.io.*;
    import java.util.*;
    public class SocialSn2
    public static void main(String args[]) throws Exception
    boolean validSSAN = false;
    Ssn(validSSAN);
    if (validSSAN)
    //Ssn(false);//write the code here to continue processing
    }//end main
    public static void Ssn(boolean Validated)
    String[][] employees =
    {{"333333333", "Jeff"},
    {"222222222", "Keith"},
    {"444444444", "Sally"},
    {"555555555", "Kaylen"},
    {"111111111", "Sheriden"} };
    boolean found = false;
    System.out.println(employees.length);
    System.out.println(employees[0].length);
    while (!found)
    System.out.println("Enter the employee's Social Security number.");
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    try
    String line = in.readLine();
    //int input = Integer.parseInt(line); //added
    found = false;
    for (int i=0; i< employees.length;i++)
         if(employees[0].equals(line))
         System.out.println(employees[i][0]+" "+employees[i][1]);
         found = true;
    catch (Exception exc)
    System.err.println(exc);
    found = false;
    Validated = found;
    }//end Ssn
    }//end class

  • How to add elements into java string array?

    I open a file and want to put the contents in a string array. I tried as below.
    String[] names;
    s = new Scanner(new BufferedReader(new FileReader("outfile.txt")));
    while (s.hasNext()) {
                    String item = s.next();
                    item.trim();
                    email = item;
                    names = email;
                }But I know that this is a wrong way of adding elements into my string array names []. How do I do it? Thanks.

    Actually you cannot increase the size of a String array. But you can create a temp array with the lengt = lengthofarray+1 and use arraycopy method to copy all elements to new array, then you can assign the value of string at the end of the temp array
    I would use this one:
    String [] sArray = null;
    s = new Scanner(new BufferedReader(new FileReader("outfile.txt")));
    while (s.hasNext()) {
        String item = s.next();
        item.trim();
        email = item;
        sArray = addToStringArray(sArray, email);
    * Method for increasing the size of a String Array with the given string.
    * Given string will be added at the end of the String array.
    * @param sArray String array to be increased. If null, an array will be returned with one element: String s
    * @param s String to be added to the end of the array. If null, sArray will be returned.(No change)
    * @return sArray increased with String s
    public String[] addToStringArray (String[] sArray, String s){
         if (sArray == null){
              if (s!= null){
                   String[] temp = {s};
                   return temp;
              }else{
                   return null;
         }else{
              if (s!= null){
                   String[] temp = new String[sArray.length+1];
                   System.arraycopy(sArray,0,temp,0,sArray.length);
                   temp[temp.length-1] = s;
                   return temp;
              }else{
                   return sArray;
    }Edited by: mimdalli on May 4, 2009 8:22 AM
    Edited by: mimdalli on May 4, 2009 8:26 AM
    Edited by: mimdalli on May 4, 2009 8:27 AM

  • WebService problem: only the first element of a string array is returned

    Hello,
    i did the J2EE QuickCarRental tutorial and extended it by some features: I created another entity bean and implemented four new methods in the QuickOrderProcessor. Then i deployed it as a WebService and accessed it using the Visual Composer.
    Everything works fine except the return value of one WebService method. I created a method with the return value String[]. But the Visual Composer reads it as String. Only the first element of the resulting string array is displayed. Although the test at the web-page http://<server>:<port>/QuickCarRentalService/Config1 displays the whole string array with all its elements. What did i wrong?
    Another problem is that after deploying the J2EE-Application with new WebService methods the changes are not visible inside the visual composer. Although the test at the web-page http://<server>:<port>/QuickCarRentalService/Config1 displays the changes. Do i have to restart the WebService system in the portal content? If yes how can i do that?

    Here are details about setting up and using web services and some examples:
    /people/prakash.darji/blog/2006/10/10/external-web-service-proxy-configuration-for-visual-composer

  • Trying to setText on random JPanels via a String array?

    My assignment is to create a bunch of JButtons, and randomly have an "X" appear on one, until it is clicked, and then it goes away and reappears on another random one. It does this ten times and displays the time it took to do so.
    I've created all the JButtons, named b01 to b48 and put them in a gridLayout. That part works fine.
    I created a String[] array with the 48 names of the JButtons in it, then I was thinking I could go this route...
    Random r = new Random();
    String random = panels[r.nextInt(panels.length)];
    random.setText("X");  //This is where the program hangs up.I can replace the setText statement with a System.out.println statement, and it shows up on the console correctly...

    Brandon,
    Have a chook at my minesweeper game at http://forum.java.sun.com/thread.jspa?forumID=54&threadID=5248903 ... it uses a matrix of cells[rows][cols]... each Cell is a JPanel which contains a Button.
    I think you'll end up with something like ...
      // create an array of Buttons
      Button buttons[] = Button[NUM_BUTTONS];
      for (int i=0; i<NUM_BUTTONS; i++) {
        buttons[] = new Button(i);
      // Xify a random button for a random time
      buttons[random.nextInt(NUM_BUTTONS)].xify()I'd create a:
    class Button extends JButton
    * provides a constructor(int index) which sizes and places the button according to it's index
    * provides an "xify" method, which setText("X"), then sets-up a SwingTimer to setText(null) after a random time.
    Cheers. Keith.

Maybe you are looking for

  • How can I get my Ipod to play on someone elses computer?

    How can I get my Ipod classic to play on someone elses computer.  Not my home computer where my library is stored?

  • Ant task to include Halo theme

    Hi, I recently migrated from Flex 3.4 to Flex 4. Everything works fine when I compile the application using Flash Builder 4. But I am having issues making our automated ant builds pick up the Halo theme over the Spark theme. In FB4, I just used the "

  • SQL Query in JDBC

    Can somebody guide me on this Q i have: 1. can we write 2 separate SQL statements when we configure a JDBC adapter?

  • Finder Resetting After Restart

    Hello, I recently restored my preferences folders, both on the Macintosh HD and my user account, from a Time Machine backup to solve a problem that I was having with my trackpad. I am now finding that whenever I add any shortcuts to my finder sidebar

  • Install on Imac from external DVD

    Hi I have a 2.16GHz intel core Duo Imac running 10.6.5 and I seem to be having niggly problems with it ie plug-ins quit in Safari etc. I have done all the normal things to put these right but they have not worked. Someone on the forum suggested that