我创建了一个建筑目录,它基本上向用户显示整个目录(使用字符串数组),如果他们不想查看整个目录,他们只需搜索建筑物中的特定业务。但是,我似乎无法使搜索选项工作,因为在我的数组中间有空格...例如:
String Floor [] = {" Ground Floor"," Vacant" };
如果我删除其间的空间"底层"并使它成为#34; GroundFloor"然后可以搜索它,否则只是在搜索"底层"时才会出现。我该怎么做才能解决这个问题?
程序的骨头:
import java.util.Arrays;
import java.util.Scanner;
public class Townsendtest {
public static void main(String[] args) {
//prints the Floor Number of index and he Business listed on the floor
System.out.println("Floor Number\t\tBusiness");
//String array of businesses on each floor starting at floor 0-24
String floor [] = { "Ground Floor", "Advanced Technologies", "HiMark Marketing", "Law offices
of John Daniels", "PST Systems", "Century United Brokers Inc.", "Creative Resources", "Design
Centre Associates", "Ideal Media Group", "SF Net Developers", "Shears medical Services Inc.",
"Green Space Construction Inc.", "Cornerstone Mortgage Capital", "Allied Advantage Realty", "JAMS
the Resolution Experts", "Law Offices of Matt Dill", "Vacant", "The Drop in Centre", "Artisan
Interiors Consultancy", "NGS Group", "Robert H. Greene Real Estate", "Vacant", "Vacant", "Denise
A. Patterson Attorney at Law", "Conference Rooms 1-6" };
//for loop to print entire index to the user
for(int counter=0; counter<floor.length; counter++ ){
System.out.println(counter + "\t\t\t" + floor[counter]);
}//end for loop
Scanner businessname = new Scanner(System.in);
String namefind;
System.out.print("Enter the name of the Business: ");
namefind = businessname.next();
for(int i = 0; i < floor.length; i++){
if(namefind.equalsIgnoreCase(floor[i])) {
System.out.println("Business Found!");
System.exit(0);
}
}
System.out.println("Business not found, try again");
}//end main
}//end class
答案 0 :(得分:2)
而不是使用
namefind = businessname.next();
使用
namefind = businessname.nextLine();
因此也需要考虑空间。
答案 1 :(得分:1)
如果您使用扫描仪,其基本的下一个方法将为您提供下一个标记,即由空格分隔的内容。
使用nextLine获取包含用户输入,修剪前导和尾随空格的完整行,并在搜索中使用它。
namefind = businessname.nextLine();
答案 2 :(得分:0)
您也可以使用 BufferedReader 代替扫描程序来满足您的要求。这是更有效的方式。
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = br.readLine();