1

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.

4
  • 1
    and your question is...? Commented Feb 23, 2012 at 10:18
  • If the user inputs a number between 1 and 10, Why does your array have 11 elements? Commented Feb 23, 2012 at 10:20
  • well the list is much longer I would like to know how to increment through the array till I find the matching index and return the value. Commented Feb 23, 2012 at 10:21
  • 1
    @ JB Nizet because [0] is also included Commented Feb 23, 2012 at 10:22

4 Answers 4

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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];
}

Comments

1

you can use for loop...

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.