gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 08:45:47 26 4
gpt4 key购买 nike

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


}

}

最佳答案

您可以通过检查输入的数字是否在 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 " );
}
}

关于java - 使用用户输入访问元素数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33120715/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com