.equals Problem in 2D Array

I get the problem, "int cannot be dereferenced" for cell[x][y].equals(1)) etc. How can I check if the cells have 1 in them correctly?
//Figures out how many neighbors the live cells have.
    for (int x = 1; x < row; x++)
       for (int y = 1; y < col; y++)
        if (cell[x][y].equals(1))
          if (cell[x--][y--].equals(1))
            neighbors++; 
          if (cell[x--][y].equals(1))
            neighbors++;
          if (cell[x--][y++].equals(1))
            neighbors++;
          if (cell[x][y--].equals(1))
            neighbors++;
          if (cell[x][y++].equals(1))
            neighbors++;
          if (cell[x++][y--].equals(1))
            neighbors++;
          if (cell[x++][y].equals(1))
            neighbors++;
          if (cell[x++][y++].equals(1))
            neighbors++;
    }            

Your code makes be nervous:
1. All those increments and decrements in the array subscripts -- do you really want to do that, or do you want to do this:
if (cell[x-1][y-1] == 1)2. Boundary conditions. I see that x and y start at 1, what happens when x is row-1 or y is col-1? will [x+1] or [y+1] be out-of-bounds?
3. Parentheses: do you realize this:
if (cell[x][y] == 1)
          if (cell[x--][y--] == 1)
            neighbors++; 
          if (cell[x--][y] == 1)
            neighbors++;
          if (cell[x--][y++] == 1)
            neighbors++;
          if (cell[x][y--] == 1)
            neighbors++;
          if (cell[x][y++] == 1)
            neighbors++;
          if (cell[x++][y--] == 1)
            neighbors++;
          if (cell[x++][y] == 1)
            neighbors++;
          if (cell[x++][y++] == 1)
            neighbors++;Is really this:
if (cell[x][y] == 1)
          if (cell[x--][y--] == 1)
            neighbors++; 
if (cell[x--][y] == 1)
    neighbors++;
if (cell[x--][y++] == 1)
    neighbors++;
if (cell[x][y--] == 1)
    neighbors++;
if (cell[x][y++] == 1)
    neighbors++;
if (cell[x++][y--] == 1)
    neighbors++;
if (cell[x++][y] == 1)
    neighbors++;
if (cell[x++][y++] == 1)
    neighbors++;

