Java 如何返回搜索后找到的项目数?
请帮助我了解在搜索特定文件夹时如何获得结果计数 另外,我如何询问用户是否要执行另一次搜索Java 如何返回搜索后找到的项目数?,java,Java,请帮助我了解在搜索特定文件夹时如何获得结果计数 另外,我如何询问用户是否要执行另一次搜索 // Importing utilities import java.io.File; import java.util.*; public class FileListing { public static void main (String[] args) { // Creating a Scanner Scanner keyboard = ne
// Importing utilities
import java.io.File;
import java.util.*;
public class FileListing
{
public static void main (String[] args)
{
// Creating a Scanner
Scanner keyboard = new Scanner(System.in);
// Specifying search location
File file = new File("D:/Music");
String[] content = file.list();
// Searching for a match
System.out.println("Enter the first few characters of the folder/file to do a lookup");
String userInput = keyboard.nextLine();
// Adding text to say what the user searched for
System.out.println("Below you will find the list of folders/files with a partial match to (" + userInput + ").");
System.out.println();
// Posting the contents
for(String folders : content)
{
if(folders.toUpperCase().startsWith(userInput.toUpperCase()))
{
System.out.println("Name: " + folders);
}
}
}
}
我将添加一个变量
int count = 0;
就在for循环之前,如果匹配,只需增加它。这应该可以让您开始。每次找到匹配项时,我都会增加变量
count
。我也会一直循环,所以它会不断要求用户输入更多内容
// Importing utilities
import java.io.File;
import java.util.*;
public class FileListing
{
public static void main (String[] args)
{
// Creating a Scanner
Scanner keyboard = new Scanner(System.in);
// Specifying search location
File file = new File("D:/Music");
String[] content = file.list();
while(true){
// Searching for a match
System.out.println("Enter the first few characters of the folder/file to do a lookup");
String userInput = keyboard.nextLine();
// Adding text to say what the user searched for
System.out.println("Below you will find the list of folders/files with a partial match to (" + userInput + ").");
System.out.println();
// Posting the contents
int count=0;
for(String folders : content)
{
if(folders.toUpperCase().startsWith(userInput.toUpperCase()))
{
System.out.println("Name: " + folders);
count++;
}
}
}
}
}
如果要计算匹配项,可以执行以下操作
int i=0;
// Posting the contents
for(String folders : content)
{
if(folders.toUpperCase().startsWith(userInput.toUpperCase()))
{
System.out.println("Name: " + folders);
i++;
}
}
System.out.println("Total number of results: " + i);`
至于询问用户,请考虑使用以下格式的do-while循环
do{
// your code
// ask user and read his answer on a string called userChoice
}while (userChoice.equals('y'))
尝试一下我们的建议,你会很容易找到答案 如果用户想要停止,使用while循环并提示用户输入短语(如“退出”)。阅读用户输入后,检查短语,如果与退出短语匹配,则调用break
按照Robert的建议使用一个变量来计算找到的文件总数。反勾号用于内联代码,如
this
。。。要生成代码块,请将代码缩进4个空格。或者选择它并点击顶部的{}图标。谢谢你,我能够实现我想要的。谢谢你。