首页 > 解决方案 > 使用扫描仪时如何检测空白点并用预定答案填写?(爪哇)

问题描述

目前我正在编写一个从文件中提取数据的程序。文件中的一行通常有 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(); 
    }


}

标签: java

解决方案


你正面临这个问题,因为你正在阅读使用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.


推荐阅读