不读两个字输入

时间:2012-02-19 10:09:22

标签: java java.util.scanner

我目前正在制作一个小程序来教我一些新的Java,而且我被困了。我正在制作的程序,你进入一个预先设定的位置,它会给你一个它的距离。除了我想添加两个+单词位置,除非我输入它们,它直接进入else语句,而不是给出jist。我的代码如下。

import java.util.*;

public class Distance {
    String _destination;
    public Distance() {
    Scanner scan = new Scanner(System.in);
        System.out.println("Where do you want to go?");
            _destination = scan.next();

        if(getDistance() >= 2000) {
            System.out.println("F*cking woop c*nt");
        } else if(getDistance() >= 500) {
            System.out.println("F*cking far c*nt");
        } else if(getDistance() < 0) {
            System.out.println("What are you? Retarded?");
        } else if(getDistance().equals("0") {
            System.out.println("Why bother?");
        } else {
            System.out.println("Walk it c*nt");
        }
    }

    public int getDistance() {
     int distance = 0;
        if(_destination.equalsIgnoreCase("Ellenbrook")) {
            distance = 1200;
        } else if(_destination.equalsIgnoreCase("Midland")) {
            distance = 900;
        } else if(_destination.equalsIgnoreCase("Perth")) {
            distance = 200;
        } else if(_destination.equalsIgnoreCase("Woop Woop")) {
            distance = 2100;
        } else if(_destination.equalsIgnoreCase("High Wycombe")) {
            distance = -2;
        }

        return distance;
    }

    public static void main(String[] args) {
        new Distance();
    }
}

2 个答案:

答案 0 :(得分:3)

您需要使用scan.nextLine()来获取字符串作为输入,如下所述:

import java.util.*;
public class Distance {
    String _destination;
    public Distance() {
    Scanner scan = new Scanner(System.in);
        System.out.println("Where do you want to go?");
            _destination = scan.nextLine();

        if(getDistance() >= 2000) {
            System.out.println("F*cking woop c*nt");
        } else if(getDistance() >= 500) {
            System.out.println("F*cking far c*nt");
        } else if(getDistance() < 0) {
            System.out.println("What are you? Retarded?");
        } else if(getDistance()==0) {
            System.out.println("Why bother?");
        } else {
            System.out.println("Walk it c*nt");
        }
    }

    public int getDistance() {
     int distance = 0;
        if(_destination.equalsIgnoreCase("Ellenbrook")) {
            distance = 1200;
        } else if(_destination.equalsIgnoreCase("Midland")) {
            distance = 900;
        } else if(_destination.equalsIgnoreCase("Perth")) {
            distance = 200;
        } else if(_destination.equalsIgnoreCase("Woop Woop")) {
            distance = 2100;
        } else if(_destination.equalsIgnoreCase("High Wycombe")) {
            distance = -2;
        }

        return distance;
    }

    public static void main(String[] args) {
        new Distance();
    }
}

答案 1 :(得分:2)

默认情况下,扫描程序会对空格字符进行标记,因此您对next的调用只返回一个单词。您需要将扫描仪更改为使用换行符进行标记,或使用BufferedReader(和readLine方法)来获取输入。