与扫描仪类混淆 - > nextLine()

时间:2015-07-30 14:05:49

标签: java java.util.scanner

我编写了一个基本代码来读取不同的数据类型。但我无法输入字符串作为输入。我错过了什么?

    private class GpsStatusListener implements GpsStatus.Listener {

    @Override
    public void onGpsStatusChanged(int event) {

        switch (event) {

            case GpsStatus.GPS_EVENT_FIRST_FIX:
                locationListener.onGpsFixed();
                gpsActive = true;

                break;

            case GpsStatus.GPS_EVENT_SATELLITE_STATUS:

                int count = 0;
                for (GpsSatellite satellite: locationManager.getGpsStatus(null).getSatellites()) {
                    if (satellite.usedInFix())
                        count++;
                }

                boolean gpsPreActive = gpsActive;

                gpsActive = count >= 4;


                if (gpsPreActive && !gpsActive)
                    locationListener.onGpsUnlinked();

                locationListener.onGpsSatelliteStatus(count);
                break;

            case GpsStatus.GPS_EVENT_STARTED:
                locationListener.onGpsStarted();
                break;

            case GpsStatus.GPS_EVENT_STOPPED:
                locationListener.onGpsStopped();
                gpsActive = false;
                break;

        }

    }

}

1 个答案:

答案 0 :(得分:4)

你必须"吃掉"双线上留下的换行符。

Scanner read = new Scanner(System.in);
int integer = read.nextInt();
double Double = read.nextDouble();
read.nextLine();
String string = read.nextLine();
System.out.printf("String: %s\nDouble: %f\nInt: %d",string,Double,integer);

问题是在nextDouble()之后仍然有换行符,所以扫描程序会读取下一行中没有任何内容...