어떻게 스캐너를 사용할 때 빈 공간을 감지하고 미리 정해진 답을 기입하는? (자바)

itsDathan :

현재 내가 파일에서 데이터를 가져옵니다 프로그램을 쓰고 있어요. 첫 번째는 온도 및 풍속을 나타내는 두 번째를 나타내는 상기 파일의 라인 2 개 번호는 일반적으로있다. 스캐너가 파일을 읽고 있지만, 풍속이 비어있는 몇몇 장소가있다, 그래서 나는 그것을 설정합니다. 공백이 있기 때문에 그냥 자리 스킵하고보고 그 다음 번호에가는 끝납니다. 거기에 아무것도 내가 빈 자리에 두는 NA 또는 0이있는 경우 그 때문에 그것을 만들 것입니다 추가 할 수 있습니까? 나는 매우 혼란 스러워요 그래서 나는 자바에 아주 새로운 오전.

데이터 파일의 예 :

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(); 
    }


}
아빈 드 쿠마 Avinash :

사용 읽고 있기 때문에 문제에 직면하고있다 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

file.txt를의 내용 :

20    10
15    5
12 
5     16

의심 / 문제의 경우에 의견을 주시기 바랍니다.

추천

출처http://43.154.161.224:23101/article/api/json?id=367550&siteId=1