- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我只能访问少数几行(正确的是41行)。此后我无法阅读。
import java.io.File;
import java.util.Scanner;
public class FileReader {
public static void main(String[] args) {
String filePath = "qwe.csv";
System.out.println("Enter the City name to be Searched\n");
Scanner in = new Scanner(System.in);
String searchTerm = in.nextLine();
readRecord(filePath, searchTerm);
}
public static void readRecord( String filePath, String searchTerm ) {
boolean found = false;
String City = ""; String City_Asciis = ""; String Lattitude = "";
String longitude = ""; String Country = "";
String iso_2 = ""; String iso_3 = ""; String Admin_Name = "";
String Capital = ""; String Population = ""; String Id = "";
try {
File file = new File(filePath);
Scanner x = new Scanner (file);
x.useDelimiter("[,\n]"); //to separate the data items
//hasNext - Returns true if the scanner has another token/value in its input
while(x.hasNext() && !found) {
City = x.next();
City_Asciis = x.next();
Lattitude = x.next();
longitude = x.next();
Country = x.next();
iso_2 = x.next();
iso_3 = x.next();
Admin_Name = x.next();
Capital = x.next();
Population = x.next();
Id = x.next();
if (City.equals(searchTerm)) {
found = true;
}
}
if (found) {
System.out.println(" The following details are of city : " + City +"\n The Ascii string would be : "
+ City_Asciis +"\n Its having the lattitude around : "
+ Lattitude + "\n and Longitude of : "+ longitude +"\n It is situated in : "
+ Country +"\n These have iso code like : "+ iso_2 +" and : "+ iso_3 +"\n It comes under : "
+ Admin_Name +" State \n Capital of this city is : "+ Capital +"\n The population is around : "
+ Population +"\n ZIP code is : "+Id+"");
}
else {
System.out.print("Enter the Correct City Name");
}
}
catch(Exception e1){
System.out.print("file not found \n");
e1.printStackTrace();
}
}
}
最佳答案
谁知道?
不费吹灰之力,代码本身看起来就应该工作,而且我个人无法理解为什么您的读取仅能执行41行,而无需对实际数据进行一系列实验,并且没有多少人真正愿意这样做这就是为什么要求您提供一些虚拟数据示例的原因。
这可能很简单,因为您满足了while循环条件内的布尔找到的变量条件,并且循环中断了读取。我怀疑这是因为您确实指出了"code will load the searched city from the file path given"
。我应该认为,这并不是您真正想要的,仅因为某些国家/地区包含相同的城市名称。实际上,同一国家/地区中的某些州,省或地区可以包含相同的城市名称。例如,您是否知道仅在United States中就有88个名为华盛顿的城镇?我知道,这很奇怪,特别是当您考虑到只有50个州和2个地区时。本杰明·富兰克林(Benjamin Franklin)还是美国的开国元勋之一,在该国有35个城镇和村庄/村庄以光荣的名字命名为富兰克林(Franklin)。
如果您的数据文件或数据库足够大,那么我确定您将要显示所有符合您特定搜索条件的城市。话虽如此,也许您需要做的就是为while循环摆脱&& !found
条件。我个人也不会在while循环条件下使用Scanner#hasNext()方法。这是灾难的诱因,因为它更侧重于与Scanner#next()结合使用而不是实际的文件行时,检查令牌的可用性。结合使用Scanner#hasNextLine()方法和Scanner#nextLine()方法,然后使用String#split()方法一次解析CSV逗号分隔的数据行。
下面,我提供一个可运行的Java代码示例,以演示上述方法。您使用了readRecord()方法,但对其进行了大量修改,以适应以下选项:
返回找到的城市信息的列表界面(List<String>
)
关于提供的搜索条件。
忽略(跳过)CSV文件中的空白行或注释行。注释行可以以#或;开头。
搜索期间忽略字母大小写的选项。
允许选择所需的城市信息字段
搜索条件将适用。城市信息领域
是:
城市,CityAscii,纬度,经度,国家/地区,ISO2,
ISO3,管理员名称,资本,人口和ID
在提供所需的搜索字段时,可以使用通配符(?和*),这样就不必提供整个字段名称,例如:纬度的lat*
。因此,如果您愿意,您可以仅根据人口进行城市信息搜索,而不是城市名称。
允许在通配符中使用通配符(?和*)
提供的搜索条件,例如:wash*
。这说明了方法
搜索任何以Wash开头的城市
华盛顿,华盛顿州或华盛顿州。
允许返回找到的城市实例的数量。
下面是可运行的代码,演示了上述概念。该代码是很好的注释。代码中使用了Regular Expressions,如果要解释这些表达式,则将其复制/粘贴到regex101.com中。
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class CityInfoRecords {
public static void main(String[] args) {
/* The appplication is started this way so that there
is no need for static methods or variables.
*/
new CityInfoRecords().startApp(args);
}
// Application Start method.
private void startApp(String[] args) {
String ls = System.lineSeparator(); // Not all OS Consoles work well with "\n"
String filePath = "qwe.csv"; // Path and file name of the data file.
Scanner in = new Scanner(System.in);
// Provide the City Info Field to base search from...
System.out.println("Enter the Data Field you want to search by:" + ls
+ "[City, CityAscii, Lattitude, Longitude, Country" + ls
+ "ISO2, ISO3, AdminName, Capital, Population, ID]" + ls
+ "Wildcards (? and *) can be used:");
String searchField = in.nextLine();
// Provide the Search Criteria to find within the supplied City Info Field.
System.out.println(ls + "Enter the search criteria you are looking for" + ls
+ "in " + searchField + ". Wildcards (? and *) are permitted:");
String searchCriteria = in.nextLine();
// Declare a List Interface of String and fill it
// with the call to the readRecord method.
List<String> cityInfoList = readRecord(filePath, searchField, searchCriteria, 0, "N/A");
// Display the returned List to console window.
for (int i = 0; i < cityInfoList.size(); i++) {
System.out.println(cityInfoList.get(i));
}
}
/**
* Returns a List Interface of the City Information found based on the supplied
* search criteria.<br><br>
*
* @param filePath (String) The full path and file name of the data file to read
* containing City information.<br>
*
* @param searchField (String) The City Information Field to based the supplied
* Search Criteria from. Any City Information Field can be supplied here and
* letter case is optional. The wildcard characters (? and *) can also be used
* here so that the entire field name does not need to be supplied, for example:
* <pre>
* lat* for the Latitude field or
* *asc* for the CityAscii field or
* iso? for either the ISO2 or ISO3 fields or simply
* City for the City field.</pre><br>
*
* The <b>?</b> wildcard character specifies any single alphanumeric character,
* as in ?an, which locates "ran," "pan", "can", and "ban".<br><br>
*
* The <b>*</b> wildcard character specifies zero or more of any alphanumeric
* character, as in corp*, which locates "corp", "corporate", "corporation",
* "corporal", and "corpulent".<br>
*
* @param searchCriteria (String) The search criteria string. This can be any
* string you would like to search for within the supplied City Information
* Field. By default letter case is ignored during searches therefore the
* supplied search criteria string does not need to be letter case specific
* however if you want the search to be case specific then set this methods
* optional ignoreLetterCase parameter to false.<br><br>
*
* Wildcard characters (? and *) can also be used within the Search Criteria
* string so as to expand the search to other possibilities, for example if
* the "City" field is supplied and a criteria string like: "wash*" is supplied
* then any city which name starts with "Wash" will have their city information
* returned.<br><br>
*
* The <b>?</b> wildcard character specifies any single alphanumeric character,
* as in ?an, which locates "ran," "pan", "can", and "ban".<br><br>
*
* The <b>*</b> wildcard character specifies zero or more of any alphanumeric
* character, as in corp*, which locates "corp", "corporate", "corporation",
* "corporal", and "corpulent".<br>
*
* @param numberOfFoundToReturn (int) The number of cities who's information
* should be returned. If 0 is supplied then all cities found will be returned.<br>
*
* @param noDataReplacement (String) Sometimes there is no data supplied for a
* specific field within the data file or the file data line may not contain
* the same amount of delimited data. Rather than returning NULL or Null String
* ("") for empty data fields you can supply here what to actually return in
* such a case. "N/A" is a good choice or perhaps: "Nothing Supplied". Whatever
* you like to use can be supplied here.<br>
*
* @param ignoreLetterCase (Optional - Boolean - Default is true) By default
* searches ignore letter case but if you want your search to be letter case
* specific then you can supply boolean false to this optional parameter.<br>
*
* @return (String List Collection) Information for every City found within the
* supplied data file which matches the supplied field and search criteria.
*/
public List<String> readRecord(String filePath, String searchField,
String searchCriteria, int numberOfFoundToReturn,
String noDataReplacement, boolean... ignoreLetterCase) {
String ls = System.lineSeparator(); // Not all OS Consoles work well with "\n" (property)
boolean ignoreCase = true; // Ignore letter case when searching (Default - property)
if (ignoreLetterCase.length > 0) {
ignoreCase = ignoreLetterCase[0];
}
boolean found = false; // Flag to indicate data was found (toggles)
int foundCounter = 0; // Indicates number of same data found (increments)
List<String> returnableList = // The List of found city information that will be returned (collection)
new ArrayList<>();
// City Information Variables (data fields)
String city;
String cityAscii;
String latitude;
String longitude;
String country;
String iso2;
String iso3;
String adminName;
String capital;
String population;
String id;
// Open Scanner to read data file...
// Try With Resources is used here to auto close the reader.
try (Scanner fileReader = new Scanner(new File(filePath))) {
// Iterate through data file...
while (fileReader.hasNextLine()) {
// Read file line by line and remove leading or
// trailing whitespaces, tabs, line breaks, etc.
String cityData = fileReader.nextLine().trim();
// Skip blank or comment lines (comment lines can be lines that start with # or ;)
if (cityData.equals("") || cityData.startsWith("#") || cityData.startsWith(";")) {
continue; // Get next file line
}
// Split the read line based on any comma delimited anomaly.
String[] cityInfo = cityData.split(",|,\\s+|\\s+,|\\s+,\\s+");
// The number of data pieces split from data line.
// Not all lines may contain the same amount of data.
int i = cityInfo.length;
/* Ternary is used to fill city information variables
so that data not provided will not be null or null string.
As an Example for the city variabel this is the same as:
if (i >= 1 && !cityInfo[0].equals("")) {
city = cityInfo[0].trim();
}
else {
city = noDataReplacement;
}
*/
city = (i >= 1 && !cityInfo[0].equals("")) ? cityInfo[0].trim() : noDataReplacement;
cityAscii = (i >= 2 && !cityInfo[1].equals("")) ? cityInfo[1].trim() : noDataReplacement;
latitude = (i >= 3 && !cityInfo[2].equals("")) ? cityInfo[2].trim() : noDataReplacement;
longitude = (i >= 4 && !cityInfo[3].equals("")) ? cityInfo[3].trim() : noDataReplacement;
country = (i >= 5 && !cityInfo[4].equals("")) ? cityInfo[4].trim() : noDataReplacement;
iso2 = (i >= 6 && !cityInfo[5].equals("")) ? cityInfo[5].trim() : noDataReplacement;
iso3 = (i >= 7 && !cityInfo[6].equals("")) ? cityInfo[6].trim() : noDataReplacement;
adminName = (i >= 8 && !cityInfo[7].equals("")) ? cityInfo[7].trim() : noDataReplacement;
capital = (i >= 9 && !cityInfo[8].equals("")) ? cityInfo[8].trim() : noDataReplacement;
population = (i >= 10 && !cityInfo[9].equals("")) ? cityInfo[9].trim() : noDataReplacement;
id = (i >= 11 && !cityInfo[10].equals("")) ? cityInfo[10].trim() : noDataReplacement;
// Determine the city data field we want to search in
String regex;
// Were wildcards used in the supplied Search Field string?
if (searchField.contains("?") || searchField.contains("*")) {
// Yes... Prep regex to get proper search field
regex = searchField.replace("?", ".?").replace("*", ".*?").toLowerCase();
}
else {
regex = "(?i)(" + searchField + ")";
}
// Get proper search field data
String field = "";
if ("city".toLowerCase().matches(regex)) {
field = city;
}
else if ("cityAsciis".toLowerCase().matches(regex)) {
field = cityAscii;
}
else if ("lattitude".toLowerCase().matches(regex)) {
field = latitude;
}
else if ("longitude".toLowerCase().matches(regex)) {
field = longitude;
}
else if ("country".toLowerCase().matches(regex)) {
field = country;
}
else if ("iso2".toLowerCase().matches(regex)) {
field = iso2;
}
else if ("iso3".toLowerCase().matches(regex)) {
field = iso3;
}
else if ("adminName".toLowerCase().matches(regex)) {
field = adminName;
}
else if ("capital".toLowerCase().matches(regex)) {
field = capital;
}
else if ("population".toLowerCase().matches(regex)) {
field = population;
}
else if ("id".toLowerCase().matches(regex)) {
field = id;
}
if (field.equals("")) {
System.err.println("Invalid Search Field Name Provided! (" + searchField + ")");
return returnableList;
}
// See if the search criteria contains wildcard characters
// A search can be carried out using wildcards in this method.
if (searchCriteria.contains("?") || searchCriteria.contains("*")) {
// There is...build the required Regular Expression (RegEx) to use.
regex = searchCriteria.replace("?", ".?").replace("*", ".*?");
// See if the data item matches the search criteria ignoring letter case if desired.
// The String.matches() method is used for this and ternary for ignoring letter case.
if (ignoreCase ? field.toLowerCase().matches(regex.toLowerCase()) : field.matches(regex)) {
found = true; // toogle flag to true if there is a match.
}
}
// No wildcard characters in search criteria...
// Ternary is used in condition to handle ignore letter case if desired.
else if (ignoreCase ? field.equalsIgnoreCase(searchCriteria) : field.equals(searchCriteria)) {
found = true; // toogle flag to true if there is a match.
}
// If the 'found' flag has been set to true...
if (found) {
// Add City information to returnable ArrayList
String info = ls + "The following details are of city: " + city + ls
+ "The Ascii string would be: " + cityAscii + ls
+ "It has the approximate Lattitude of: " + latitude + ls
+ "And the approximate Longitude of: " + longitude + ls
+ "It is situated in the country of: " + country + ls
+ "The city has iso codes like: " + iso2 + " and: " + iso3 + ls
+ "The State/Province/Region is: " + adminName + ls
+ "Capital of this city is: " + capital + ls
+ // Didn't know cities had capitals
"The population is approximately: " + population + ls
+ "City general ZIP code is: " + id;
returnableList.add(info); // Add to list
found = false; // Toggle found flag back to false in prep to locate more city data.
foundCounter++; // increment the found counter.
// If the First Instance Only flag is true then...
if (numberOfFoundToReturn > 0 && foundCounter == numberOfFoundToReturn) {
// Break out of the 'while' loop. We don't need anymore cities.
break;
}
}
}
// If the Found Counter was not incremented then
// we didn't find any data in file... Inform User.
if (foundCounter == 0) {
System.err.print(ls + "Can not find City Name (" + searchCriteria
+ ") in data file!" + ls);
}
}
catch (FileNotFoundException ex) {
System.err.print("City Data file not found! (" + filePath + ")" + ls);
}
// Return the List of found data.
return returnableList;
}
}
city
。
city
的搜索条件...以大写或小写形式输入城市名称(没关系)。城市信息将显示在控制台中,但前提是该城市名称包含在数据文件的“城市”字段中。
关于java - 如何根据输入字段搜索CSV文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54285067/
我有一个测试即将进行,我想澄清两个有关参数的问题。 在我的笔记中指出,将参数传递给函数的推荐方法是使用“按引用传递” const type& x; // for "in" parameters
当我通过 OMG 2.5(Beta)推广的 UML 规范阅读以下概念时: in: Indicates that Parameter values are passed in by the caller
我试图在用户按下 Enter 时触发一个函数。我将此输入设置为只读的原因是限制用户在填充值后修改输入中的值。 该值来自将在点击属性中触发的弹出窗口。问题是 keyup.enter 没有触发该输入。 代
我在jQuery中使用模式弹出窗口控件,该弹出窗口具有由jQuery Tokenize输入插件提供动力的输入文本。问题是,当我在模式弹出文本框中键入内容时, token 化插件的搜索结果显示为隐藏在弹
我有一个问题。当我选中复选框时,系统工作正常,总值发生变化,但一旦我修改文本输入,它就会变为 0。我需要将此文本框输入排除在更改值之外。 这是 html: $15000 $
我正在努力让它发挥作用,但还是有些不对劲。 我想用 CSS 设置提交按钮的样式以匹配我已有的按钮。 风格: input[type="button"], input[type="submit"], b
import java.util.*;; public class selection { Scanner in=new Scanner(System.in); private
这可能是一个非常菜鸟的问题。假设我有一个带宽限制为 100MB/s 的网卡,那么输入/输出带宽是否有可能达到该限制 同时 ?或者我会在任何时候遇到这个不等式:in bandwidth + out ba
看着这个问题,Fill immutable map with for loop upon creation ,我很好奇是什么this表示在 Map(1 -> this) . scala> Map(1
我有这样的东西 一个 乙 问? 是或否 数字 数字或零 我想做的是: 如果 B1 = “Y”,则让用户在 B2 中输入一个数字。 如果 B1 = “N”,则将 B2 中的值更改为零,并且不允许用户在
我有一个包含许多列的表,我想添加 input标题单元格内的字段,但我希望输入适合根据正文内容的宽度。 这是没有 input 的样子领域: 这就是 input 的样子领域: 可以看出,像“index”和
关于为 FTP 客户端设置传出和传入文件夹,您遵循哪些最佳实践(如果有)?我们通常使用“outgoing”和“incoming”,但无论你如何表述方向,它都可以有两种解释方式,具体取决于名称相对于哪一
我正在尝试“求解”给定 d 的 Pell 方程:x^2 - d * y^2 = 1,或者至少我想得到最小的 x > 0 来求解方程。到目前为止,一切都很好。这是我的 Haskell 代码 minX :
我是VS Code的新手,可以使用Ctrl + Enter将代码运行到python交互式窗口中。我希望光标自动移动到下一行,因此我可以逐行浏览代码。 能做到吗? 最佳答案 如this blog pos
我正在创建一个 bool 值矩阵/二维数组,并且我想为 dategrid 推断一种不仅仅是“ANY”的类型。 let yearRange = [2000,2001,2002,2003,2004]; l
我有两个排序的列表,例如 a = [1, 4, 7, 8] b = [1, 2, 3, 4, 5, 6] 我想知道a中的每个项目是否在b中。对于上面的示例,我想找到 a_in_b = [True, T
菜鸟警报 这很奇怪 - 当我编写以下代码时,尝试在 AngularJS 中创建自定义指令: myModule.directive('myTab', function(){ console.lo
已关闭。此问题需要 debugging details 。目前不接受答案。 编辑问题以包含 desired behavior, a specific problem or error, and the
假设我正在使用 gdscript 静态类型,并且对于一个函数参数,我事先不知道我会得到什么。这就是 python 中 typing.Any 的作用。如何使用 gdscript 做到这一点? 似乎 Va
我使用 dropzone 上传多个图像,并且工作正常,直到我想为每个图像插入品牌和网址。 我遇到的唯一问题是,当我要从输入字段获取值时,我会从服务器获取来自字段(品牌、网址)的未定义值,但如果我使用静
我是一名优秀的程序员,十分优秀!