简体   繁体   中英

iterating through array, android dev

I have a question I have been holding off for about a week, because I thought I can figure it out but I can't!! lol.

Well, I have created an int array just as the following.

int[] a = new int[11];
    a[0] = 15;
    a[1] = 16
    a[2] = 17;
    a[3] = 18;
    a[4] = 19;
    a[5] = 20;
    a[6] = 21;
    a[7] = 22;
    a[8] = 23;
    a[9] = 24;
    a[10] = 25;

what I want is to get user to input a value from 1 thru 10. I want to be able to match their input with the index of the array, then finally return the value. So, if the user inputs 7, then 22 will be returned, or if user input is 4, then 19 is returned.

if user input is int input , you obtain the value with a[input]

Is this the answer to your question? Or do you wonder where to get the input from? In that case, please rephrase your question.

write it as a method for more convenience:

public int checkArray(int val){
    int[] a = new int[11];
    a[0] = 15;
    a[1] = 16;
    a[2] = 17;
    a[3] = 18;
    a[4] = 19;
    a[5] = 20;
    a[6] = 21;
    a[7] = 22;
    a[8] = 23;
    a[9] = 24;
    a[10] = 25;

    return a[val];
}

you can use for loop...

for(int i = 0;i=userinput;i++)
{
    System.out.println(a[i]);
}

This requires no iteration.

You need to create a Scanner and just return a[scanner.nextInt()]; [where scanner is the initialized Scanner ].

Note the above is not safe, it might invoke IndexOutOfBoundException if the user will insert 100 for example.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM