使用用户输入访问元素数组

时间:2015-10-14 08:49:55

标签: java arrays

我是Java新手,我试图让用户可以从他们要求的数组中获取哪些元素。

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

因此,如果用户输入了答案0,他将获得0的访问元素30,依此类推。每当用户输入0, 1, 2, 3, 4时,答案将始终指向30。

我认为问题出在我的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 个答案:

答案 0 :(得分:2)

通过检查输入数字是否在aksesArray范围内,您可以大大简化代码。在任何一种情况下,您都可以打印相应的消息。

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 " );
    }
}