Java,需要帮助创建一个方法来 select 数组中的特定元素
Java, need help creating a method to select a specific element in an array
我创建了几个命令来要求用户将数字添加到数组中。我现在需要能够让用户 select 数组中的特定元素,并在打印时在 selected 元素上放置一个 *。我将程序分成两个 classes:一个 class 用于存储和管理数组,另一个处理用户输入和输出。
例如,这里是 class 中处理 input/output:
的代码
else if (cmd.equals("add"))
{
// add x command
int x = input.nextInt();
list.add(x);
list.print();
}
这里是 class 中处理数组的部分:
public void add(int x)
{
// Expand the list capacity if necessary
if (count >= list.length)
{
// Allocate a new longer list
int[] newList = new int[list.length + 5];
// Copy existing numbers to new list
for (int i = 0; i < list.length; i++)
{
newList[i] = list[i];
}
// Reassign the list to be the new one
list = newList;
}
// Add x to the end of the list
list[count] = x;
count++;
}
这是为向数组添加条目(并在必要时扩大数组)而创建的命令,现在我只需要帮助创建一个命令以允许用户 select 数组中的特定条目和在它前面放一个 *。
提示用户,然后读入所选索引并将其存储在变量中。检查你的打印循环。
Scanner kb = new Scanner(System.in);
System.out.println("Enter the index of an element:");
int selectedElement = kb.nextInt();
然后打印的时候..
for (int i = 0; i < list.length; i++) {
if(i == selectedElement)
// and then print out the * in front of it
}
好吧,您总是可以打印出数组,使用索引来显示您正在显示的值。您也可以将其显示为索引 + 1,这样它对用户更友好(这样,用户就不会想知道为什么编号从 0 开始)。例如(这可能是输出的样子):
1) First value.
2) Second value.
3) Third value.
Please enter the number that you would like to print out, then press enter.
一旦用户输入一个值,你可以从中减去1得到数组的索引,然后适当地打印出来。
希望我正确理解了您的问题,希望对您有所帮助。
我创建了几个命令来要求用户将数字添加到数组中。我现在需要能够让用户 select 数组中的特定元素,并在打印时在 selected 元素上放置一个 *。我将程序分成两个 classes:一个 class 用于存储和管理数组,另一个处理用户输入和输出。
例如,这里是 class 中处理 input/output:
的代码else if (cmd.equals("add"))
{
// add x command
int x = input.nextInt();
list.add(x);
list.print();
}
这里是 class 中处理数组的部分:
public void add(int x)
{
// Expand the list capacity if necessary
if (count >= list.length)
{
// Allocate a new longer list
int[] newList = new int[list.length + 5];
// Copy existing numbers to new list
for (int i = 0; i < list.length; i++)
{
newList[i] = list[i];
}
// Reassign the list to be the new one
list = newList;
}
// Add x to the end of the list
list[count] = x;
count++;
}
这是为向数组添加条目(并在必要时扩大数组)而创建的命令,现在我只需要帮助创建一个命令以允许用户 select 数组中的特定条目和在它前面放一个 *。
提示用户,然后读入所选索引并将其存储在变量中。检查你的打印循环。
Scanner kb = new Scanner(System.in);
System.out.println("Enter the index of an element:");
int selectedElement = kb.nextInt();
然后打印的时候..
for (int i = 0; i < list.length; i++) {
if(i == selectedElement)
// and then print out the * in front of it
}
好吧,您总是可以打印出数组,使用索引来显示您正在显示的值。您也可以将其显示为索引 + 1,这样它对用户更友好(这样,用户就不会想知道为什么编号从 0 开始)。例如(这可能是输出的样子):
1) First value.
2) Second value.
3) Third value.
Please enter the number that you would like to print out, then press enter.
一旦用户输入一个值,你可以从中减去1得到数组的索引,然后适当地打印出来。
希望我正确理解了您的问题,希望对您有所帮助。