我有这个代码,找到女性艺术家,男性艺术家或乐队的数量 -
import java.util.*;
public class FindGender {
public static void main(String[] args) {
// TODO code application logic here
ArrayList < String > artists = new ArrayList < > ();
int mnum = 0, fnum = 0, bnum = 0;
artists.add("Beyonce (f)");
artists.add("Drake (m)");
artists.add("Madonna (f)");
artists.add("Michael Jackson (m)");
artists.add("Porcupine Tree (b)");
artists.add("Opeth (b)");
artists.add("FallOut Boy (b)");
artists.add("Rick Ross {m}");
artists.add("Chris Brown (m)");
if (artists.contains("(b)")) bnum++;
if (artists.contains("(m)")) mnum++;
if (artists.contains("(f)")) fnum++;
System.out.println("The number of male artists is: " + mnum);
System.out.println("The number of female artists is: " + fnum);
System.out.println("The number of bands is: " + bnum);
}
}
Run Code Online (Sandbox Code Playgroud)
但输出显示 - 运行:
The number of male artists is: 0
The number of female artists is: 0
The number of bands is: 0
BUILD SUCCESSFUL (total time: 0 seconds)
Run Code Online (Sandbox Code Playgroud)
任何帮助,将不胜感激
list#contains()比较列表中的整个字符串而不是字符串的一部分,你可以这样做
if(artists.stream().anyMatch(e -> e.contains("(b)"))) // java 8 solution
Run Code Online (Sandbox Code Playgroud)
即迭代列表并检查列表元素的包含情况。
包含和包含String的一部分是不同的.为了返回true,它应该匹配整个String.
这有效
for (String item : artists) {
if (item.contains("(b)")) bnum++;
if (item.contains("(m)")) mnum++;
if (item.contains("(f)")) fnum++;
}
Run Code Online (Sandbox Code Playgroud)
你可以使用类似的东西if(string.indexOf("(f)")!=-1) fnum++。这在您的代码中看起来像这样。
public static void main(String[] args)
{
// TODO code application logic here
ArrayList<String> artists = new ArrayList<>();
int mnum = 0, fnum = 0, bnum = 0;
artists.add("Beyonce (f)");
artists.add("Drake (m)");
artists.add("Madonna (f)");
artists.add("Michael Jackson (m)");
artists.add("Porcupine Tree (b)");
artists.add("Opeth (b)");
artists.add("FallOut Boy (b)");
artists.add("Rick Ross (m)");
artists.add("Chris Brown (m)");
for(String s:artists)
{
if(s.indexOf("(b)")!=-1) bnum++;
if(s.indexOf("(m)")!=-1) mnum++;
if(s.indexOf("(f)")!=-1) fnum++;
}
System.out.println("The number of male artists is: " + mnum);
System.out.println("The number of female artists is: " + fnum);
System.out.println("The number of bands is: " + bnum);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2019 次 |
| 最近记录: |