Similar Messages

  • Problem with an array (Array index out of bounds)

    Hey guys, i have a problem with an array, i just want to print a few things but it won't let me because of this error, here's my code
         public static void MosDat()
              int i;
              for(i=0 ; i<n ; i++);
                   Client [ i ].print1();
                   Client [ i ].print2();
              return;
         }//MosDat
    where "n" is a global variable, and client is .
    I pretty much know how it woks, so i tried it like this and gave "n" the value of "1":
    public static void MosDat()
              int i;
              for(i=0 ; i<n ; i++);
                   Client [ 0 ].print1();
                   Client [ 0 ].print2();
              return;
         }//MosDat
    the printing methods i created worked prefectly when i tried it like that... so i really don't know where the problem could be... thanks anyone who can help me.

    for(i=0 ; i < n ; i++);I spy with my little eye,
    one semicolon too many.Well-spotted. ;-)Practicing on those weird question marks is my secret training.

  • Using equals method with an array?

    Hello all,
    I am attempting to use the equals method with an array and keep getting compiling errors. Could you please take a look at my code and tell me where I am going wrong:
    if(board[row][col].equals(" "))
              str=str + " ";
              else
              str=str + board[row][col];
    Thank you.

    Hello all,
    I am attempting to use the equals method with an
    array and keep getting compiling errors. Could you
    please take a look at my code and tell me where I am
    going wrong:
    if(board[row][col].equals(" "))
              str=str + " ";
              else
              str=str + board[row][col];
    Thank you.If you could post more of your code, that would be quite helpful...

  • Problems declaring string array.

    I am having a problem declaring string arrays in a class that I am writing now. For some reason this code won't work:
    public class rotors()
    String[] rotor = new String[5];
    rotor [0] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    rotor [1] = "ACEGIKMOQSUWYBDFHJLNPRTVXZ";
    rotor [2] = "BDFHJLNPRTVXZACEGIKMOQSUWY";
    rotor [3] = "AEIOUYBCDFGHJKLMNPQRSTVWXZ";
    rotor [4] = "BCDFGHJKLMNPQRSTVWXZAEIOUY";
    }//end rotorsOn the other hand, this code will:
    public class rotors()
    String[] rotor={"ABCDEFGHIJKLMNOPQRSTUVWXYZ","ACEGIKMOQSUWYBDFHJLNPRTVXZ","BDFHJLNPRTVXZACEGIKMOQSUWY", "AEIOUYBCDFGHJKLMNPQRSTVWXZ",  "BCDFGHJKLMNPQRSTVWXZAEIOUY"};
    }//end rotorsI've noticed that the first code block that I posted will work, but only if I post it in a method, but not just hanging out in the class. Can anyone tell me why this is so? It seems odd to me that the first code doesn't work while the second one does. Thanks a lot
    Edited by: archangeleon on Oct 10, 2008 9:13 PM

    You can initialize a newly declared variable outside of a method/constructor/initializer block, but you can't call other statements outside of these blocks. The rotor array is declared here: String[] rotor... and can only be initialized (if at all) on this line.

  • Problems defining the array for quicksort

    import java.io.*;
    import java.util.*;
    import chn.util.*;
    public class Store
              private Item [] myStore;
              public Store (String fileName) {
                   fileName = "file50.txt";
    /*          public void displayStore ()       
              public String toString () { }
              public void doSort () { }
    */          private void quickSort (Item[] lit, int lo, int hi)   // I don't exactly know what Item[ ] lit will do. please explain it for me.
              int h, l, p, t;
            if (lo < hi) { 
                l = lo;
                h = hi;
          /*      p = a[hi];     //my problem starts with the array 'a' (suppose to be item, but don't know how to modify that.
                do {
                    while ((l < h) && (a[l] <= p)) l++;
                    while ((h > l) && (a[h] >= p)) h--;
                    if (l < h) {
                        t = a[l];
                        a[l] = a[h];
                        a[h] = t;
                } while (l < h);
                t = a[l];
                a[l] = a[hi];
                a[hi] = t;
              private void loadFile (String inFileName)
                   FileInput inFile = new FileInput (inFileName = "file50.txt");
    }The array 'a' should be replaced with the array 'Item' but some how I'm getting the errors that Item's not a valid type.
    for more information, please see http://forum.java.sun.com/thread.jspa?threadID=699397&tstart=60 for more information (the original problem)

    Here is what I suggest.
    Use collections. I suggest an ArrayList. Using one array involves all sort of messy swapping around which really will make things difficult for you to grasp the basic concept of.
    So let us assume a method like this
    public void quicksort(List items)
    items is a List of Items.
    So here is how to write a quicksort
    1) If the size of the list is 1 then return the list because it is down to it's final piece and doesn't need to be sorted further
    2) Choose a pivot element of your list. The mid point is often chosen for this.
    3) Create two new Lists. One for lower elements and one for higher and equal to elements.
    4) Go through the list and use compareTo to compare the elements of the list with your pivot element. Take care to skip the pivot element. If elements are less than the pivot put them in the first list. If they are more than or equal to put them in the second list.
    5) Recursively call quicksort(list) on the sublists we made.
    6) Merge the sublists and pivot values back into one list
    7) return the merged list

  • Problems Using an Array of Objects

    I have taken some time off from java and have aparently forgot something. I have a program which has one parent class "Car" with three child classes"Sedan", "Sport", "Suv" and one interface. The "Car" class contains three accessor and mutator methods, and the child classes also have three accessor and mutator methods. In my main I create an array Car[] carArray = new Car[6]; and instantiate. I can call the methods of the parent class but am unable to call the methods of the child classes. I need a little help to get me in the right direction to get these cobwebs out of my skull. Here is a sample of what I'm doing:
    //from my main method
    Car[] carArray = new Car[3];
    carArray[0] = new Sport("Chev", "Camaro", 1995, 4500.67, 120000);
    carArray[1] = new Sedan("Ford", "Taurus", 1997, 3689.55, 40000);
    carArray[2] = new Suv("Honda", "Pilot", 2003, 6955.99, 67000);
    for(int i = 1; i < carArray.length(); i++)
        carArray.getYear(); //getYear() is from the parent "Car" class and works just fine.
    carArray[i].getValue(); //getValue() also from the parent "Car" class and works just fine.
    carArray[i].getMiles(); //getMiles() from parent "Car" class and works.
    carArray[i].getMake(); //getMake() is part of the child class and gives me an error: "cannot find symbol. symbol: variable getMake()
    carArray[i].getModel(); //getModel() is also a part of the child classes and also cannot find symbol.
    {code}
    I have imported my package with my parent and child classes correctly and have tried putting them all in the same folder, so I think I have a failure in logic. Can someone help me straighten this out in my head? :) Much thanks

    "Is it A or B"?
    "Yes"
    Meaning "either one."
    The parent class doesn't have to be abstract as far as Java is concerned, but it seems to me you'd want it to be abstract. Will you ever be creating just a plain old Car (as opposed to a Sedan or Suv)?
    You just said "doesn't work," without providing any details about what you tried or what the exact problems was, so it's impossible to offer any specific, concrete advice. Here's an example that shows one way things might fit together.
       * inteface, to define the type, with 3 methods: add(), iterator(), and contains()
      public interface List {
        boolean add(Object obj);
        Iterator iterator();
        boolean contains(Object obj);
       * abstract base class, to implement methods that don't depend on specific implementations
       * (just contains() in this case
      public abstract class AbstractList implements List {
        public boolean contains(Object obj) {
          for (Iterator iter = iterator(); iter.hasNext ();) {
            if (iter.next ().equals (obj)) {
              return true;
          return false;
       * concrete subclass
       * provides concrete methods that depend on the specific implementation
      public class ArrayList extends AbstractList {
        private Object[] elements = new Object[256];
        int size = 0;
        public boolean add(Object obj) {
          if (size == elements.length) {
            // create a larger array and copy over existing elements
          elements[size++] = obj;
          return true;
         * anonymous inner class that implements Iterator
        public Iterator iterator() {
          return new Iterator() {
            private int nextIndex = 0;
            public boolean hasNext () {
              return nextIndex < size;
            public Object next () {
              return elements[nextIndex++];
      }A few things to note:
    0. The above are based on the classes of the same names in java.util, but are stripped down for simplicity. If something doesn't look right (like missing methods on List and Iterator) it was done to keep the example clean and simple.
    1. We could skip either the interface or the abstract class or both, or the abstract base class could be concrete. Java doesn't care. We do what makes sense for our design.
    2. Here we define an interface because we want to define a pure type with no implementation. Anybody anywhere can implement a List however they want, and as long as it meets the contract of our interface, it can be used by any code expecting a List.
    3. We define the base class AbstractList because there are methods that have a reasonable default implementation that can be reused by subclasses. In this case, contains() doesn't do anything that depends on the specific implementation, so it can be defined in the base class. All the subclasses can use that implementation of contains(). Of course, any subclass is still free to override contains() to provide its own implementation if it wants.
    4. An implementation of List can extend the base class, AbstractList, but it doesn't have to. It could just implement List and provide its own implementation of contains().
    5. The base class is abstract because some methods don't have a default implementation that can be reused. Both add() and iterator() depend on the specifics of the implementation. They both need direct access to the internal backing store. If we had another concrete implementation, LinkedList, its backing store would be a privately defined class of Node that contains the elements and pointers to previous and next. There would be no array, and add() and iterator() would be written very differently. There's no way we could have written add() and iterator() in a way that would have worked for both backing stores.
    6. All methods in an interface are public and abstract, even if you don't declare them that way.
    7. A class that implements an interface or extends an abstract class must provide implementations for all the abstract methods in both, or else must be itself declared abstract.
    8. When a class extends another class, it also implicitly implements all the interfaces that the parent class does.
    9. A class with one or more abstract methods must be declared abstract, but any class can be declared abstract, even if it has no abstract methods.
    Edited by: jverd on Mar 27, 2010 9:12 AM

  • Problem with an array

    i have problem with my program i implement saveing method
    but when i open file( game.txt) it does not update my board it return same postion every time i same game
    chess class Jframe(Jfilechooser)(call an board array)---->
    Gui Japplet class( call and board array------------>
    Board(class Jpanel have board array)
    it does not update borad array
    it just call it once in start and return the same value every time
    classChess(){
    ChessPlayer  java = new ChessPlayer();
    public  void saveData()
        File file = null;
       JFileChooser fc = new JFileChooser();
       fc.setCurrentDirectory(new File("."));
        fc.setDialogTitle("Save Text As...");
       int returnVal = fc.showSaveDialog(this);
       if (returnVal == JFileChooser.APPROVE_OPTION)
       { file = fc.getSelectedFile();
         try
         { PrintWriter out =
          new PrintWriter(
         new BufferedWriter(
           new FileWriter(file)));
         //while for all the moves in the array>
    for (int i=0;i<120;i++)
         out.println( java.saveDAta(i));
         out.println("\n");
         out.close();
         catch (IOException e) {
              // Some error has occured while trying to read the file.
                // Show an error message.
             JOptionPane.showMessageDialog(this,
                   "Sorry, some error occurred:\n" + e.getMessage());}
    public static void main(String[] args) {
    JPopupMenu.setDefaultLightWeightPopupEnabled(false);
         JFrame frame = new ChessMan();
         Container content = frame.getContentPane();
         ChessMan f = new ChessMan();
              //japplet
         ChessPlayer  javaAppletication = new ChessPlayer();
            javaAppletication.init();
            javaAppletication.start();
       }Gui
    [Gui]
    class Gui{
    int [] board = new int [120];
         int [] boardcolor = new int [120];     
    Board check = new Board(this,false);
    {public void init()
         {        // Create new Border
         contentPane = getContentPane();
         bboard = new Board(this,false);
    public String saveDAta(int i)
    String l=check. save(i);
    return (l);
    and finally board Jpanel
    class Board extends JPanel
    {public Board (JApplet useapplet,boolean bool) {
       setup();
    { public String  save(int i)
         {  String l;
                   if (color==1)
                 {System.out.println("notpossible");}
               l =  board[i]+"$"+boardColor;
    return l;
    thanks guys

    My Jframe
    public class ChessMan extends JFrame implements ActionListener, WindowListener  {
    JMenuItem saveItem, loadItem, copyItem, pasteItem; 
    JMenu fileMenu, editMenu; 
    JMenuBar bar;
    ChessPlayer  java = new ChessPlayer();
    public ChessMan()  { setTitle("CHESS PLAYER GAME" );
    setSize(200,300);
    System.out.println("\n");      }
    addWindowListener(new java.awt.event.WindowAdapter()
         {      public void windowClosing(java.awt.event.WindowEvent e)
         {        System.exit(0);      }    });
    JMenu fileMenu = new JMenu("File");
    saveItem = new JMenuItem("Save");
    saveItem.setActionCommand("save");
    saveItem.setAccelerator( KeyStroke.getKeyStroke("ctrl S"));
    saveItem.addActionListener(this);
    fileMenu.add(saveItem);
    loadItem = new JMenuItem("Load");
    loadItem.setActionCommand("load");
    loadItem.setAccelerator( KeyStroke.getKeyStroke("ctrl L"));
    loadItem.addActionListener(this);
    fileMenu.add(loadItem);
    JMenu editMenu = new JMenu("About");
    copyItem = new JMenuItem("Help");
    copyItem.setActionCommand("Help");
    copyItem.setAccelerator( KeyStroke.getKeyStroke("ctrl H"));
    copyItem.addActionListener(this);
    editMenu.add(copyItem);
    pasteItem = new JMenuItem("Exit");
    pasteItem.setActionCommand("Exit");
    pasteItem.setAccelerator( KeyStroke.getKeyStroke("ctrl E"));
    pasteItem.addActionListener(this);
    editMenu.add(pasteItem);
    JMenuBar bar = new JMenuBar();
    bar.add(fileMenu);
    bar.add(editMenu);
    setJMenuBar(bar);
    setVisible(true);
    setLocation(0,0);
    public void actionPerformed(ActionEvent e) {
    JMenuItem item = (JMenuItem)e.getSource();
    String    ac   = item.getActionCommand();
    System.out.println("ac = "+ ac);
    // you can use action commands to track menu item events   
    if(ac.equals("save"))
         {System.out.println("ac.equals(\"save\") = "+ ac.equals("save"));
            saveData();}
    if(ac.equals("load"))
    {System.out.println("ac.equals(\"load\") = "+ ac.equals("load"));
                         loadingData();}
       if(ac.equals("Help"))
    {System.out.println("ac.equals(\"load\") = "+ ac.equals("Help"));
    if(ac.equals("Exit"))
    {System.out.println("ac.equals(\"load\") = "+ ac.equals("Exit"));
                         Exit();}                   
    // the event origin  
    if(item == saveItem)
         System.out.println("item = "+ item.toString().substring
         (item.toString().indexOf("text=") + 5, item.toString().lastIndexOf("]")));
    if(item == loadItem)
         System.out.println("item = "+ item);
    //   System.out.print( java.saveDAta());
    public  void saveData()
        File file = null;
       JFileChooser fc = new JFileChooser();
       fc.setCurrentDirectory(new File("."));
        fc.setDialogTitle("Save Text As...");
       int returnVal = fc.showSaveDialog(this);
       if (returnVal == JFileChooser.APPROVE_OPTION)
       { file = fc.getSelectedFile();
         try
         { PrintWriter out =
          new PrintWriter(
         new BufferedWriter(
           new FileWriter(file)));
         //while for all the moves in the array>
    for (int i=0;i<120;i++)
         out.println( java.saveDAta(i));
         out.println("\n");
         out.close();
         catch (IOException e) {
              // Some error has occured while trying to read the file.
                // Show an error message.
             JOptionPane.showMessageDialog(this,
                   "Sorry, some error occurred:\n" + e.getMessage());}
       public  void loadingData()
       File loadfile = null;
       JFileChooser fc = new JFileChooser();
          fc.setDialogTitle("OpenFile...");
       fc.setCurrentDirectory(new File("."));
        int returnVal = fc.showOpenDialog(this);
       if (returnVal == JFileChooser.APPROVE_OPTION)
       { loadfile = fc.getSelectedFile();
          try
         { PrintWriter out =
         new PrintWriter(
         new BufferedWriter(
           new FileWriter(loadfile)));
         //while for all the moves in the array>
            out.println("�����������������");
         out.println("\n");
         out.close();
         catch (IOException e) {
              // Some error has occured while trying to read the file.
                // Show an error message.
             JOptionPane.showMessageDialog(this,
                   "Sorry, some error occurred:\n" + e.getMessage());}
    public void Exit()
    System.exit(0);
    public static void main(String[] args) {
    JPopupMenu.setDefaultLightWeightPopupEnabled(false);
         JFrame frame = new ChessMan();
         Container content = frame.getContentPane();
         ChessMan f = new ChessMan();
         f.setLocation(300,300);
         f.show();
                 ImageIcon customImageIcon = new ImageIcon("ac516.gif");
              Image customImage = customImageIcon.getImage();
              frame.setIconImage(customImage);
                 //japplet
         ChessPlayer  javaAppletication = new ChessPlayer();
         // i could not put my constructor here <Static>     
    javaAppletication.init();
    javaAppletication.start();
    // for(int i=0; i < .length(); i++)
    content.add(javaAppletication, BorderLayout.CENTER);
         frame.getContentPane();
    javaAppletication.setBackground (Color.black);
         frame.setVisible(true);
    frame.show();
    frame.pack(); // invokes getPreferredSize()
    // invokes paint();
    public void windowOpened(WindowEvent e) {
    fileMenu.doClick();
    public void windowClosing(WindowEvent e) {}
    public void windowClosed(WindowEvent e) {}
    public void windowIconified(WindowEvent e) {}
    public void windowDeiconified(WindowEvent e) {}
    public void windowActivated(WindowEvent e) {}
    public void windowDeactivated(WindowEvent e) {}
    My Japplet Class
    class ChessPlayer extends JApplet
         implements ActionListener,MouseListener              
    int c;
         //Reference for new Board
               Board bboard;
         //Reference for Button
             JButton newgame,undo,onePlayer,TwoPlayer,NormalPieceSet,
             FuunyPieceSet,startButton,stopButton;
         //Reference for Label  
              JLabel message;
        //Reference for new Panel
             JPanel buttonpanel2,buttonpanel,messagepanel,buttonpane;
         //Initilize the  Applet
          DemoAnimation Demo;
          Container contentPane;
           Board check = new Board(this,false);
               int [] board = new int [120];
           int [] boardcolor = new int [120];
         public void init()
                   // Create new Border
            contentPane = getContentPane();
         check = new Board(this,false);          
         bboard = new Board(this,false);
         bboard.setPreferredSize(new Dimension(500,400));
        bboard.setBorder(BorderFactory.createLineBorder( Color.red ) ); 
         contentPane.add(bboard);   
         final ImageIcon image = new ImageIcon("ac516.gif");
         bboard.addMouseListener(this);
         bboard.setBackground (Color.black); 
         BorderLayout text=new BorderLayout();
        Demo = new DemoAnimation( this );
         Demo.setPreferredSize(new Dimension(160, 500));
         contentPane.add(Demo);
        // Set Background Black
         contentPane.setBackground (Color.black); 
         contentPane.setLayout (new BorderLayout (50,50));
         // set new Font "TimesRoman"
         Font Text= new Font("TimesRoman", Font.BOLD,15);
         //panel to keep buttons together
         buttonpanel=new JPanel();
         buttonpanel.setLayout(new GridLayout(1,2,6,0));
         buttonpanel.add(newgame=new JButton("new game",image));
         newgame.addActionListener(this);
         buttonpanel.add(undo=new JButton("undo"));
         undo.addActionListener(this);
         // Create new Choice Panel                      
         buttonpanel2 = new JPanel();
         buttonpanel2.setLayout(new GridLayout(6,1,0,10));
         buttonpanel2.add(onePlayer=new JButton("Change Colour"));
         onePlayer.addActionListener(this);
         buttonpanel2.add(TwoPlayer=new JButton("Statistic"));
         TwoPlayer.addActionListener(this);
         buttonpanel2.add(NormalPieceSet=new JButton("Quit"));
         NormalPieceSet.addActionListener(this);
         buttonpanel2.add(FuunyPieceSet=new JButton("Change Piece"));
        FuunyPieceSet.addActionListener(this);
        buttonpanel2.add(startButton = new JButton("Start Animation"));
         startButton.addActionListener(this);
         buttonpanel2.add(stopButton  = new JButton("Stop Animation"));
         stopButton.addActionListener(this);
            contentPane.add(BorderLayout.WEST, demopanel);
    // Set Font For Text Message
         setFont(Text);
         messagepanel=new JPanel();
         messagepanel.setBorder(BorderFactory.createLineBorder( Color.red ) );
         messagepanel.setBackground(Color.black);
    //     essagepanel.setLayout(new GridLayout(1,1));
         // Create new Label
         messagepanel.add(message = new JLabel());               
         setMessage("Welcome");
         // Postion panels in  Layout                
         contentPane.add("North",buttonpanel);
         contentPane.add("East",buttonpanel2);
         contentPane.add ("South",messagepanel);     
         contentPane.add ("Center",bboard);
         contentPane.add("West",Demo);
    public void mouseReleased(java.awt.event.MouseEvent e)
    {  statuseChange();}
    public void mouseClicked(java.awt.event.MouseEvent e)
    public void mouseEntered(java.awt.event.MouseEvent e) {     
    public void mouseExited(java.awt.event.MouseEvent e) {
    public void mouseMoved(java.awt.event.MouseEvent e) {
    statuseChange();
    public void mousePressed(java.awt.event.MouseEvent e)
    {statuseChange();
    public void actionPerformed(ActionEvent e)
         Object source=e.getSource();
         if (source == newgame)
              {  bboard.newgame();
                yellow();
              setMessage("try again");
              pause(100);
              c=add(c);
         else if (source==undo)
                  yellow();
              bboard.undo();
         setMessage("Undo");
         else if (source== TwoPlayer )
              //bboard.setup();
                 yellow(); 
              setMessage("Starting new Game");
         setMessage("Change Color");
         else if(source == FuunyPieceSet)
              {yellow();
              setMessage("game played::" +c);
              bboard.PieceChange();
         else if(source == NormalPieceSet)
              {yellow();
              setMessage("GOODBYE");
              destroy();
          else if(source == startButton)
              {yellow();
              setMessage("Start Animation");
              Demo.start();
         else if(source == stopButton)
              {yellow();
              setMessage("Stop Animation");
              Demo.stop();
              else if(source == onePlayer)
              {setMessage("");
              bboard.changePiece();
              setMessage("Change Color");
           public void statuseChange()
                switch (bboard.gameStatus())
            case 1:
                red();
               setMessage("White won");
           break;
      case 2:
            red();
            setMessage("Black won");
         break;
      case 3:
          red();
           setMessage("DRAW");
         Demo.changeAnimation(2);
           break;
      case 4:
           white();
           setMessage("White Turn");
           Demo.changeAnimation(1);
           break;
      case 5:
           green();
           setMessage("Black turn");
           Demo.changeAnimation(3);
         break;
      case 6:
           red();
            setMessage(" Check");
            Demo.changeAnimation(4);
              break;
      case 7:
           red();
           setMessage("Check");     
            Demo.changeAnimation(4);
            break;
      case 8:
           yellow();
           setMessage("I Hope you enjoyed it");     
    public String saveDAta(int i)
    String l=check.save(i);
    return (l);   
    public void LoadData(String load)
    public void setMessage(String s)
                /*The string s will be shown to the user.*/
         Font Text= new Font("Courier", Font.BOLD,30);
                       message.setText(s);
                       message.setFont(Text);
              public void white()
                   {  message.setForeground(Color.white);}
              public void green()
                     message.setForeground(Color.green);
                   public void red()
                          message.setForeground(Color.red);
                   public void yellow()
                        message.setForeground(Color.yellow);
             //  pause method       
              void pause(int time)
      try {Thread.sleep(time);
    }     catch (InterruptedException e)
         // Create new inset Object
         public Insets getInsets()
         return new Insets(50,220,150,200);
    public void destroy()
    contentPane.remove(buttonpanel2);
    contentPane.remove(buttonpanel);
    contentPane.remove(bboard);
    contentPane.repaint();
    Demo.start();
    public int add(int x)
         { int b=x+1;
          return b;
    }tanx man i dont the other two because they are to long
    my is when i open jframe
    i think Japplet and Jframe can not commuinicate to each other

  • Problems with string arrays

    Previous task was:
    Write a class "QuestionAnalyser" which has a method "turnAnswerToScore". This method takes a String parameter and returns an int. The int returned depends upon the parameter:
    parameter score
    "A" 1
    "B" 2
    "C" 3
    other 0
    Alright, here's the recent task:
    Write another method "turnAnswersToScore". This method takes an array of Strings as a parameter, works out the numerical score for each array entry, and adds the scores up, returning the total.
    That's my code:
    class QuestionAnalyser{
    public static int Score;
    public String[] Answer;
    public static void main(String[] args) {}
         public int turnAnswerToScore(String[] Answer)
    for (int i = 0; i < Answer.length;i++) {
    if (Answer.equals("A")) {
    Score = Score + 1; }
    else if (Answer[i].equals("B")) {
    Score = Score + 2;}
    else if (Answer[i].equals("C")) {
    Score = Score + 3;}
    else {
    Score = Score + 0;}
    return Score;
    this is the error message I get:
    The results of trying to compile your submission and run it against a set of test data was as follows:
    ----------Compilation output--------------------------------------
    javac QATest2.java
    QATest2.java:15: cannot resolve symbol
    symbol : method turnAnswersToScore (java.lang.String[])
    location: class QuestionAnalyser
    if(qa.turnAnswersToScore(task)!=total){
    ^
    What went wrong?
    Suggestions would be greatly appreciated!

    If I declare int score in the method i get this message
    The results of trying to compile your submission and run it against a set of test data was as follows:
    ----------Compilation output--------------------------------------
    javac QATest2.java
    ./QuestionAnalyser.java:20: variable score might not have been initialized
    score++; }
    ^
    ./QuestionAnalyser.java:23: variable score might not have been initialized
    score++;
    ^
    ./QuestionAnalyser.java:27: variable score might not have been initialized
    score++;
    ^
    ./QuestionAnalyser.java:34: variable score might not have been initialized
    return score;
    ^
    4 errors
    ----------Sorry expected answer was-------------------------------
    The method turnAnswersToScore is working OK - well done!
    ----------Your answer however was---------------------------------
    Exception in thread "main" java.lang.NoClassDefFoundError: QuestionAnalyser
         at QATest2.main(QATest2.java:4)
    This is the message I get from the submission page, but trying to compile it I get the same messages.
    The code looks like this, then
    class QuestionAnalyser{
    String[] answer;
    public static void main(String[] args) {}
         public int turnAnswersToScore(String[] answer)
    int score;
    for (int i = 0; i < answer.length; i++) {
    if (answer.equals("A")) {
    score++; }
    else if (answer[i].equals("B")) {
    score++;
    score++; }
    else if (answer[i].equals("C")) {
    score++;
    score++;
    score++; }
    else {}
    return score;
    When I leave 'public int score;' where it was before (right after the class declaration below the declaration of the string array) I get this but it compiles normally.
    The results of trying to compile your submission and run it against a set of test data was as follows:
    ----------Compilation output--------------------------------------
    javac QATest2.java
    ----------Sorry expected answer was-------------------------------
    The method turnAnswersToScore is working OK - well done!
    ----------Your answer however was---------------------------------
    wrong answer in turnAnswersToScore for
    BDCAADDCA
    Alright, even university students need to sleep :-)
    Good night.

  • Performance Problems with intrinsic array multiplikation in Fortran with Su

    Hello,
    I found a serious performance problem in my application with intrinsic array multiplikation. Therefore I wrote a small test program to check if this a general problem or only exists in my code.
    The test program (as seen below) was compiled with Sunstudio12 und Solaris 5.10 on an 64 bit Amd Opteron Machine. First with high optimization (f95 -fast -g), and the second time with out optimization (f95 -O0 -g). In both cases the intrinsic array mupltiplication had a lot of tlb and L2 cache misses (I made some test with the performance analyzer) which caused a huge increase in computation time compared to the explicit loop. In the ideal case the compiler should create the nested loops from the intrinsic statement and both functions should use exactly the same computing time.
    I also tried compiling with Studio11, the problem also occurs there. Maybe its a compiler bug but I'm not sure.
    Greetings
    Michael Kroeger
    program test
    !Test zur Ausfuehrung einer einfachen array Multiplikation
    implicit none
    real,dimension(:,:,:),pointer::check1,check2
    integer i,j,k,ni,nj,nk,status
    ni=1000
    nj=1000
    nk=100
    allocate(check1(0:ni,0:nj,0:nk),STAT=status)
    write(*,*)status
    allocate(check2(0:ni,0:nj,0:nk),STAT=status)
    write(*,*)status
    check1(i,j,k)=25
    check2(i,j,k)=25
    call intrinsic_f(check1)
    call withloop(check2,i,j,k)
    deallocate(check1,check2)
    contains
    subroutine intrinsic_f(check1)
    real, dimension(:,:,:),pointer::check1
    check1=check1*5
    end subroutine intrinsic_f
    subroutine withloop(check2,ni,nj,nk)
    real, dimension(:,:,:),pointer::check2
    integer i,j,k,nk,nj,ni
    do k=0,nk
    do j=0,nj
    do i=0,ni
    check2(i,j,k)=check2(i,j,k)*5
    enddo
    enddo
    enddo
    end subroutine withloop
    end program

    I will try the large pages, but what me puzzles is, that the intrinsic function has cache misses, but the loop function has not. All documentation says, that the compiler would expand the intrinsic function into 3 nested loops, so that both functions should be essential the same (and the compiler says it has created 3 loops from the intrinsic). Since they are not the same, this is a severe problem.
    I have a fairly large code for high performance simulations, and this intrinsic functions are a significant bottle neck. If it is not a compiler bug, I would have to rewrite all intrinsic functions into loops.

  • Please Help!-Problem using Image[ ] array

    Hi everyone,
    I have this real confusing bug in my code which i am not able to fix.
    Image[] tmpImg = new Image[Img.size()];   /initializing an image array tmpImg
                for(int i=0; i<Img.size(); i++) {          //i require this display the image a number of times
                try{
                       icon = Image.createImage("/Icon.png");
                       im = new ImageItem("Image", icon,ImageItem.LAYOUT_CENTER,"image"); //using a imageItem to display the image in a form
                       form.append(im);
                       icon2 = Image.createImage("/Icon2.png");
                           im2 = new ImageItem("Image2",icon2,ImageItem.LAYOUT_CENTER,"image"); //using another imageItem to display the second image
                      form.append(im2);
                       if (imageValue.elementAt(i) == "availableImage") {
                           tmpImg[i] = icon;  //assigning the value to the image array based on a condition from a String Vector
                      if (imageValue.elementAt(i) == "offlineImage") {
         tmpImg[i] = icon2;   //assigning the value to the image array based on a condition from a String Vector
                      } catch(IOException err) {}
           System.out.println(tmpImg[0]);
           System.out.println(tmpImg[1]);
           System.out.println(tmpImg[2]);
           System.out.println(tmpImg[3]);
           return tmpImg;
       }My problem is that when i try to print tmpImg[0], tmpImg[1] etc all the values are printed null. But the Image is created and being displayed on a ImageItem. but i am not able to assign the image to the image array 'tmpImg' which is within an if condition.
    Can anyone tell me why is this so. I would be grateful
    Thank You

    Thank u deepspace
    I got a lil' frustrated, so completely did not think that way. The code is working now
    Thanx again

  • Fustrating equality problem, pls help

    Hello ppl. Im here with a rather silly but fustrating problem...
    I have a conditional like this:
    String host = request.getRemoteHost();
    if(host != "localhost"){
    // code...
    Im the localhost and the value of host is localhost but java thinks otherwise, so therefore the conditional returns false and the code is executed! WHY?? I've even tried this...
    if(String.valueOf(host) != "localhost"){
    // code...
    That still didnt work! I dont want that piece of code executing if the host value is localhost. Help appreciated. Thanks.

    Thanks jesperdj that worked a treat. I was aware of the equals() method but i wasnt quite sure how to test for unequality using the equals() method. Thanks.

  • Problem in displaying Array Position?

    hi,
    I am having a problem in displaying the array position of a sorted Array
    for ex:
    int[] a = {4,3,1,7}for sorting the array i am using Arrays.sort(a); then the output will be
    a = {1,3,4,7}now according to this i need to display the array position of a before sorting like a should have the output {2,1,0,3} which should be the array position of the sorted array. Any help will be appreciated.
    Thanks.

    for (int i = 0 ; i < unsortedArray.length ; i++)
       for (int j = 0 ; j < sortedArray.length ; j++)
           if (unsortedArray[i] == sortedArray[j]) {
                 System.out.println("position for element "+i+" is "+j);
                 break;
           }notice that if you have duplicate values, the position of the duplicate will always be considered as the first occurence of this value

  • Problem with Point-Array

    I made the following method:
    Point[] makeLine (int length)
              Point[] newLine = new Point[length];
              for (int i = 0; i < newLine.length; i++)
                   newLine.x = i;
                   newLine[i].y = (int)Math.round(Math.random()*5+1);
              return newLine;
    to make a Line that randomly jumps and stuff.
    Compiles fine, but when i want to run it i get a NullPointerExeption at
    newLine.x = i;
    when i comment that one out i get the same error on the line after .
    I absolutely cant find the mistake, can anybody help me please?
    Thanks in advance

    You have defined an array, but you need to put objects into the array. i.e. when an array is created, every value is initlaised to null. The OO way to do this is
    newLine[i] = new Point(i, (int) (Math.random()*5+1));Note round may not be the best choice as this will round down/up 50% of the time. This means each value does not have an equal chance of occuring.

  • Problem with cloning Array

    I got a problem with cloning a Point[] Array.
    for example i have 2 Point-Arrays declared as Membervariables:
    Point[] array1;
    Point[] array2;then in the constructor i filled array1 with random Point Objects
    and then
    array2 = (Point[])(array1.clone());then i, for example, add 5 to the x-coordinate of every Point in array2.
    for (int i = 0; i < array2.length; i++)
         array2.x += 5;
    But array1's Point objects are also changed when i do that!
    Shouldnt clone copy the whole array and leave no connection between them?
    Thanks in advance

    so i made a method copyArray where every point object's x and y value is copied into the new Array's new Point Object, but as it seems that isnt where the error comes from.
    (That method works fine, the arrays are identical after that, but shouldnt reference to the same chunk of memory, right?)
    then i run the following method on array2
    array2 = (Point[])addFive(array2);
    Point[] addFive(Point[] array)
                    array[0].x += 5;
              return line;
         }Hence array2[0].x is instead of, e.g., zero 5
    But array1[0] .x is 5 intead of 0 too!
    Where's the mistake, where's the reference left? =X (and how do i fix it? :))

  • KT4 Ultra: problem config. raid array IDE3

    I owe the MSI 6590 KT4 Ultra BSR mainboard and I have difficulties configurring the RAID array in striping mode, on the IDE3 controller.
    The manual describes on page 2-18 it's possible to connect up to 2 hard drives, cdrom, 120mb fd and other devices to the IDE3 controller.
    Unfortunately only one of my two MAXTOR D740X-6L (6L080J4) 80gig drives is recognized by the array.
    One Maxtor hard drive is jumpered as MASTER and the other is set up as SLAVE.
    When I hook up the cable to an ordinary IDE port (eg IDE1) the two drives are properly recognized.
    Both drives can be formatted using the regular IDE ports, this means without any cluster errors or other errors so the drives are physically OK.
    Before I wrote this post I checked the support section again to make sure I am using the latest BIOS which is 1.1. I also downgraded to 1.0, but that didn't solve my problem either.
    Since I work in a computer shop now and then I had the opportunity to check two Maxtor Fireball3 30gig drives on a different MS-6590 RAID board (BIOS 1.1.) and exactly the same problem occurs: the 2nd drive won't be recognized in the ARRAY on IDE3.
    Please tell me what to do to make the striping option fully work on my two IDENTICAL Maxtor hard drives since MSI support came up with a standard email, which didn't cheer me up at all. Hopefully this time they will investigate this matter since no doubt more people will experience this.

    Thanks for the quick response, though it's not satisfactory for me (of course).
    Actually before installing the new KT4 Ultra I owed the KT266 Pro RAID motherboard. It's true this board has two controllers for the RAID option. Nevertheless because after reading the manual of this new board I was convinced I could connect two hard drives on the IDE3-channel. This is the reason I decided to go ahead and to upgrade to this new mainboard.
    I guess I have to go back to my employer and fall back again to my KT266 (MS6380).

Maybe you are looking for