Integers problem

Hello, I'm new to object C and I need some help with two things:
1. I'm trying to create a counter in a ibaction method that when its clicked the value of a uilabel
changes...IE 1 2 3 4 5.
2. I'm also trying to pass that value into a global variable so that I can access it in another function.
Here is what I have so far.
-(IBAction)clicking:(id)sender
static int count;
count++
myLabel.text = [NSString stringWithFormat:@"%d\n", count];
The label updates but I cant assign the value of count to a variable. I want the data of count to be stored so that I can add it to anorther integer.
please help, getting real frustrated.

[self otherFunction] is the correct and most common way to call an Obj-C function. But in Obj-C, it's more correct to say we're "passing a message" to self, instead of calling a member function of self. A function that's a member of an Obj-C class is called a "method" and its name is a "selector" that the class responds to.
Of course the software does the same thing no matter what you call it, so don't worry about any of that right now. I was just showing off the new words I learned, since Obj-C is new for me too.
Btw, it's also good to remember what Tod wrote about formatting code in this forum (since we hope you'll come back!). Notice how Tod's code is indented correctly, and appears almost the same as in the Xcode editor? Notice how none of his square brackets are missing? The code you post could look that good too!! All you need to remember is this:
paste your code here
If you're not sure you did that correctly, just click on the Preview tab before you Post your message.
The other night I had a dream that Tod bumped my code formatting thread up in the Feedback forum. It was very real, but turned out to be just a dream.
As to books, a lot depends on whether and how much you've programmed before. If you know a little of the C language, you can start learning Cocoa right away because you'll pick up the Obj-C you need as you go along. If C is new to you, it might be good to get a book on C, then a book on Obj-C. But you can continue to build iPhone projects while you're studying the language. In other words, get the language books you need, but don't feel you have to get to the back cover before you can have fun building projects.
That said, if you want to develop iPhone apps here's the book to get right away: +Beginning iPhone Development:+ Exploring the iPhone SDK by Mark and LaMarche. The projects are so well explained and tuned to what you want to know, you'll think you're an iPhone programmer by the time you're into Chapter 6. Actually, by the time you finish Chapter 9 you'll be able to answer several questions a week in this forum.
Of course the other resource you never want to be far away from is the iPhone Dev Center online library. Read the docs you can understand and don't worry about the rest for now (except in a few months you'll be glad you remembered where some of those docs live). Some of the tutorials are really good, but very few of the docs are intended for beginners (or if they are, the authors forgot what beginners need to know first). So just explore what's there and start bookmarking the pages you understand. Not to worry, because 80% of what you need to know in your first year will be explained in Mark and LaMarche.

