java - 使用扫描仪时如何检测空白点并用预定答案填写?(爪哇)
问题描述
目前我正在编写一个从文件中提取数据的程序。文件中的一行通常有 2 个数字,其中第一个代表温度,第二个代表风速。我设置它以便扫描仪读取文件,但有些地方风速是空白的。由于有空格,它最终只是跳过该位置并转到它看到的下一个数字。有什么我可以添加的东西可以使它如此,如果有一个空白点放入一个 NA 或 0 ?我对java很陌生,所以我很困惑。
数据文件示例:
20\s\s\s10\n
15\s\s\s 5\n
12\s\s\s\n
5\s\s\s16\n
public class readingData {
private Scanner x;
public void openFile(){
try{
x = new Scanner(new File("weatherData.txt"));
}
catch(Exception e) {
System.out.println("File not found");
}
}
public void readData(){
while(x.hasNext()) {
int tempf = x.nextInt();
int windspeed = x.nextInt();
int celsius = ((tempf-32)*5/9); //Celcius equatin
double windmps = windspeed / 2.23694; // Wind in mps equation
double windchill = 35.74 + 0.6215*tempf + (0.4275*tempf - 35.75) * Math.pow(windspeed, 0.16); // Windchill equation
double windchillc = ((windchill-32)*5/9);
if (tempf <= 50) {
System.out.printf("%20s%20s%20s%20s%20s\n", "Farenheit:","Celcius","Wind Speed(MPH)" ,"Wind Chill(F)" , "Wind Chill(C)" , "Wind Speed(MPS)");
System.out.printf("%20s%20s%20s%20s%20s\n", tempf, celsius,windspeed ,(int)windchill, (int)windchillc, (int)windmps);
}
}
}
public void closeFile() {
x.close();
}
}
解决方案
你正面临这个问题,因为你正在阅读使用nextInt()
. 我建议您阅读一行使用nextLine()
然后使用正则表达式将其拆分,例如
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int tempf, windspeed;
Scanner x;
try {
x = new Scanner(new File("file.txt"));
while (x.hasNextLine()) {
String[] data = x.nextLine().split("\\s+"); // Split the line on space(s)
try {
tempf = Integer.parseInt(data[0]);
System.out.print(tempf + " ");
} catch (Exception e) {
System.out.println("Invalid/No data for temperature");
tempf = 0;
}
try {
windspeed = Integer.parseInt(data[1]);
System.out.println(windspeed);
} catch (Exception e) {
System.out.println("Invalid/No data for wind speed");
windspeed = 0;
}
}
} catch (FileNotFoundException e) {
System.out.println("Unable to read file.");
}
}
}
Output:
20 10
15 5
12 Invalid/No data for wind speed
5 16
Content of file.txt:
20 10
15 5
12
5 16
Feel free to comment in case of any doubt/issue.
推荐阅读
- apache-spark - 使用 --files 传递文件时,Spark-Submit 在集群模式下失败
- floating-point - 32 位 IEEE 754 单精度浮点到十六进制
- php - Laravel 5.x 如何使用路由名称获取控制器名称?
- stripe-payments - 条带测试:当使用像 tok_visa 这样的测试令牌时,如何使 cvc_check 和 address_zip_check 设置为 true?
- java - 逐行从文本中读取 int
- javascript - Javascript图表一步
- c# - 异常时取消 OnLoad
- angular - 使用 RxJS(和 Angular)临时缓存来自参数化请求的 HTTP 响应
- amazon-web-services - 在 ECS 上使用我修改的 nginx.conf 启动 NginX
- r - R ggplot 重叠线以使用 matplotlib 颜色行为