This site requires JavaScript, please enable it in your browser!
Greenfoot back
maboidanpost
maboidanpost wrote ...

2018/4/15

help with array

maboidanpost maboidanpost

2018/4/15

#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public char[] digits = {};
public Score(){
 
}
public void act()
{
    test();
}   
public void test(){
    String numberString = Integer.toString(Fighter.score);
    for(int i = 0; i < numberString.length(); i++){
        //char c = numberString.charAt(i);
        digits[i] = numberString.charAt(i);
    }
}
This crashes greenfoot, why? I'm trying to get an int from another class then convert each digit into a char. Then add that char/digit to an array.
danpost danpost

2018/4/15

#
You gave your array a length of zero. (line 1). You cannot change the length of any given array. You can have a new array assigned to numberString of a length that is more appropriate for what you want to save in it, but there is an even easier way to do what you want. The String class has a toCharArray method you can make use of:
1
2
3
4
5
6
7
8
// change line 1 to
public char[] digits;
 
// and test method to
public void test()
{
    digits = (""+Fighter.score).toCharArray();
}
maboidanpost maboidanpost

2018/4/15

#
Thank You! How could I "make a number" using this array. Since I don't know how to upload a new font. I made pictures for each digit 1,2,3,4,5,6,7,8,9,0 For every digit make object and setImage(digit); In order of course The files name for the image files are just "1.png" and so on...
danpost danpost

2018/4/15

#
maboidanpost wrote...
How could I "make a number" using this array. ...
You do not need an array of type char. What you need is an array of type GreenfootImage for the images representing the digits of the number. That way you can calculate the length of the final image, create the final image and draw the digits onto it:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
Sting numberString = ""+Fighter.score;
int digitCount = numberString.length();
GreenfootImage[] digitImages = new GreenfootImage[digitCount];
int textImageWidth = 0;
for (int i=0; i<digitCount; i++)
{
    digitImages[i] = new GreenfootImage(""+numberString.charAt(i)+".png");
    textImageWidth += digitImages[i].getWidth();
}
GreenfootImage textImage = new GreenfootImage(textImageWidth, digitImages[0].getHeight());
int drawPosition = 0;
for (int i=0; i<digitImages.length; i++)
{
    textImage.drawImage(digitImages[i], drawPosition, 0);
    drawPosition += digitImages[i].getWidth();
}
setImage(textImage);
You need to login to post a reply.