2

i'm new in Java and i am trying to make user can get what element from arrays they're asking for.

int[] aksesArray = {30, 50, 10, 90, 70}; 

So if the user inputs an answer 0, he will get access element 0 which is 30, and so on. And whenever the user inputs 0, 1, 2, 3, 4 the answer will always refer to 30.

i think the problem is on my a = aksesArray.length;

import javax.swing.JOptionPane; 

public class pickingArray {


public static void main(String[] args) {

int[] aksesArray = {30, 50, 10, 90, 70};

int inputElm = Integer.parseInt(JOptionPane.showInputDialog("Input Number to find an Element "));
int a = (inputElm);

a = aksesArray.length;


    if ( a == aksesArray.length ) {
        JOptionPane.showMessageDialog(null, "Element you are looking for : " + aksesArray[0] );
    }
    else if ( a == aksesArray[1] ) {
        JOptionPane.showMessageDialog(null, "Element you are looking for : " + aksesArray[1] );
    }
    else if ( a == aksesArray.length ) { 
        JOptionPane.showMessageDialog(null, "Element you are looking for : " + aksesArray[2] );
    }
    else if ( a == aksesArray.length ) { 
        JOptionPane.showMessageDialog(null, "Element you are looking for : " + aksesArray[3] );
    }
    else if ( a == aksesArray.length ) { 
        JOptionPane.showMessageDialog(null, "Element you are looking for : " + aksesArray[4] );
    }
    else {
        JOptionPane.showMessageDialog(null, "No Element " );
    }


    }

}
1
  • int a=aksesArray[inputElm]; Commented Oct 14, 2015 at 8:51

1 Answer 1

2

You can greatly simplify your code by checking if the input number is within the range of the aksesArray. In either case, you can print an appropriate message.

public static void main(String[] args) {
    int[] aksesArray = {30, 50, 10, 90, 70};

    int inputElm = Integer.parseInt(JOptionPane.showInputDialog("Input Number to find an Element "));

    if (inputElm >= 0 && inputElm < aksesArray.length) {
        JOptionPane.showMessageDialog(null, "Element you are looking for : " + aksesArray[inputElm] );
    }
    else {
        JOptionPane.showMessageDialog(null, "No Element " );
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

Yes it does simplify the previous codes, thank you for your help.
how do i mark solved to my question that has been solved ? i'm new on here
No you can mark my answer. Click the gray checkmark box and it will turn green. You get 5 points for doing that I think.

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.