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.

Similar Messages

  • Problems with string array, please help!

    I have a String array floor[][], it has 20 rows and columns
    After I do some statement to modify it, I print this array
    out in JTextArea, why the output be like this?
    null* null....
    null null...
    null null...
    How to correct it?

    a turtle graphics applet:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class TG extends JApplet implements ActionListener {
      private int x, y;
      private int pendown, command, movement;
      String direction, output, temp;
      JLabel l1;
      JTextField tf1;
      JTextArea ta1;
      String floor[][] = new String[20][20];;
      public void init()
        x = 0;
        y = 0;
        pendown = 0;
        direction = "r";
        Container c = getContentPane();
        c.setLayout( new FlowLayout() );
           l1 = new JLabel( "Please type a command:" );
           c.add( l1 );
           tf1 = new JTextField(20);
           tf1.addActionListener( this );
           c.add( tf1 );
           ta1 = new JTextArea(20,20);
           ta1.setEditable( false );
           c.add( ta1 );
    public void actionPerformed( ActionEvent e )
           temp = tf1.getText();
           if( temp.length() > 1)
           command = Integer.parseInt(temp.substring(0,1));
           movement = Integer.parseInt(temp.substring(2,temp.length()));
           else
           command = Integer.parseInt(temp);
           switch(command)
                case 1:
                pendown=0;
                break;
                case 2:
                pendown=1;
                break;
                case 3:
                direct("r");
                break;
                case 4:
                direct("l");
                break;
                case 5:
               move(movement);           
                break;
                case 6:
                print();
                break;                                     
      public void direct(String s)
           if(direction == "r" && s =="r")
              direction = "d";
           else if(direction == "r" && s =="l")
              direction = "u";
           else if(direction == "l" && s =="r")
              direction = "u";
           else if(direction == "l" && s =="l")
              direction = "d";
           else if(direction == "u" && s =="r")
              direction = "r";
           else if(direction == "u" && s =="l")
              direction = "l";
           else if(direction == "d" && s =="r")
              direction = "l";
           else if(direction == "d" && s =="l")
              direction = "r";
      public void move(int movement)
           if(pendown == 1)
                if(direction == "u")
                for(int b=0;b<movement;b++)
                     floor[x][y+b] = "*";
                else if(direction == "d")
                for(int b=0;b<movement;b++)
                     floor[x][y-b] = "*";
                else if(direction == "l")
                for(int b=0;b<movement;b++)
                     floor[x-b][y] = "*";
                else if(direction == "r")
                for(int b=0;b<movement;b++)
                     floor[x+b][y] = "*";
            else if(pendown == 0)
                 if(direction == "u")
                for(int b=0;b<movement;b++)
                     floor[x][y+b] = "-";
                else if(direction == "d")
                for(int b=0;b<movement;b++)
                     floor[x][y-b] = "-";
                else if(direction == "l")
                for(int b=0;b<movement;b++)
                     floor[x-b][y] = "-";
                else if(direction == "r")
                for(int b=0;b<movement;b++)
                     floor[x+b][y] = "-";
          public void print()
         for(int row=0;row<20;row++)
           for( int column=0;column<20;column++)
                output += floor[row][column];
                if(column == 19)
                 output+="\n";
            ta1.setText(output);
    }

  • Problem with String variable

    I am new to Java Programming.
    I have a line of code that works and does what is supposed to.
    faceData.getProfile("Lisa").removeFriend("Curtis");
    If I assign the strings to variables such as-
    String name = "Lisa";
    String fName = "Curtis";
    and then plug those into the same line of code, it does not work
    faceData.getProfile(name).removeFriend(fName);
    What could be causing the problem?
    I even added some lines to print out what is stored in the variables to verify that they are what they should be, but for some reason the variables do not work while putting the strings in quotes does. Any ideas?

    I guarantee that something about your assertions are incorrect. Those variables are either not equal to the values you claim, or something else is going on. But it's not a problem with string variables versus string constants.
    Edit: My best guess in lack of a real example from you, is that the strings in question have non-printable characters in them, such as trailing spaces or line feeds.

  • Little problem with Strings.

              I have an little problem with Strings, i make one comparision like this.
              String nombre="Javier";
              if( nombre.equalsIgnoreCase(output.getStringValue("CN_NOMBRESf",null)) )
              Wich output.getStringValue("CN_NOMBRESf",null) is "Javier" too, because I display
              this before and are equals.
              What I do wrong?.
              

    You are actually making your users key in things like
    "\026"? Not very user-friendly, I would say. But
    assuming that is the best way for you to get your
    input, or if it's just you doing the input, the way to
    change that 4-character string into the single
    character that Java represents by '\026', you would
    use a bit of code like this:char encoded =
    (char)Integer.parseInt(substring(inputString, 1),
    16);
    DrClap has the right idea, except '\026' is octal, not hex. So change the radix from 16 to 8. Unicode is usually represented like '\u002A'. So it looks like you want:String s = "\\077";
    System.out.println((char)Integer.parseInt(s.substring(1), 8));Now all you have to do is parse through the String and replace them, which I think shouldn't be too hard for you now :)

  • Problem with String to Int conversion

    Dear Friends,
    Problem with String to Int conversion
    I am having a column where most of the values are numeric. Only 4 values are non numeric.
    I have replaces those non numeric values to numeric in order to maintain the data type.
    CASE Grade.Grade  WHEN 'E4' THEN '24'  WHEN 'E3' THEN '23'  WHEN 'E2' THEN '22' WHEN 'E1' THEN '21' ELSE Grade.Grade  END
    This comes the result as down
    Grade
    _0_
    _1_
    _10_
    _11_
    _12_
    _13_
    _14_
    _15_
    _16_
    _17_
    _18_
    _19_
    _2_
    _20_
    _21_
    _22_
    _23_
    _24_
    _3_
    _4_
    _5_
    _6_
    _7_
    _8_
    _9_
    Refresh
    Now I want to convert this value to numeric and do some calculation
    So I changed the formula as below
    cast (CASE Grade.Grade  WHEN 'E4' THEN '24'  WHEN 'E3' THEN '23'  WHEN 'E2' THEN '22' WHEN 'E1' THEN '21' ELSE Grade.Grade  END as INT)
    Now I get the following error
    View Display Error
    _     Odbc driver returned an error (SQLExecDirectW)._
    Error Details
    Error Codes: OPR4ONWY:U9IM8TAC:OI2DL65P
    _State: HY000. Code: 10058. [NQODBC] [SQL_STATE: HY000] [nQSError: 10058] A general error has occurred. [nQSError: 17001] Oracle Error code: 1722, message: ORA-01722: invalid number at OCI call OCIStmtFetch. [nQSError: 17012] Bulk fetch failed. (HY000)_
    SQL Issued: SELECT cast ( CASE Grade.Grade WHEN 'E4' THEN '24' WHEN 'E3' THEN '23' WHEN 'E2' THEN '22' WHEN 'E1' THEN '21' ELSE Grade.Grade END as Int) saw0 FROM "Human Capital - Manpower Costing" WHERE LENGTH(CASE Grade.Grade WHEN 'E1' THEN '20' WHEN 'E2' THEN '21' WHEN 'E3' THEN '22' WHEN 'E4' THEN '23' ELSE Grade.Grade END) > 0 ORDER BY saw_0_
    Refresh
    Could anybody help me
    Regards
    Mustafa
    Edited by: Musnet on Jun 29, 2010 5:42 AM
    Edited by: Musnet on Jun 29, 2010 6:48 AM

    Dear Kart,
    This give me another hint, Yes you are right. There was one row which returns neither blank nor any value.
    I have done the code like following and it works fine
    Thanks again for your support
    Regards
    Code: cast (CASE (CASE WHEN Length(Grade.Grade)=0 THEN '--' ELSE Grade.Grade END) WHEN 'E4' THEN '24' WHEN 'E3' THEN '23' WHEN 'E2' THEN '22' WHEN 'E1' THEN '21' when '--' then '-1' ELSE Grade.Grade END as Int)

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

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

  • Problem with String in JSP! Help Me

    Hi all,
    i spent my whole day with this error. How can i solve it. I am trying to convert a string array to Integer array. The program is taking all the select input from the previous JSP page and then converting them into integer array for storing to database. i am catching them as request.getParameterValues(); but i found out that if i select 4 item from the menu it is storing in 8 array cells and the format is if you select 1 2 3 4 the it stores [1 null 2 null 3 null 4 null] i guessed that those are null values. so i have tried to select only 1 2 3 4 from the array and it is showing number format error on tomcat. here is the code guys. Please i am tired of it please help me. Thanks. SORRY I TRIED TO SEPARATE THE CODE BUT IT SEEMS LIKE THERE ARE SOME PROBLEM IN THE FORUM SETTINGS. so the code is:
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
    <%@page import="java.io.*"%>
    <%@page import="java.sql.*"%>
    <%@page import="java.lang.String.*"%>
    <%@page import="java.lang.Character.*"%>
    <%@page import="java.util.*"%>
    <%@page import="java.text.*"%>
    <HTML>
    <HEAD>
    <TITLE> HR ADVANTAGE TIMESHEET </TITLE>
    </HEAD>
    <BODY>
    <%
    String emplno = request.getParameter("emplno");
    String date = request.getParameter("date");
    String proposal = request.getParameter("proposals");
    String network1 = request.getParameter("network");
    String suppassociates = request.getParameter("suppasso");
    String intmngt = request.getParameter("intmgt");
    String client[] = request.getParameterValues("client");
    String client1= request.getParameter("client1");
    String clientunit[] = request.getParameterValues("clientunit");
    String clientunit1=request.getParameter("clientunit1");
    boolean bool=true;
    int staffid = Integer.parseInt(emplno);
    int len=0;
    len=client.length;
    //String[] check_client = new String[len];
    //check_client=client;
    //int check_length=0;
    //check_length=check_client.length;
    //int unitlength=0;
    //unitlength=clientunit.length;
    int arr_length=0;
    arr_length=len-(len/2);
    int[] array = new int[arr_length];
    int j=0;
    j=arr_length;
    for (int i=0; i<len-1; i++)
    bool=true;
    if(client=="\0")
    bool=false;
         if(bool==true)
         array[arr_length-j]=Integer.parseInt(client[i]);
              j=j-1;
              if(j==0)
              break;
    %>
    </BODY>
    </HTML>
    The error is:
    org.apache.jasper.JasperException: For input string: ""
         org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:367)
         org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:293)
         org.apache.jasper.servlet.JspServlet.service(JspServlet.java:240)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:856)
    root cause
    java.lang.NumberFormatException: For input string: ""
         java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
         java.lang.Integer.parseInt(Integer.java:489)
         java.lang.Integer.parseInt(Integer.java:518)
         org.apache.jsp.store_jsp._jspService(store_jsp.java:107)
         org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:136)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:856)
         org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:320)
         org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:293)
         org.apache.jasper.servlet.JspServlet.service(JspServlet.java:240)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:856)

    what are you trying to test with client [ i ] == "\0"
    You sure you dont need to test against null ?

  • 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

  • Problem with String in a Vector

    I'm making a small hangman game. And I got a problem with putting words in a Vector... This is the code... Can someone tell me what I'm doing wrong?
    // First I define it.
    Vector Words;
    //  Then add the words
    Vector Words = new Vector();
    Words.add(new String("HELLO"));
    Words.add(new String("GOOD BYE"));
    // When I try to get a string from the Vector I use this.
    // The program compiles but when I try to run it I get NullPointerExeption here
    W = (String) Words.elementAt(0);

    Not sure since I cant see all of your code but looks like this might be your problem:
    // First I define it.
    Vector Words; //<-- here you define a Vector named Words that is null
    // Then add the words
    Vector Words = new Vector(); //<-- here you define another vector named Words that holds a reference to a new Vector. This is a different reference than the one created above so you should probably remove the "Vector" part from the beginning of this line. Is this a local variable to a method and the one before is a global variable?
    //Here you probably access the locally created Words vector which is initialized
    Words.add(new String("HELLO"));
    // When I try to get a string from the Vector I use this.
    // The program compiles but when I try to run it I get NullPointerExeption here
    W = (String) Words.elementAt(0); //<--and here my guess is that this statement is inside another method than the one with the local Words vector defined. Thus this one accesses the global Words Vector that is never initalized and is Null. And that gives you the NullPointerException.
    So try changing the statement
    Vector Words = new Vector();
    to
    Words = new Vector();
    or just remove it totally and move the Vector creation to the place where you introduce the global variable.
    Of course I might be totally wrong since I cant see all of your code but that is my guess.
    Hope it helps,
    -teka

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

  • StringTokenizer class problem with strings in double quotes

    Hello Technocrats,
    I have a problem with tokenizing following string enclosed in (). (abc," India, Asia", computer engineer). My separator is ",", thus StringTokenizer class gives me 4 tokens namely abc, "India, Asia" and computer engineer. But I require that String in double quotes should be a single token. How to achieve this using StringTokenizer class? Or is there any other way?
    Thanks in advance.

    Try
    String[] str="abc,\" India, Asia\",computer engineer".split(",",1);
              for(String s: str)
                   System.out.println(s);
              }Thanks.

  • 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? :))

  • Problem with building array inside a case statement

    I have a problem with my build array.
    Iam trying to construct a build array when ever I see a new element in my parent array during run time.
    Using shift registers, search array and If- case structure, inside a while loop. Iam implementing this logic (I dont want to use Event structure).
    Iam able to achieve most part of it, but have a problem with the first element. Except the first element of my parrent array, every thing is appending in to the build array. Can any one look at my vi and suggest me what Iam doing wrong here.
    Thank you
    Attachments:
    debug.vi ‏12 KB

    I think you need to replace the tunnels (carrying the array) in the for loop with a shift register.
    Lynn

  • Problems with an array (attachMovie)

    I've created a 20 x 20 grid of objects (openCircles). They're set to 'alpha = 0', then 'alpha = 100' on rollover. This works for all of them except for the final one at the coordinate T,20 in the bottom right corner, as I'm not able to rollover over it. To test whether or not they all existed, I set them all to an initial value of 'alpha = 100' and they did all appear, but I'm still unable to rollover the one at T20.
    The other problem is that when an 'openCircle' is clicked, a 'filledCircle' (set up as another grid of invisible objects in the same place) is supposed to appear in its place. That doesn't happen. All of the objects are created and exist, using attachMovie, so it's maybe due to some logical error. See code:-
    I'd be grateful for any help. Many thanks.
    stop();
    //The purpose of this experiment is to locate a trap of oil. Only 30 exploration holes are allowed.
    //Use the grid coordinate to locate the borehole and then plot the depth
    //Drilled is set to false in the 1st(previous) frame
    //Rolling over a grid coordinate will reveal a borehole (open circle).
    //Click on the borehole (open circle) to start drilling
              //open circle will be removed
              //drilled is set to true for that coordinate
              //filled circle will appear in its place
    //set up variables for grid array of open circles (undrilled) and closed circles (drilled)
    var spacing:Number = 5.75;
    var cols:Number = 20; // number of columns in grid
    var rows:Number = 20; // number of rows in grid
    var leftMargin:Number = 154;
    var topMargin:Number = 169;
    var currentRow:Number = 0;
    var currentCol:Number = 0;
    for (i=1; i<=rows; i++) {                                                                                                         
    for (j=1; j<=cols; j++) {                                                                                                                              
              current = attachMovie("openCircle_mc", "openCircle_mc"+i+"_"+j,getNextHighestDepth());
              current._x = leftMargin + ((i-1) * (spacing + current._width));
              current._y = topMargin + ((j-1) * (spacing + current._height));
              current2 = attachMovie("filledCircle_mc", "filledCircle_mc"+i+"_"+j, getNextHighestDepth());
              current2._x = leftMargin + ((i-1) * (spacing + current2._width));
              current2._y = topMargin + ((j-1) * (spacing + current2._height));
              //open circle initially invisible, then visible on rollOver
              current._alpha = 0;
              //filled circles initially invisible
              currentCol2=(current2._x-leftMargin)/(spacing + current2._width);
              currentRow2=(current2._y-topMargin)/(spacing + current2._height);
                                     if (drilled[currentCol,currentRow]==true){
                                                      current2._alpha = 100;
                                                      }else{
                                                                current2._alpha=0;
              //open circle visible on rollover
              current.onRollOver = function() {
                                     this._alpha = 100;
                                     currentCol=(this._x-leftMargin)/(spacing + current._width);
                                     trace("current column ="+currentCol);
                                     currentRow=(this._y-topMargin)/(spacing + current._height);
                                     trace("current row ="+currentRow);
                                     if (drilled[currentCol,currentRow]==false){
                                              trace("Click on the grid point to drill at "+rowLabel[currentRow]+","+colLabel[currentCol]);
                                  }else{
                                              trace("Click on the grid point to review the core at "+rowLabel[currentRow]+","+colLabel[currentCol]);
                                  }     //end 'if-else'
              //open circle invisible on rollout
              current.onRollOut = function() {
                                     this._alpha = 0;
                                     trace("No grid point selected")
              //click on open circle - variable drilled becomes true
              current.onRelease=function(){
                        drilled[currentCol,currentRow]=true;
                        trace(drilled[currentCol,currentRow]);
                        this.removeMovieClip();
    This is an image of the grid showing an 'openCircle' visible when rolled over

    Thanks for the explanation. That was very helpful.
    However, I am having problems with the variables. I did as you suggested though and extended the (grid) layer, but had to create a separate keyframe for the code layer, as that code had to execute first before moving into the next frame. See below (I've also attached the fla, but if you need any more information, please let me know):
    In frame 2 of the animation, if an open circle mc is clicked, that mc is deactivated (removed), drilled becomes true for that coordinate, a filled circle becomes visible in its place and you enter another frame(3) (this is currently just a test frame), to later be used to implement the drilling animation for a clicked coordinate.
    It all seems to be working as it should, until the open circle is clicked and you enter frame 3. See below:
    All the instances of the openCircle mc's are still active in frame 3, so I guess I need to use removeMovieClip(). I know how to do that for a single instance, but howdo I execute that if they're in an array?
    I also don't want any instances of the filledCircles from frame 2 to be visible in frame 3. I'm not sure how to hide them temporarily in frame 3 and then have them visible again in frame 2?
    When I go back to frame 2 (using a back button), all of the filled circles in the array are visible, whereas only the ones that have been previously clicked (drilled = true) should be visible. However, when I return to frame 2 and do a trace to find out which coordinates are set to true/false, it seems that a whole row is now set to (drilled = true), whereas it should just be a single coordinate set to true. Oddly enough, the variable seems to working properly in frame 2 when the code is first executed, but then when I go to frame 3 and then re enter frame 2, it's not working as it should do. Below is the trace code that I've used:
    if (drilled[currentCol,currentRow] == false) {
                                            trace("Click on the grid point to drill at " + rowLabel[currentRow] + "," + colLabel[currentCol]);
                                  } else {
                                            trace("Click on the grid point to review the core at " + rowLabel[currentRow] + "," + colLabel[currentCol]);
    If you could help, I'd be very grateful! Very many thanks.
    http://synergese.co.uk/boreholes15.fla
    Message was edited by: Pippa01
    Sorry, Although the original question was correct, I've just unmarked it as correct. Maybe, I should have started it as a new thread?

Maybe you are looking for

  • 3D on Mac

    Hi, i am really interested in 3D but cant afford a 3DTV. Ive heard their are ways of viewing 3d through reald 3d but not sure how. is their in media players for 3d? i have a set on red on left and cyan on right glasses too... but when watching on you

  • HT5731 How can i transfer from itunes store USA to australian store

    HOw can i transfer from itunes store USA to AustraliN store

  • My Environments are miss

    2 Days ago I wanted to use Chapel for a certain tune, Much to my dismay, I hand no enviro's. System Diagnostics wont even open. I tried uninstalling the driver, then reinstalling them, hoping that would work, it didn't I have a Compaq Presario 5wv252

  • HST60: qms$trans_errors.display_messages does not activate error window

    Using qms$trans_errors.display_messages; does not activate the error window. The window is popped but is not activated and no errors are shown. When activating the error window the errors are shown. Help needed.

  • OS 2.1 Bug with CGAffineTransform and Views?

    Anyone get any complaints about shifting images in OS2.1? I use [[rootViewController view] addSubview:[holdemController view]]; CGAffineTransform rotate = CGAffineTransformMakeRotation(1.57079633); rotate = CGAffineTransformTranslate (rotate, 80.0, 8