gpt4 book ai didi

java - 数组值输出多个

转载 作者:行者123 更新时间:2023-12-02 12:55:00 26 4
gpt4 key购买 nike

这是我想出的代码。但是,我希望能够输出:

  • (值)位于槽 x 中。
  • (值)位于槽 x 中。

如果(值)在两个槽中可用(例如 7),则有两个输出。

  • (num) 不在数组中。

但不能两者兼而有之。有人可以帮忙吗?

    public static void main(String[] args) {
int search, counter;
int num[]={3, 4, 5, 6, 7, 8, 10, 7, 9, 13};

System.out.print("Array: ");
for (int count=0; count<num.length; count++)
System.out.print(+num[count] + " ");

Scanner in = new Scanner (System.in);
System.out.print("\nValue to find: ");
search = in.nextInt();

for (counter = 0; counter < num.length; counter++ ){
if (num[counter] == search)
{
System.out.println(search + " is in slot " + (counter + 1) + ".");
}
}
if (counter == num.length)
{
System.out.println(search + " is not in the array.");
}
}
}

最佳答案

虽然我觉得你应该在另一个社区上问这样的问题,例如 https://codereview.stackexchange.com/我可以提供一个建议:

使用 boolean 标志来检查您之前是否找到过它。像这样的事情:

public static void main(String[] args) {
int search;
boolean found = false;
int num[]={3, 4, 5, 6, 7, 8, 10, 7, 9, 13};

System.out.print("Array: ");
for (int count=0; count<num.length; count++)
System.out.print(+num[count] + " ");

Scanner in = new Scanner (System.in);
System.out.print("\nValue to find: ");
search = in.nextInt();

for (int counter = 0; counter < num.length; counter++ ) {
if (num[counter] == search)
{
System.out.println(search + " is in slot " + (counter + 1) + ".");
found = true;
}
}

if (!found) {
System.out.println(search + " is not in the array.");
}

in.close();

}

因此,只有在线性遍历数组后找不到元素时,才会打印“未找到”消息...

关于java - 数组值输出多个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44470275/

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