如何在使用扫描仪时检测到一个空位,并用预先确定的答案填写?(Java)

  • 本文关键字:答案 Java 空位 扫描仪 一个 java
  • 更新时间 :
  • 英文 :


目前我正在编写一个从文件中提取数据的程序。文件中的一行通常有两个数字,第一个代表温度,第二个代表风速。我把它设置成扫描仪可以读取文件,但有些地方的风速是空白的。由于有空格,它最终只是跳过这个位置,转到它看到的下一个数字。我有什么可以补充的吗?如果有一个空白点,可以输入NA或0?我对java还很陌生,所以我很困惑。

数据文件示例:

20sss10n
15sss 5n
12sssn 
5sss16n
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%20sn", "Farenheit:","Celcius","Wind Speed(MPH)" ,"Wind Chill(F)" , "Wind Chill(C)" , "Wind Speed(MPS)");
System.out.printf("%20s%20s%20s%20s%20sn", 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.");
}
}
}

输出:

20 10
15 5
12 Invalid/No data for wind speed
5 16

文件.txt的内容:

20    10
15    5
12 
5     16

如有任何疑问/问题,请随时发表评论。

最新更新