vendredi 28 avril 2017

Java homework: Print Arrays with stored random numbers in it

I need some help for a class assignment. I dont want to be given the solution but rather to understand how i can solve this because i really dont get it even if it's simple.

I need to write a program that will have an Array with 10 elements(all of them integers). A random generated number will be set to each element and each number will be from 0-20. Next, i must print the position of the element of the array , the random number and as many asterisks as the value of the array.

It will look like this:

Array Value Asterisks
0     5     *****
1     15    ***************

I can generate the numbers and set store them to the Array but i cant print them according to the description. Could you please tell me what am i doing wrong?.

public class ForTest{
    public static void main(String[] args) {
        //Method 1
        int[] myNumbers = {0,1,2,3,4,5,6,7,8,9};
        //Method 2
        int[] randomNumbers = new int[10];
        String asterisk = "";

        for( int index=0; index < randomNumbers.length; index++)
        {
            randomNumbers[index] = 1 + (int) ( Math.random() *20);
        } // end for

        for ( int index=0; index < randomNumbers.length; index++)
        {
            switch (randomNumbers[index]) {
                case 1:
                asterisk = "*";
                System.out.println(myNumbers[0] + "\t-->\t" + randomNumbers + asterisk);
                break;
                case 2:
                asterisk = "**";
                System.out.println(myNumbers[1] + "\t-->\t" + randomNumbers + asterisk);
                break;
                case 3:
                asterisk = "**";
                System.out.println(myNumbers[2] + "\t-->\t" + randomNumbers + asterisk);
                break;
                case 4:
                asterisk = "**";
                System.out.println(myNumbers[3] + "\t-->\t" + randomNumbers + asterisk);
                break;
            }
        }
    }
}




Aucun commentaire:

Enregistrer un commentaire