Turn on thread page Beta
    • Thread Starter
    Offline

    0
    ReputationRep:
    Button numButtons[]; //declear variables
    int i;

    numButtons = new Button[10]; // create an array to hold references to the 10 buttons

    for(i=0;i<10;i++){
    numButtons[i] = new Button();
    p1.add(numButtons[i]);
    }
    I can get the code to work fine, the array creates 10 buttons from the awt class and places them on the panel p1; by using both an array and for loop.

    I however want it to automatically label each button from 1-10, I tried this in my for loop:


    for(i=0;i<10;i++){
    numButtons[i] = new Button(i);
    p1.add(numButtons[i]);
    }

    So everytime i++ increments, the button label will be the corresponding label. 0...9 .

    It did not work...I cant do this:

    numButtons[i] = new Button("i");

    because it is then a string - and won't increment.

    How can I get the button labels to go from 0-9 thanks.
    Offline

    1
    ReputationRep:
    I don't know what your Button class is and it's been a year since I did any Java, but is that how a name is normally passed into the object? Does its constructor specify an int as its "name"?
    • Thread Starter
    Offline

    0
    ReputationRep:
    (Original post by guitarromantic)
    I don't know what your Button class is and it's been a year since I did any Java, but is that how a name is normally passed into the object? Does its constructor specify an int as its "name"?
    Its an object from the class java.awt.

    I used import java.awt.*; to import the object into my class.

    the method - button(); will not take any values except for strings. So it is a bit tricky.
    Offline

    1
    ReputationRep:
    Ah, I haven't used it so I didn't know.

    The Java API says:

    Constructor Summary
    Button()
    Constructs a button with an empty string for its label.
    Button(String label)
    Constructs a button with the specified label.

    So it looks like you do need to enclose it within "s so it's a string.
    • Thread Starter
    Offline

    0
    ReputationRep:
    (Original post by guitarromantic)
    Ah, I haven't used it so I didn't know.

    The Java API says:

    Constructor Summary
    Button()
    Constructs a button with an empty string for its label.
    Button(String label)
    Constructs a button with the specified label.

    So it looks like you do need to enclose it within "s so it's a string.
    Yep That is the problem though, because when it loops it will just print out the same string label for each button - I want newButton[i] to create an array of 10 objects, place it on the Jpanel p1 (which it does), but with each button label being unique going from 0...9
    Offline

    1
    ReputationRep:
    Ohhh I get what you mean. Hmm, couldn't you make a string within the loop using the value of i, and then use that string variable as the name of the Button?
    • Thread Starter
    Offline

    0
    ReputationRep:
    (Original post by guitarromantic)
    Ohhh I get what you mean. Hmm, couldn't you make a string within the loop using the value of i, and then use that string variable as the name of the Button?
    like that?


    //create a For Loop to create buttons
    int i;

    numButtons = new Button[10]; // create an array to hold references to the 10 buttons

    for(i=0;i<10;i++){
    String test;
    test = i;

    numButtons[i] = new Button(test);
    //numButtons.setText(i);
    p1.add(numButtons[i]);
    }

    I got the following error:

    Exception in thread "main" java.lang.Error: Unresolved compilation problem:
    Type mismatch: cannot convert from int to String

    at Calculator.<init>(Calculator.jav a:118)
    at Calculator.main(Calculator.java: 140)
    Offline

    1
    ReputationRep:
    You have to parse it, you can't just make an int a string in Java. Do:

    String test = String.valueOf(i);

    or

    String test = Integer.toString(i);
    • Thread Starter
    Offline

    0
    ReputationRep:
    http://stuff.mit.edu/people/ele/Javaconversion.htm

    Got it. This works:

    for(i=0;i<10;i++){
    String test;
    test = ""+i;

    numButtons[i] = new Button(test);
    //numButtons.setText(i);
    p1.add(numButtons[i]);
    }



    Is there another way to do it?
    • Thread Starter
    Offline

    0
    ReputationRep:
    (Original post by guitarromantic)
    You have to parse it, you can't just make an int a string in Java. Do:

    String test = String.valueOf(i);

    or

    String test = Integer.toString(i);
    Ahh I see.

    Which method is better? The one I did or parsing it?
    Offline

    1
    ReputationRep:
    I guess mine's more elegant really since those methods are intended for conversion, whereas yours is just slapping an int on the end of an empty string. It all works, but for someone reading your code, something like toString(i) is probably more readable than what you're doing.
    • Thread Starter
    Offline

    0
    ReputationRep:
    (Original post by guitarromantic)
    I guess mine's more elegant really since those methods are intended for conversion, whereas yours is just slapping an int on the end of an empty string. It all works, but for someone reading your code, something like toString(i) is probably more readable than what you're doing.
    I see, thanks dude for your help at this time.

    Hate it when the problems are this simple - but take hours to solve
    Offline

    0
    ReputationRep:
    First, try not to use AWT, use Swing instead (javax.swing). It's built on top of AWT and extends a lot of it's functionality, but is a lot better. All the major AWT stuff has been replaced, like JButton instead of Button, JPanel instead of Panel, JTable instead of Table. If there is a J version of your AWT class, use it instead. But bear in mind that Swing is built on top of AWT and not a complete replacement. Most of the stuff to do with event handlers, layout managers and graphics that you might be using with Swing components is still in AWT. It's mainly the AWT GUI components or 'widgets' that have been replaced in Swing.

    Second, the way I'd turn it into a String is to 'concatenate' the i with a String. Simply: "" + i will do it. What that does is create a new String that starts with the first String (which just happens to be empty, the "") and ends with the String version of the int. Doesn't work the other way round (i + ""), as then you are trying to add a String to an int, which means Java will try addition and not string concatenation.

    Alternatively (just to show yet another way) 'new Integer(i).toString()' will also do the job. It wraps the i object into it's appropriate wrapper class (as int is a 'primitive data type' not an Object, Integer is an Object, see AutoBoxing). It then runs it's 'toString()' method which all Objects have, and Integer overrides it to return the String version of the int it's holding. Hope that all helps.
    Offline

    0
    ReputationRep:
    Oh, and one suggestion about the for/loop. Instead of 'for (int i = 0; i < 10; i++)' do 'for (int i = 0; i < numButtons.length; i++)'

    Notice there are no brackets on the 'length', that's cos it's not a method. But as you are adding a button for each place in numButtons, you ought to tie the size of numButtons into the for loop. This also meant if you changed the 'new Button[10]' to 'new Button[20]' the for loop won't need changing too. In yours, it would. It also makes more sense to anyone else who reads it, and for you when you forget your code and want to come back to it.
    Offline

    14
    ReputationRep:
    (Original post by DiablosDevil)
    Second, the way I'd turn it into a String is to 'concatenate' the i with a String. Simply: "" + i will do it.
    Baaaaaad boy. The fact that Java is nice to you and lets you use ints in the middle of string concatenation, automatically handling the type conversion, is handy. But this is just blatant abuse of it. First it's inefficient (instantiate one empty String object, then one that represents i, then another one that's the concatenation of the two), and second it's just plain wrong. Many coders reading that will spend thirty seconds going "wtf is going on here?". Make the code reflect what you're actually trying to do - converting an int to a string, suggesting the words "toString" really should feature in there.

    Alternatively (just to show yet another way) 'new Integer(i).toString()' will also do the job. It wraps the i object into it's appropriate wrapper class (as int is a 'primitive data type' not an Object, Integer is an Object, see AutoBoxing). It then runs it's 'toString()' method which all Objects have, and Integer overrides it to return the String version of the int it's holding.
    No need for the "new Integer" there. The Integer class has both a member toString() method and a static toString(int i) method. It's inefficient to instantiate an Integer just to call the member method, when you can just call Integer.toString(myInt).
    Offline

    0
    ReputationRep:
    (Original post by ThePants999)
    But this is just blatant abuse of it. First it's inefficient (instantiate one empty String object, then one that represents i, then another one that's the concatenation of the two), and second it's just plain wrong. Many coders reading that will spend thirty seconds going "wtf is going on here?". Make the code reflect what you're actually trying to do - converting an int to a string, suggesting the words "toString" really should feature in there.
    You can concatenate a String with an integer. That does work, so my suggestion is not wrong.

    Very few programmers would be mislead or wouldn't understand instinctively the result of "" + i. But to try to get 'toString' into there somewhere is a fair point and a good suggestion. Dojo also obviously doesn't know of String concatenation, or he would have tried it. Regardless of if you should or shouldn't ever use it (as you should use a StringBuilder in other occasions when you'd want to concatenation multiple strings), he should know about it.

    It's a perfectly valid suggestion, not wrong, and not an abuse of any features of Java.

    As for efficiency, yes of course fast code is always better then slow code. I agree, Integer.toString(i) is the best way to achieve what he's after (I didn't bother checking the Integer class API before) and it probably is the fastest suggestion. However "" + i is not in the slightest bit slow.

    So I find this a little pedantic. Especially when a programmers time and energy could be spent elsewhere on more important aspects, then on a single line which will probably only take up a small decimal of a percent of the performance of any real application. I have seen ALOT of novice programmers care too much about making their code efficient. Even to the extent of writing as few different methods as possible, as calling methods adds overhead. Which although is true, the idea is just plain silly.
    Offline

    1
    ReputationRep:
    When he said "just plain wrong", I don't think he meant it wasn't valid code to do this task, but more that it's not the best solution for this task. Your method is kinda like sellotaping a door shut instead of locking it. It'll work, yeah, but it's not as clear what you're doing it for, at-a-glance people might get the wrong idea, and it could lead to some sticky situations (sorry, I love analagies and puns way too much).

    Don't you see how the toString() method is just, well, better? It's not really about speed or code economy, it's just about writing easily-readable stuff (ever worked on a project where other people will be looking at your code?) that you won't have to spend a few seconds thinking about when you edit it 6 months down the line. These methods exist partly to allow you to give a logical name to generic operations: it's in our interest as programmers to use them.
    Offline

    0
    ReputationRep:
    (Original post by guitarromantic)
    Don't you see how the toString() method is just, well, better?
    I don't mean to be anal, but you haven't properly read my post.

    (Original post by DiablosDevil)
    to try to get 'toString' into there somewhere is a fair point and a good suggestion.
    (Original post by DiablosDevil)
    I agree, Integer.toString(i) is the best way to achieve what he's after...and it probably is the fastest suggestion.
    (Original post by guitarromantic)
    It's not really about speed or code economy, it's just about writing easily-readable stuff
    I completely agree. That was more my point (even though it may not be too clear). He went on about speed and inefficient code when this example will have almost no effect on the performance of an application.

    Finally the answer to your question is yes. I'm still very new to programming, but I have worked on multiple small projects other people in my own time. I am also employed part-time programming for one of my lecturers with the Greenfoot team. Although any code I produce is usually made completely by myself, it is looked at by other people.
    Offline

    14
    ReputationRep:
    Thanks guitarromantic - you have the right idea about my post, though I'll reply anyway.

    Diablos: methinks you take my post too personally. Do you never get peer review of code you write?

    (Original post by DiablosDevil)
    You can concatenate a String with an integer. That does work, so my suggestion is not wrong.
    Of course you can. I never said it was "wrong" in the sense of not working - only in the sense of not being the right way to do it.

    Regardless of if you should or shouldn't ever use it . . . he should know about it.
    Yes, you're right. After all, some people do it, so it's good to know what's going on so you can understand other people's code.

    It's a perfectly valid suggestion, not wrong, and not an abuse of any features of Java.
    I disagree here. It is a valid suggestion in that it works, but being less efficient and less maintainable without saving any time, I don't believe it's the "right" suggestion. As for "abuse" - it's a stronger word than I really wanted, but the idea I'm trying to convey is that it's using a feature for something it wasn't intended to do, even though it achieves it.

    So I find this a little pedantic. Especially when a programmers time and energy could be spent elsewhere on more important aspects, then on a single line which will probably only take up a small decimal of a percent of the performance of any real application.
    <shrug> Performance wasn't my main point. For 99% of applications it's utterly irrelevant. I care far more about the maintainability of code, as per guitarromantic's post.

    But just to dwell on this minor point a moment longer, that's not to say the performance is entirely irrelevant. (I just did some quick performance testing and Integer.toString(i) is 2-4 times as fast as "" + i.) Obviously stuff like this can be taken too far, and the extent to which we're arguing about it is indeed taking it too far. I mentor someone at work, and I clearly wouldn't want to spend ages debating a line of code with them like this. But how many times in a programmer's life will they do integer to string conversion? All I have to do is tell them the right way once, and from then on they'll be doing it right every time without thinking about it. You never know when you'll work on an application that does it so much as for it to be critical.
    Offline

    14
    ReputationRep:
    Quick addendum: by raising the issue of performance here where it doesn't matter, I hope to have made some people think "oohh, I didn't realise things like that had a performance impact" - and then they might stop to think about performance in scenarios where it does matter. Got to be worthwhile.
 
 
 
Poll
Black Friday: Yay or Nay?
Useful resources

The Student Room, Get Revising and Marked by Teachers are trading names of The Student Room Group Ltd.

Register Number: 04666380 (England and Wales), VAT No. 806 8067 22 Registered Office: International House, Queens Road, Brighton, BN1 3XE

Write a reply...
Reply
Hide
Reputation gems: You get these gems as you gain rep from other members for making good contributions and giving helpful advice.