gpt4 book ai didi

java - 如何查看数组

转载 作者:行者123 更新时间:2023-12-02 01:09:43 24 4
gpt4 key购买 nike

我在下面附加了代码,用于在数组中搜索特定字符串,但此代码不起作用。为什么? if(children[x].equals(music)) 确实有效,但前提是您输入完整的文件名(存储在 music 变量中),我怎样才能做到这一点,以便如果 music 的值'h' 子数组中包含字符 'h' 的任何元素都会作为输出打印吗?

public class main {

public static void main(String[] args) throws IOException {
//text file, should be opening in default text editor


//Look through directory
File dir = new File("/Users/Runa.c/Music/music");
String[] children = dir.list();

if (children == null) {
System.out.println("does not exist or is not a directory");
} else {
for (int i = 0; i < children.length; i++) {
String filename = children[i];
System.out.println(filename);
}
}

//search
Scanner search = new Scanner(System.in);
System.out.print("Search for a song: ");
String music = search.next();


for (int x=0; x<children.length; x++){
if(children[x].equals(music)){
System.out.println(children[x]);
}
}



//Open file
File file = new File("/Users/Runa.C/Music/music/youtubnow.co - Distrion & Alex Skrindo - Lightning [NCS Release].mp3");

Desktop desktop = Desktop.getDesktop();
if(file.exists()) desktop.open(file);

file = new File("/Users/Runa.C/Music/music/youtubnow.co - Distrion & Alex Skrindo - Lightning [NCS Release].mp3");
if(file.exists()) desktop.open(file);
search.close();
}
}



最佳答案

而不是:

if (children[x].equals(音乐))

您可以使用:

if (children[x].contains(music))

根据:https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#contains(java.lang.CharSequence)

Returns true if and only if this string contains the specified sequence of char values.

关于java - 如何查看数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59568998/

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