Similar Messages

  • Problem in reading integers data

    hi all,
    i'm reading integers from console and storing them in a file and then reading back, but my data is inconsistent.can anybody tell me the reason for this.
    heres my code snippet...
    DataInputStream in = new DataInputStream(System.in);
              DataOutputStream out = new DataOutputStream(new FileOutputStream("intdata.txt"));
              try{
                   int a = in.readInt();
                   out.writeInt(a);
                   out.close();
                   in.close();
              }catch(EOFException eofe){
                   throw new RuntimeException(eofe);
              DataInputStream in2 = new DataInputStream(new FileInputStream("intdata.txt"));
              System.out.println(in2.readInt());
              in2.close();

    The whole problem here is in that last phrase "a readInt() function which should function exactly as i'm expecting." What it actually does do in the posted code is sit there doing nothing, or rather it waits for more input. It's doing exactly what its API documentation says it will do.
    But you say it "should function exactly as i'm expecting." Now unless you pay Sun a very, very big sum of money DataInputStreams are going to go on behaving as documented in the API. That isn't going to change. You had better change what you are expecting.
    If you throw a String like "58" at a DataInputStream readInt() will not produce 58. (And nowhere in the documentation of the class does it suggest it will.) What it will do - and I've tried this - is sit there and do nothing. This was sort of what Ceci was getting at by "Broken As Designed". It's not that DIS is broken, after in2 (see below) works fine. But using it to read keyboard input is a Bad Thing.
    Having changed what we expect, we need to rethink that "apart from parseInt" bit. We need a plan B, and here it is. We are reading a string (a bunch of characters such as people produce when they hammer a keyboard) - so we'll use a Reader. We want an entire line, so we'll make it a BufferedReader and use its readline() method. And we want to obtain an int from that string, which pretty much suggests ... parseInt().
    At any rate, that's my suggestion! Something along the lines of:import java.io.BufferedReader;
    import java.io.DataInputStream;
    import java.io.DataOutputStream;
    import java.io.EOFException;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.InputStreamReader;
    public class Test {
        public static void main(String[] args) throws Exception {
            //DataInputStream in = new DataInputStream(System.in);
            BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
            DataOutputStream out = new DataOutputStream(new FileOutputStream("intdata.txt"));
            try{
                //int a = in.readInt();
                int a = Integer.parseInt(in.readLine());
                     * Add this line to see what int the DataInputStream
                     * is creating based on your "85"
                System.out.println("The number I typed in was " + a);
                out.writeInt(a);
                out.close();
                 //in.close();
            } catch(EOFException eofe) {
                throw new RuntimeException(eofe);
            DataInputStream in2 = new DataInputStream(new FileInputStream("intdata.txt"));
            System.out.println(in2.readInt());
            in2.close();
    }Which results in58
    The number I typed in was 58
    58

  • Counter Problems (Integers)

    Greetings,
    I want to make a script that has three inputs (start,stop,increment) (all of them are integers)
    For example:
    Start: 140
    Stop: 180
    Increment: 2
    The output of the script should be 140,142,144…..180
    My problem:
    The loop continuous until the stop integer (in this example 180) is reached. Only the stop integer (180) exits the loop. How do I edit the VI to get all the integers in between the start en stop as well?
    Any help would be greatly appreciated.
    Thanks in advance,
    Henk
    This application is made in Labview 8.5
    Attachments:
    Testpositioner1maart.vi ‏12 KB
    positioner 1maart.JPG ‏33 KB

    Omar

  • Problem with integeration builder

    Hi,
    I am trying to access SXMB_IFR to connect to integeration builder on browser, SAP screen shows me Starting Browser and it opens up SAPWORK directory and does nothing.
    I have installed Java web start but still nothing is happening....
    Can anyone help me...
    regards
    Rinku
    Message was edited by:
            Rinku Malik

    Hi Rinku,
    U may try the following,
    1. Check if u r using the java version lower than 1.5
    If it is not PI7.o then try to use only java webstart 1.4.2_13 or 1.4.2_12
    2. Make sure u r using IE and not Mozilla
    3. That could also mean that your Java portion of XI is not workign properly. Can you start visual admin tool and check that all the services are running. You might have to manually start those which have not automatically started.
    [Dont forget to mark helpful answers]
    Regards,
    Prateek

  • Reading integers from file problem...

    I managed to read integers from a file but only the ones from the first line. I can't somehow read the remaining lines.
    The format is...
    33 212 3111 12 1
    1
    123
    2 3 4
    I know that the first while loop pretty much does nothing...
    Any help is appreciated :)
    import java.util.*;
    import java.io.*;
    public class TokenTest {
          public static void main(String[] args) throws Exception {
                BufferedReader in = new BufferedReader(new FileReader("numbers.txt"));
                String line = in.readLine();
                StringTokenizer st = new StringTokenizer(line);
                while (in.readLine() != null) {
                      while (st.hasMoreTokens()) {
                            String s = st.nextToken();
                            int j = Integer.parseInt(s);
                            System.out.print(j + " ");
    }

    Ok i kind of done it. For the input...
    0 56 3
    23 6 10 12
    3 2 4
    1
    It returns 23 6 10 12 3 2 4 1. Basically all the numbers except for the first line.
    import java.util.*;
    import java.io.*;
    public class TokenTest {
          public static void main(String[] args) throws Exception {
                BufferedReader in = new BufferedReader(new FileReader("numbers.txt"));
                String line = in.readLine();
                while ((line = in.readLine()) != null) {
                      StringTokenizer st = new StringTokenizer(line);
                      while (st.hasMoreTokens()) {
                            String s = st.nextToken();
                            int j = Integer.parseInt(s);
                            System.out.print(j + " ");
    }

  • Splitting integers - BigIntegers - parsing data problem

    Hi
    I have a function which I have written to split up a BigInteger and put it into a list, the second value in the function call represents the base system being used. However, I have now realised that I could be feeding in integers of any length. The function works fine with small values, but as soon as I make the integer large (BigInteger) i get an out of bounds error - what would be a better approach?
    Typical inputs include 26, (base) 2 or 234752138651249763254 (base) 23472.
    public List split(BigInteger x, BigInteger b)
         BigInteger t;
         List<BigInteger> lst = new ArrayList<BigInteger>();
         while (x.compareTo(BigInteger.ZERO) > 0)
              BigInteger[] qr = x.divideAndRemainder(b);
                   x = qr[0];
                   t = qr[1];               
                   lst.add(t);
              //System.out.println(l.toString());
              return lst;
         }any help would be a boon on this!
    ron

    > Then I get an out of bounds error!
    I doubt that.
    > If I call the split method like this:
    >
    cc.split(234752138651249763254,
    BigInteger.valueOf(10));
    You can't call your method like that. 234752138651249763254 is not a BigInteger.
    Try this:
    import java.math.BigInteger;
    import java.util.List;
    import java.util.ArrayList;
    public class Test {
        public static void main(String[] args) {
            List list = split(new BigInteger("234752138651249763254"), BigInteger.valueOf(10));
            System.out.println(list);
        public static List split(BigInteger x, BigInteger b) {
            BigInteger t;
            List<BigInteger> lst = new ArrayList<BigInteger>();
            while (x.compareTo(BigInteger.ZERO) > 0) {
                BigInteger[] qr = x.divideAndRemainder(b);
                x = qr[0];
                t = qr[1];
                lst.add(t);
            return lst;
    }It works fine.

  • Problem with database integers

    Hi,
    I am implementing an online fantasy football game...my problem is how to create a league table using the scores of each of the users...
    i have a table which has the username and scores in the table...
    for eg.
    username | score
    daz | 20
    eric | 12
    azaad | 18
    rakesh | 25
    i know how to order this table to put it in order of highest score to lowest score, by using ORDER BY in my SQL query...but how do i do it, so that in the league table, the position of the team is also correct...if u understand what i mean, i will be grateful for any help..

    check below between your code.
    my code is below:
    <html>
    <head>
    <basefont face="Arial">
    </head>
    <content = league.jsp>
    <body>
    <center>
    <TABLE border=1>
    <TR><TD valign=top>
    <TABLE cellspacing=5><TR><TD colspan=2><I>League
    Table:</I></TD></TR>
                        <TR>
                        <TD width=40 align=center>Position</TD>
                        <TD width=40 align=center>Manager</TD>
                        <TD width=40 align=center>Points</TD>
                        </TR>
    <BR>     
    <%@ page language="java" import="java.sql.*" %>
    <%
         // load driver
         Class.forName("org.postgresql.Driver");
         // create connection url
         String URL = "jdbc:postgresql://dbhost/ug59sxn";
         // pass database parameters to JDBC driver
    Connection Conn = DriverManager.getConnection(URL,
    "ug59sxn", "hupeswop");
         // query statement
         Statement SQLStatement = Conn.createStatement();
         // generate query
    String Query = "SELECT user, teamscore FROM userteam
    " +
                             "ORDER BY teamscore ";
         // get result
    ResultSet SQLResult =
    SQLStatement.executeQuery(Query);
    int j=0;
         // check for email
         while(SQLResult.next())
    j++;
    String user =
    ring user = SQLResult.getString("user");
    String score =
    ing score = SQLResult.getString("teamscore");
    out.println("<tr><td bgcolor ='lightcoral'>" +**********************************************************
    " + pos + "</td><td bgcolor ='lightcoral'>" +j+"."+ user +***************************************************************
    "</td><td bgcolor ='lightcoral'>" + score +
    "</td></tr>");
         // close connections
         SQLResult.close();
         SQLStatement.close();
         Conn.close();
    %>
    </center>
    </body>
    </html>

  • Problem with Integerating Microsoft Exchange server as Webdav Repository

    Hi all
    We are using MS Outlook 2000.
    I created an HTTP system with the exchange server domain name and the corresponding user id and password required for authentication.
    Then i created the Repository Manager using WebDav Repository template.But when I go to component monitoring it gives error in the server as server not connected.
    How to rectify the error?

    hi,
    Have you set the protocol to SMTP.
    You have to create a system alias for the exchange server. have you done with it?
    See this link
    http://help.sap.com/saphelp_nw04/helpdata/en/1d/3d59fdaa5ebb45967ea107d3fa117a/frameset.htm
    regards,
    Ganesh.N

  • Using integers/characters as bookmarks in rtf document

    first of all, i am self taught (ie i know practically nothing)
    i am trying to write an application which includes a database and produces standard letters with individual clients' details inserted. it is driving me insane.
    i am using rtf files and the code below (part of which i stole off the internet) copies everything just fine
    the code below works ok for a limited number of 'fields' - the integers in the 'switch' apply to characters such as # $ [ and they seem to be the integers the code uses.......(the code inserts my fields as it should)
    and this is where my ignorance kicks in big-time - i have tried everything, putting the character itself into the switch instead of the integer, using Unicode symbols - to expand the range so i can use more 'fields' - but i have to confess i am really out of my depth, i don't really understand Unicode........
    for example, i have tried using 'à' as an example, but no matter whether i use the integer (the default one recovered from the rtf document by this code), the character itself, or the Unicode value........the code just ignores it, does not insert the field i require, instead just re-types the à in the copy document.
    tall order, but is there any simple way for me to have a much wider range of 'bookmarks' so i can insert fields?
    void doLetter(String lettCode, Client client, Defendant defendant)
    FileReader in = null;
    out = null;
    currClient = client;
    currDefendant = defendant;
    lett = lettCode;
    try
    File inputFile = new File("C:\\testBill\\" + lett + ".rtf");
    in = new FileReader(inputFile);
    out = new FileWriter(createPath(lett));
    int c;
    while ((c = in.read()) != -1)
    System.out.print(" " + c);
    if (insertField(c)) continue;
    out.write(c);
    catch (Exception io)
    System.out.println(io.getMessage());
    finally
    try
    in.close();
    out.close();
    catch (Exception ex)
    System.out.println(ex.getMessage());
    private boolean insertField(int d) throws Exception
    int a = d;
    switch(a)
    case 35: doField(currClient.getTitle());
    return true;
    case 36: doField(currClient.getFirstName());
    return true;
    case 91: doField(currClient.getLastName());
    return true;
    case 93: doField(currClient.getFirstAddress());
    return true;
    case 126: doField(currClient.getSecondAddress());
    return true;
    case 95: doField(currClient.getThirdAddress());
    return true;
    case 94: doField(currClient.getFourthAddress());
    return true;
    case 124: doField(currClient.getPostCode());
    return true;
    case 33: doField(currDefendant.getPPI());
    return true;
    case 64: doField(currDefendant.getLastName());
    //System.out.println(currDefendant.getLastName());
    return true;
    return false;
    private void doField(String champ) throws Exception
    String whatever = champ;
    char cbuf[] = whatever.toCharArray();
    out.write(cbuf);
    }

    hi mel
    first of all thanks for taking the trouble to answer my query. i am rather embarrassed on two counts - first for the mistake in my code (i did admit to ignorance after all) and secondly that i seem to have found an answer to my problem - after about 3 months of tearing out what hair i have, perhaps posting here galvanised me, i don't know.
    re your solution, yes i could switch happily between the characters themselves, the integers the rtf document seemed to be using (cp1252 or something like that?) and unicode symbols, but the problem was the code was only recognising certain symbols, such as $ and [, but it steadfastly refused to recognise (and therefore act upon) the accented a character (and every other character which was not a letter or a number), which effectively left me with about 12 fields to play with in my standard letters.
    anyway, this seems to be working!:
    int c;
    while ((c = in.read()) != -1)
    System.out.print(" " + c);
    if (c == '%')
    char cbuf[] = new char[3];//in my rtf document i am using %001, %002 etc
    cbuf[0] = (char)in.read();
    cbuf[1] = (char)in.read();
    cbuf[2] = (char)in.read();
    if (insertField(Integer.parseInt(new String(cbuf)))) continue;
    out.write(c);
    catch (Exception io)
    System.out.println(io.getMessage());
    finally
    try
    in.close();
    out.close();
    catch (Exception ex)
    System.out.println(ex.getMessage());
    private boolean insertField(int d) throws Exception
    int a = d;
    switch(a)
    case 1: doField(currClient.getTitle());//35 - these are integers i was using previously
    return true;
    case 2: doField(currClient.getFirstName());//36
    return true;
    case 3: doField(currClient.getLastName());//91
    return true;
    case 4: doField(currClient.getFirstAddress());//93
    return true;
    etc
    i just have to make sure i have no %s in my standard letters, otherwise i should use some other symbol. i will now worry until i am sure you are not going to point out why this will not work long term, but it seems to have worked so far and has helped expand my armoury of fields..........
    thanks once again for your help
    ant

  • Unable to launch Integeration Builder - Java Web Start - Unexpected Error

    Hi there,
    I am not able to launch the Integeration builder. The ESR has no problem and is working fine though.
    Here is the exception :- com.sap.aii.ibdir.gui.appl.ApplicationImpl
    I have tried below options already :
    1. Cleared the java cache under - javaws -logviewer
    2. Go into administration and inside Directory --> Java Web Start Administration clicked "Restore archives and generate new sign."
    Strange part is some of my colleagues here doesnt have any issue while opening the Integeration Builder. In fact I dont have any such issue in QA and PROD environment. The issue is only in DEV environment. Please advice.
    Anshul

    Hello,
    Usually restoring the archives will help resolve the issue.
    If the issue is occurring for just yourself maybe you could check that you are using the correct java version. e.g. for for 7. 1 java version 5
    Also please refresh the Java Web Start:
    If it's a Windows terminal, select Start - Run - javaws to launch Java Web Start and then clear the cache. File -> preferences ->
    advanced -> clear folder button
    If you have later versions of Java and doing the
    Start -> Run doesn't give you anything, then select Start - Run and type Control and hit Enter. Double-click Java in the list
    that displays to view the more up-to-date Java Control Panel. In the General tab, select Settings from the Temporary Internet Files section. Click Delete Files to clear the cache and then log into the Integration Builder again (download will be longer as jars will be cached locally again).
    If the problem still remains I would advise to check that the latest patches have been applied for XI_TOOL, and also the other components MESSAGING  SAP-XIAFC SAP_XIAF SAP_XIESR SAP_XIGUI
    Regards,
    Sarah

  • Reading strings and integers from a text file

    I want to read the contents of a text file and print them to screen, but am having problems reading integers. The file contains employee's personal info and basically looks like this:
    Warren Laing
    32 //age, data type is int
    M //gender, data type is String
    Sharon Smith
    44
    F
    Here's what I've done so far. The method should continue reading the file until there's no lines left. When I call it from main, I get a numberFormatException error. I'm not sure why because the data types of the set and get methods are correct, the right packages have been imported, and I'm sure I've used Integer.parseInt() correctly (if not, pls let me know). Can anyone suggest why I'm getting errors, or where my code is going wrong?
    many thanks
    Chris
    public void readFile() throws IOException{
    BufferedReader read = new BufferedReader(new FileReader("personal.txt"));
    int age = 0;
    String input = "";
    input = read.readLine();
    while (input != null){
    setName(input);
    age = Integer.parseInt(input);
    setAge(age);
    input = read.readLine();
    setGender(input);
    System.out.println("Name: " + getName() + " Age: " + getAge() + " Gender: " + getGender());
    read.close();

    To answer your question - I'm teaching myself java and I haven't covered enumeration classes yet.
    With the setGender("Q") scenario, the data in the text file has already been validated by other methods before being written to the file. Anyway I worked out my problems were caused by "input = read.readLine()" being in the wrong places. The code below works fine though I've left out the set and get methods for the time being.
    Chris
    public static void readFile()throws IOException{
    String name = "";
    String gender = "";
    int age = 0;
    BufferedReader read = new BufferedReader(new FileReader("myfile.txt"));
    String input = read.readLine();
    while(input != null){
    name = input;
    input = read.readLine();
    gender = input;
    input = read.readLine();
    age = Integer.parseInt(input);
    input = read.readLine();
    System.out.println("Name: " + name + " Gender: " + gender + " Age: " + age);
    read.close();

  • Lots of problems with program

    Guys,
    I really am having a lot of problems with a program. I got the program to compile but it looks absolutely nothing like it is supposed to look. I have a deadline for tomorrow and sent my teacher an email but the chances of him getting back to me by tomorrow night for a weekend is pretty much slim to none. Anyways I am sending my output and if anyone could give me advice or feedback on why it does not look right if it is something small and if its alot of things go ahead and call me dumb.
    here is my code:
    import javax.swing.JOptionPane;
    import java.awt.*;
    import java.awt.event.*;
    public class Checkerboard extends Frame implements ActionListener
         private Panel topPanel;
         private TextArea topDisplay[];
         private Panel bottomPanel;
         private TextField startField = new TextField(10);
         private TextField stopField = new TextField(10);
         private TextField stepField = new TextField(10);
         private Label startLabel = new Label ("Start");
         private Label stopLabel = new Label ("Stop");
         private Label stepLabel = new Label ("Step");
         private Button goButton;
         private Button clearButton;
         private boolean clearText;
         private boolean first;
         private int start;
         private int stop;
         private int step;
         //constructor methods
         public Checkerboard()
              //construct components and initialize beginning values
              topPanel = new Panel();
              topDisplay = new TextArea[16];
              goButton = new Button("Go");
              clearButton = new Button("Clear");
              first = true;
              bottomPanel = new Panel();
              int start = 0;
              int stop = 0;
              int step = 0;
              bottomPanel.add(startField);
              bottomPanel.add(stopField);
              bottomPanel.add(stepField);
              bottomPanel.add(startLabel);
              bottomPanel.add(stopLabel);
              bottomPanel.add(stepLabel);
              bottomPanel.add(goButton);
              goButton.addActionListener(this);
              bottomPanel.add(clearButton);
              clearButton.addActionListener(this);
              clearText = true;
              //set layouts for the Frame and Panels
              setLayout(new BorderLayout());
              topPanel.setLayout(new GridLayout(4, 4, 10, 10));
              bottomPanel.setLayout(new GridLayout(3, 3, 5, 5));
              //construct the Display
              for(int i = 1; i <= 15; i++)
                        topDisplay[i] = new TextArea(null, 3, 5, 3);
              //set color to the panel
              //row 1
              for(int x = 1; x <= 4; x++)
              //set color for
              setBackground(Color.white);
              //row 2
              for(int x = 5; x <= 8; x++)
              //set color for
              setBackground(Color.white);
              //row 3
              for(int x = 9; x <= 12; x++)
              //set color for
              setBackground(Color.white);
              //row 4
              for(int x = 13; x <= 16; x++)
              //set color for
              setBackground(Color.white);
              //add components to frame
              add(topPanel, BorderLayout.NORTH);
              add(bottomPanel, BorderLayout.CENTER);
              //allow the x to close the application
              addWindowListener(new WindowAdapter()
                        public void windowclosing(WindowEvent e)
                                  System.exit(0);
                   } //end window adapter
         public static void main(String args[])
              Checkerboard f = new Checkerboard();
              f.setTitle("Checkerboard Array");
              f.setBounds(50, 100, 300, 400);
              f.setLocationRelativeTo(null);
              f.setVisible(true);
         } //end main
         public void actionPerformed(ActionEvent e)
              //convert data in TextField to int
              int start = Integer.parseInt(startField.getText());
              int stop = Integer.parseInt(stopField.getText());
              int step = Integer.parseInt(stepField.getText());
              for(int i = 1; i <=16; i++)
              setBackground(Color.blue);
              for(int i = start; i <= stop; i++)
              setBackground(Color.yellow);
              //test clear
              String arg = e.getActionCommand();
              //clear button was clicked
              if(arg.equals("Clear"))
                   clearText = true;
                   start = 0;
                   stop = 0;
                   step = 0;
                   first = true;
                   setBackground(Color.white);
                   startField.requestFocus();
              } //end the if clear
         }//end action listener
    }//end classThis will incorporate arrays, for loops, and Frames all in one.
    Create a panel containing an array of 16 TextArea components that change color to correspond with the start, stop, and step values entered by the user. Perform the following tasks to create the Checkerboard Array application shown below. When the user enters the start, stop, and step fields and then clicks the Go button, the results are also shown below.
    1.     Call your application Checkerboard.java
    2.     You will need the following variables� declare them as private:
    a.     16 component TextArea array
    b.     a Panel to hold the array
    c.     3 TextField components with length of 10
    d.     3 int variables to receive the start, stop, and step values
    e.     3 Labels to display the words Start, Stop, and Step
    f.     a Go button
    g.     a Clear button
    h.     a Panel to hold the 3 TextFields, 3 Labels, and the 2 Buttons
    3.     Create a constructor method to:
    a.     construct each of the components declared above and initializes the start, stop, and step variables to zero (when constructing the TextArea components, use the following parameters: null, 3, 5, 3)
    b.     set the Frame layout to BorderLayout
    c.     write a for loop to loop the array and set each of the 16 TextArea components in that array so they cannot be edited. In the same loop, set each of the TextArea components text to be 1 more than the index number. Also in this same loop, set the background of each of the TextArea components to white.
    d.     set the Panel for the TextArea components to GridLayout with 4 rows, 4 columns, and both gaps set to 10
    e.     set the Panel for the TextFields, Labels, and button to GridLayout with 3 rows, 3 columns, and both gaps set to 5
    f.     add the components to their respective Panels
    g.     make the buttons clickable
    h.     place the Panels in the Frame� put one in the NORTH and one in the CENTER
    i.     Enter the addWindowListener() method described in the chapter� this is the method that overrides the click of the X so it terminates the application
    4.     In your actionPerformed() method:
    a.     convert the data in your TextFields to int and store them in the variables declared above
    b.     write a loop that goes through the array setting every background color to blue
    c.     write another loop that�s based on the user inputs. Each time the loop is executed, change the background color to yellow (so� start your loop at the user�s specified starting condition. You�ll stop at the user�s specified stopping value. You�ll change the fields to yellow every time you increment your loop based on the step value. REMEMBER: Your displayed values are 1 off from your index numbers!!)
    5.     Write a main() method that creates an instance of the Checkerboard Frame.
    a.     set the bounds for the frame to 50, 100, 300, 400
    b.     set the title bar caption to Checkerboard Array
    c.     use the setVisible() method to display the application Frame during execution
    6.     After you get all of this complete, include error handling to make sure:
    a.     the values entered in the TextFields are valid integers
    b.     the start value is greater than or equal to 1 and less than or equal to 16
    c.     the stop value is greater than or equal to 1 and less than or equal to 16
    d.     the step value is greater than or equal to 1 and less than or equal to 16
    e.     the start condition is less than the stop condition
    f.     when an error occurs, give an error message in a dialog box that is specific to their error, remove the text from the invalid field, and put the cursor in that field so the user has a chance to re-enter� this can be accomplished by using multiple try/catch statements
    g.     only change the colors if the numbers are valid
    7.     Create a clear button as seen in the example below. This button should:
    a.     clear out all 3 TextFields
    b.     change the background color of all TextArea array elements to white
    c.     put the cursor in the start field
    8.     Document!!
    I know you guys are probably busy with your own stuff but any help and I would certainly appreciate it

    got the yellow boxes to come up but just one box.....so is there something wrong with my yellow set background because I am not seeing any more errors
    //packages to import
    import javax.swing.JOptionPane;
    import java.awt.*;
    import java.awt.event.*;
    public class Checkerboard extends Frame implements ActionListener
         private Panel topPanel;
         private TextArea topDisplay[];
         private Panel bottomPanel;
         private TextField startField = new TextField(10);
         private TextField stopField = new TextField(10);
         private TextField stepField = new TextField(10);
         private Label startLabel = new Label ("Start");
         private Label stopLabel = new Label ("Stop");
         private Label stepLabel = new Label ("Step");
         private Button goButton;
         private Button clearButton;
         private boolean clearText;
         private boolean first;
         private int start;
         private int stop;
         private int step;
         //constructor methods
         public Checkerboard()
              //construct components and initialize beginning values
              topPanel = new Panel();
              topDisplay = new TextArea[16];
              goButton = new Button("Go");
              clearButton = new Button("Clear");
              first = true;
              bottomPanel = new Panel();
              int start = 0;
              int stop = 0;
              int step = 0;
              bottomPanel.add(startField);
              bottomPanel.add(stopField);
              bottomPanel.add(stepField);
              bottomPanel.add(startLabel);
              bottomPanel.add(stopLabel);
              bottomPanel.add(stepLabel);
              bottomPanel.add(goButton);
              goButton.addActionListener(this);
              bottomPanel.add(clearButton);
              clearButton.addActionListener(this);
              clearText = true;
              //set layouts for the Frame and Panels
              setLayout(new BorderLayout());
              topPanel.setLayout(new GridLayout(4, 4, 10, 10));
              bottomPanel.setLayout(new GridLayout(3, 3, 5, 5));
              //construct the Display
              for(int i = 0; i <= 15; i++)
                        topDisplay[i] = new TextArea(null, 3, 5, 3);
                        topDisplay.setText(String.valueOf(i+1));
                        topDisplay[i].setEditable(false);
                        topPanel.add(topDisplay[i]);
              //add components to frame
              add(topPanel, BorderLayout.NORTH);
              add(bottomPanel, BorderLayout.CENTER);
              //allow the x to close the application
              addWindowListener(new WindowAdapter()
                        public void windowClosing(WindowEvent e)
                                  System.exit(0);
                   } //end window adapter
              public static void main(String args[])
                        Checkerboard f = new Checkerboard();
                        f.setTitle("Checkerboard Array");
                        f.setBounds(50, 100, 300, 400);
                        f.setLocationRelativeTo(null);
                        f.setVisible(true);
                   } //end main
                   public void actionPerformed(ActionEvent e)
                        boolean done = false;
                        //test go
                        String arg = e.getActionCommand();
                        //go button was clicked
                        if(arg.equals("Go"))
                   //convert data in TextField to int
                   int start = Integer.parseInt(startField.getText());
                   int stop = Integer.parseInt(stopField.getText());
                   int step = Integer.parseInt(stepField.getText());
                   while(!done)
                        try
                             if((start <= 1) && (start > 16)) throw new NumberFormatException();
                             else done = true;
                        } //end try
                        catch (NumberFormatException f)
                             JOptionPane.showMessageDialog(null, "You must enter start between 1 and 16", "Error", JOptionPane.ERROR_MESSAGE);
                             startField.setText(" ");
                             startField.requestFocus();
                        } //end catch
                        try
                             if ((stop < 1) && (stop > 16)) throw new NumberFormatException();
                             else done = true;
                        } //end try
                        catch (NumberFormatException f)
                             JOptionPane.showMessageDialog(null, "You must enter stop between 1 and 16", "Error", JOptionPane.ERROR_MESSAGE);
                             stopField.setText(" ");
                             stopField.requestFocus();
                        } //end catch
                        try
                             if ((step < 1) && (step > 16)) throw new NumberFormatException();
                             else done = true;
                        } //end try
                        catch (NumberFormatException f)
                             JOptionPane.showMessageDialog(null, "You must enter step between 1 and 16", "Error", JOptionPane.ERROR_MESSAGE);
                             stepField.setText(" ");
                             stepField.requestFocus();
                        } //end catch
                        try
                             if (start > stop) throw new NumberFormatException();
                             else done = true;
                        } //end try
                        catch (NumberFormatException f)
                             JOptionPane.showMessageDialog(null, "Stop cannot be larger than start", "Error", JOptionPane.ERROR_MESSAGE);
                             startField.setText(" ");
                             stopField.setText(" ");
                             stepField.setText(" ");
                             startField.requestFocus();
                        } //end catch
              } //end while
                        for(int i = 0; i <=15; i++)
                        topDisplay[i].setBackground(Color.blue);
                        for(int i = start; i <= stop; step++)
                        topDisplay[i].setBackground(Color.yellow);
                   } //end the if go
                   //clear button was clicked
                   if(arg.equals("Clear"))
                        clearText = true;
                        startField.setText("");
                        stopField.setText("");
                        stepField.setText("");
                        first = true;
                        setBackground(Color.white);
                        startField.requestFocus();
                   } //end the if clear
         }//end action listener
    }//end class

  • Problem with code: reading a string

    Hi,
    I am very new to java so excuse my naivety. i need to write some code which will decode an encrypted message. the message is stored as a string which is a series of integers which. Eg. Nick in this code is 1409030110 where a = 1, b = 2,... and there is a 0 (zero) after every word. at the moment the code only goes as far as seperating the individual characters in the message up and printing them out onscreen.
    Heres the code:
    int index = 0;
    while(index < line.length() - 1) {
    char first = line.charAt(index);
    char second = line.charAt(index + 1);
    if(second == 0) {
    char third = line.charAt(index + 2);
    if(third == 0) {
    System.out.print(first + "" + second);
    index = index + 3;
    else {
    System.out.print(first);
    index = index + 2;
    else {
    System.out.print(first + "" + second);
    index = index + 3;
    Basically its meant to undo the code by reading the first two characters in the string then determining whether the second is equal to 0 (zero). if the second is 0 then it needs to decide whether the third character is 0 (zero) because the code could be displaying 10 or 20. if so the first two characters are recorded to another string and if not only the first is recorded. obviously if the second character is not a zero then the code will automatically record the first 2 characters.
    my problem is that the code doesnt seem to recognise the 0 (zero) values. when i run it thru with the string being the coded version of Nick above (1409030110) the outputted answer is 1490010 when it should be 149311. as far as i can see the code is right but its not working! basically the zeros are begin removed but i need each group of non-zero digits to be removed seperately so i can decode them.
    if anyone has understood any of this could you give me some advice, im at my wits end!
    Thanks, Nick

    Try something like this:
    import java.io.FileInputStream;
    import java.io.InputStream;
    import java.io.IOException;
    import java.util.Properties;
    public class SimpleDecoder
        /** Default mapping file */
        public static final String DEFAULT_MAPPING_FILE = "SimpleDecoder.properties";
        /** Regular expression pattern to match one or more zeroes */
        public static final String SEPARATOR = "0+";
        private Properties decodeMapping = new Properties();
        public static void main(String [] args)
            try
                SimpleDecoder decoder = new SimpleDecoder();
                decoder.setDecodeMapping(new FileInputStream(DEFAULT_MAPPING_FILE));
                for (int i = 0; i < args.length; ++i)
                    System.out.println("Original encoded string: " + args);
    System.out.println("Decoded string : " + decoder.decode(args[i]));
    catch (Exception e)
    e.printStackTrace();
    public void setDecodeMapping(InputStream stream) throws IOException
    this.decodeMapping.load(stream);
    public String decode(final String encodedString)
    StringBuffer value = new StringBuffer();
    String [] tokens = encodedString.split(SEPARATOR);
    for (int i = 0; i < tokens.length; ++i)
    value.append(this.decodeMapping.getProperty(tokens[i]));
    return value.toString();
    I gave your "1409030110" string on the command line and got back "nick". The SimpleDecoder.properties file had 26 lines in it:
    1 = a
    2 = b
    3 = c
    // etc;Not a very tricky encryption scheme, but it's what you asked for. - MOD

  • Assigning value to a two-dimensional byte array - problem or not?

    I am facing a really strange issue.
    I have a 2D byte array of 10 rows and a byte array of some audio bytes:
    byte[][] buf = new byte[10][];
    byte[] a = ~ some bytes read from an audio streamWhen I assign like this:
    for (int i=0; i<10; i++) {
        a = ~read some audio bytes // this method properly returns a byte[]
        buf[i] = a;
    }the assignment is not working!!!
    If I use this:
    for (int i=0; i<10; i++) {
        a = ~read some audio bytes
        for (int j=0; j<a.length; j++) {
            buf[i][j] = a[j];
    }or this:
    for (int i=0; i<10; i++) {
        System.arraycopy(a, 0, buf, 0, a.length);
    }everything works fine, which is really odd!!
    I use this type of value assignment for the first time in byte arrays.
    However, I never had the same problem with integers, where the problem does not appear:int[] a = new int[] {1, 2, 3, 4, 5};
    int[][] b = new int[3][5];
    for (int i=0; i<3; i++) {
    b[i] = a;
    // This works fineAnybody has a clue about what's happening?
    Is it a Java issue or a programmers mistake?                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    Back again! I'm trying to track down the problem.
    Here is most of my actual code to get a better idea.
    private void test() {
         byte[][] buf1 = new byte[11][];
         byte[][] buf2 = new byte[11][];
         AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(audioFile);
         byte[] audioBytes = new byte[100];
         int serialNumber = 0;
         while (audioInputStream.read(audioBytes) != -1) {
              if (serialNumber == 10) {
                   serialNumber = 0; // breakpoint here for debugging
              // Fill buf1 -- working
              for (int i=0; i<audioBytes.length; i++) {
                   buf1[serialNumber] = audioBytes[i];
              // Fill buf2 -- not working
              buf2[serialNumber] = new byte[audioBytes.length];
              buf2[serialNumber] = audioBytes;
              serialNumber++;
    }I debugged the program, using a debug point after taking 10 "groups" of byte arrays (audioBytes) from the audio file.
    The result (as also indicated later by the audio output) is this:
    At the debug point the values of buf1's elements change in every loop, while buf2's remain unchanged, always having the initial value of audioBytes!
    It's really strange and annoying. These are the debugging results for the  [first|http://eevoskos.googlepages.com/loop1.jpg] ,  [second|http://eevoskos.googlepages.com/loop2.jpg]  and  [third|http://eevoskos.googlepages.com/loop3.jpg]  loop.
    I really can't see any mistake in the code.
    Could it be a Netbeans 6.1 bug or something?
    The problem appears both with jdk 5 or 6.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • Problem converting to INT from an XML file

    Hi folks, I hope you can help with this one, as it's been driving me nuts...
    Basically (and I'll try to keep this brief!) my project takes in an extremely basic XML file. I've never really done this before, but I seem to have got most of it working apart from taking in attribute values which I want to use as integers.
    Essentially, each element relates to objects of a basic class I have set up, while each attribute relates to the variables for the object. When the XML file is read, a new object is set up for each element and is stored in a linked list. That was supposed to be the difficult bit, but it turns out it hasn't been...
    The XML file looks a little bit like this (only the elements are shown to save space):
    <Object name="My object" description = "blah" x_axis = "96" y_axis="23" />
    <Object name="Another one" description = "blah, again" x_axis = "83" y_axis="40"/>
    etc. etc. The problem relates to the x_axis and y_axis attributes. While the description and name attributes are assigned correctly, for some reason the x_axis and y_axis attributes are both given values of zero when I convert them from Strings to Ints. After much printing to the console, kicking and screaming, I think I've narrowed the problem down to the following code:
    if (attrib.getName() == "x_axis")
    int myX = Integer.parseInt(attrib.getValue()); // converting a string to an int
    myObject.setSoundX_Axis(myX);
    // And, of course, I do the same sort of thing for the Y axis.Anyone know why I'm getting zero values? Is it something to do with the way I'm converting the string to an int in Java?
    Cheers for any help.

    int myX = Integer.parseInt(attrib.getValue());I don't see anything wrong. Try printing out the value of attrib.getValue() to see if it is what you expect. You may want to try:
    String s = "" + myX;
    if ( s.compareTo(attrib.getValue() != 0 ) {
        System.out.println("Don't compare: myX=" + myX + " getValue=" + attrib.getValue());
    }

Maybe you are looking for