[英]How do I test an array of strings to find if a specific string is in the array?
I have this part of my code so far. 到目前为止,我的代码已经包含了这一部分。 It compiles fine and runs fine. 它可以编译并运行良好。 But If I choose to insert a Rank that isn't in the list it still prints the value that I input. 但是,如果我选择插入不在列表中的等级,它仍然会打印我输入的值。
private String Rank; //string r
private static String[] Ranks = {"Assistant", "Associate", "Full"};
public professor(String n, int a, int s, String r, int nc, int pp)
{
super(n, a, s);
setRank(r);
setNumCo(nc);
setPubPaps(pp);
}
//mutator to set the Rank and check to make sure it is in the string list
public void setRank(String r)
{
boolean check = false;
List valid = Arrays.asList(this.Ranks);
if(valid.contains(r))
check = true;
if(check = true)
this.Rank = r;
else
this.Rank = "Associate";
}
Here's an example of what I'm talking about: 这是我正在谈论的示例:
professor p2 = new professor ("Muench", 50, 222344455, "False", 3, 45);
"False" is definitely not in the list of ranks but it will still print as follows in my print window False professor Muench.... “错误”绝对不在等级列表中,但在我的打印窗口False Professor Muench中仍然打印如下。
writing it like this will work and a lot more readable 这样写就可以了,而且可读性更高
List valid = Arrays.asList(this.Ranks);
if(valid.contains(r))
this.Rank = r;
else
this.Rank = "Associate";
This works because the .contains method returns a boolean value so you basically end up with if(true)
or if(false)
when the value is returned 这是可行的,因为.contains方法返回一个布尔值,因此返回值时基本上以if(true)
或if(false)
结尾
if(valid.contains(r))
check = true;
if(check == true)
this.Rank = r;
else
this.Rank = "Associate";
You can also do it using your array of strings (without converting the array to a list): 您也可以使用字符串数组来执行此操作(无需将数组转换为列表):
public void setRank(String r)
{
for ( final String rank : professor.Ranks ) // Static reference to Ranks class variable.
{
if ( rank.equals( r ) )
{
this.Rank = r;
return;
}
}
this.Rank = "Associate";
}
You also have an odd naming convention: 您还有一个奇怪的命名约定:
professor
is entirely in lower case when it is usual to capitalise (or camel-case) class names. 在通常使用大写(或驼峰大写)的班级名称时,班级professor
完全是小写的。 Rank
is capitolised when the normal convention is to use lower case. 当常规使用小写字母时,属性Rank
被大写。 Using Java 8 使用Java 8
If case sensitive 如果区分大小写
public void setRank(String r){
this.Rank = Stream.of(Ranks).filter(p->p.equals(r)).findAny().orElse("Associate");
}
If not case sensitive 如果不区分大小写
public void setRank(String r){
this.Rank = Stream.of(Ranks).filter(p->p.equalsIgnoreCase(r)).findAny().orElse("Associate");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.