所以这不仅仅是检查用户是否在数组中输入字符串,因为如果字符串实际上在数组中并且bool返回true,我希望它写一些自定义文本。
{
static void Main(string[] args)
{
string[] name= {"Bob","Bob2","Bob3","Bob4"};
bool exists = name.Contains(string userName= Console.ReadLine());
if (exists == true)
Console.WriteLine("Hi " + userName);
Console.ReadLine();
}
}
我知道我不能像这样运行代码,但是我正在寻找类似的方式来运行它但是我不确定如何存储用户输入并仍然检查bool用户输入的字符串在字符串数组中。
答案 0 :(得分:3)
你几乎拥有它,只需将userName
作业移到自己的行:
static void Main(string[] args)
{
string[] name = { "Bob", "Bob2", "Bob3", "Bob4" };
string userName = Console.ReadLine();
bool exists = name.Contains(userName);
if (exists == true)
Console.WriteLine("Hi " + userName);
Console.ReadLine();
}
这是输出:
答案 1 :(得分:0)
只需在te Contains
之外声明输入变量:
static void Main(string[] args)
{
string[] name= {"Bob","Bob2","Bob3","Bob4"};
string userName = Console.ReadLine();
bool exists = name.Contains(userName);
if (exists == true)
Console.WriteLine("Hi " + userName);
Console.ReadLine();
}
答案 2 :(得分:0)
我想出了这个......
import java.util.Scanner;
public class inp {
public static void main (String args[]) {
String[] name = new String[] {
"Ben",
"Sam"
};
int max = name.length;
int current = 0;
boolean is = false;
System.out.println("What name tho?");
Scanner inp = new Scanner(System.in);
String nameInq = inp.next();
while(is == false && current<max) {
if(name[current].equals(nameInq)) {
is = true;
}else {
current++;
}
}
if(is) {
System.out.println("They are in the list");
}else {
System.out.println("nah");
}
}
}
不是那么高效但完成工作。