gpt4 book ai didi

java - 使用 for 循环在数组中搜索名称

转载 作者:行者123 更新时间:2023-12-01 22:12:28 25 4
gpt4 key购买 nike

我需要帮助设计一个 for 循环,如果找到,则返回名称,如果未找到,则返回未找到的请求名称。我需要在不多次重复未找到循环的情况下执行此操作。

我尝试了各种 if、else if 和 else 语句。我还尝试在 for 循环内执行 do while 循环,并尝试在循环外执行 not find 语句

    String[] values = new String[12];
int name = 1;

// Initialize Scanner
java.util.Scanner input = new java.util.Scanner(System.in);

// Create loop for name input
for (int i = 0; i < values.length; i++)
{
System.out.print("Enter in " + " the name of friend " + name++ + ": ");
values[i] = new String(input.next());
if (values[i].equalsIgnoreCase("zzzz"))
{
break;
}
}

// Create loop for name output
System.out.println("\n" + "The names of your friends are: ");
for (int i = 0; i < values.length; i++)
{
if (values[i].equalsIgnoreCase("zzzz"))
{
break;

}
else
{
System.out.println(values[i]);
}
}

// Search for the name
boolean found = false;
System.out.print("\n" + "Enter in the name of the friend you would like to find: ");
String find = input.next();
for(int i = 0;i < values.length && !found;++i)
{
if (find.equalsIgnoreCase(values[i]))
{
System.out.println("\n" + "Your friend " + find + " was found");
found = true;
break;
}
else if (find != values[i] && (found = false))
{
System.out.println("\n" + "Your friend " + find + " was not found" );
break;
}
}

}
}

我希望在找到实际名称之前,不会在循环中多次重复未找到的语句。如果数组中不存在该名称,则应搜索整个数组并返回未找到该名称。

最佳答案

看看我的尝试。我已将所有元素转换为小写,同时迭代数组以确保我们不会错过匹配项。例如,如果我们搜索“tom”,并且在数组中我们有“Tom”,那么匹配将被错过。

import java.util.Scanner;


public class Main {


static Scanner input = new Scanner(System.in);

public static void main(String[] args) {

boolean foundFlag = false;
String[] values = new String[12];

//Populate array
for(int i = 0, x = 1; i < values.length; i ++, x ++)
{
System.out.print("Enter name of friend " + x + ": " );
String name = input.next();
values[i] = name;
}

//Output all elements of the array
System.out.println("\n" + "The names of your friends are: ");
for(String x : values)
{
System.out.println(x);
}

//Find a friend
System.out.print("\n" + "Enter in the name of the friend you would like to find: ");
String find = input.next();


//Iterate through array and check if Friend inside.
for(int i = 0; i < values.length; i ++)
{
if(values[i].toLowerCase().equals(find.toLowerCase()))
{
foundFlag = true;
break;
}

}

//If friend in the array flag will be True, else flag will remain false.
if (foundFlag)
{
System.out.println("Friend " + find + " found");
}
else
{
System.out.println("Friend " + find + " not found");
}

}
}

关于java - 使用 for 循环在数组中搜索名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58648611/

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