【问题标题】:Searching for elements in an array with spaces在带有空格的数组中搜索元素
【发布时间】:2015-02-19 15:46:10
【问题描述】:

我创建了一个建筑目录,它基本上向用户显示了整个目录(使用字符串数组),如果他们不想查看整个目录,他们可以只搜索建筑中的特定业务。但是,我似乎无法让搜索选项工作,因为在我的数组之间有空格.. 例如:

String Floor [] = { "Ground Floor", "Vacant" };

如果我删除“Ground Floor”之间的空间并将其设为“GroundFloor”,则可以搜索它,否则如果您搜索“Ground Floor”,它就会显示为未找到。我能做些什么来解决这个问题?

程序的骨架:

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

【问题讨论】:

  • 这听起来更像是您的搜索方法中的逻辑错误。您可能希望发布该方法以帮助我们解决您的问题。
  • 我们无法告诉您代码中的错误在哪里以及如何在没有看到代码的情况下改进它。
  • 可能也是如何收集输入和/或将输入传播到搜索例程的问题。

标签: java arrays string spaces


【解决方案1】:

而不是使用

namefind = businessname.next();

使用

namefind = businessname.nextLine();

所以它也考虑到空间。

【讨论】:

  • 不是真正解决 OP 问题的方法。
  • 我在评论中猜到了这一点。感谢您重复我的回答!
【解决方案2】:

如果您使用扫描仪,其基本的 next 方法将为您提供下一个标记,即由空格分隔的内容。

使用 nextLine 获取包含用户输入的完整行,修剪前导和尾随空格并在搜索中使用它。

namefind = businessname.nextLine();

【讨论】:

    【解决方案3】:

    您也可以根据您的要求使用 BufferedReader 代替 Scanner。这是更有效的方式。

    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String line = br.readLine();
    

    【讨论】:

      猜你喜欢
      • 2012-02-23
      • 2021-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-03
      • 2023-02-01
      相关资源
      最近更新 更多