扫描仪输入无法正常工作(Java)?

时间:2015-04-11 23:04:07

标签: java java.util.scanner

我是Java的新手,一直在尝试创建一个互动游戏。我可以在一个班级中完成它,但是我刚刚学会了如何使用两个班级,所以我想尝试一下。无论如何,似乎我的第二堂课(金枪鱼)中的扫描仪由于某种原因不起作用。我试图使用if和if else语句,但这也不起作用(是的,我使用'equals'而不是'=='作为if语句的参数)。我被合法地困住并需要帮助。我在Stack上寻找答案,但未能找到任何问题。请告诉我这部分代码有什么问题,因为它可能是一个逻辑错误。如果这是一个副本,请发送给我答案的链接,我会把这个给我。 码: 第一类:

    import java.util.Scanner;

class hand {

    public static void main(String[] args) {
        tuna opObject = new tuna();
        //creating input
        Scanner input = new Scanner(System.in);
        //instructions
        System.out.println("This is an interactive game. You are a traveler and have come across this strange hotel. Type in 'go' to begin.");
        // Initializing game
        if(input.nextLine().equals ("go")) {
                System.out.println("A smiling, some what tall fellow in a red suit walks up to you.'Welcome to the amazing, KingstonTraveler Hotel! How may I serve you traveler?'");
            }
        System.out.println("Will you a) punch him b) 'I would like a room' c) DIE! ");
        opObject.options();
        }
    }

SECOND CLASS(扫描仪不工作):

import java.util.Scanner;

public class tuna {
    Scanner input = new Scanner("System.in");
    public String answer = input.nextLine();
    public void options() {
        switch(answer){
        case "a": System.out.println("answer a");
            break;
        case "b": System.out.println("answer b");
            break;
        case "c": System.out.println("answer c");
        }
        }
    }

1 个答案:

答案 0 :(得分:3)

问题出在金枪鱼类:

Scanner input = new Scanner("System.in");

这会创建一个Scanner, that scans only on the String "System.in"。如果删除",您会注意到,您必须在程序启动前输入内容。这是因为在创建相应对象时(即input方法中的第一行)定义了属性(在这种情况下为main)。你想要的是这样的:

import java.util.Scanner;

public class Tuna { // Classes should always begin with an uppercase letter

    // Moved object attributes into method
    public void options() {
        // Now input is read if options() gets called
        Scanner input = new Scanner(System.in);
        String answer = input.nextLine();
        switch(answer) {
        case "a":
            System.out.println("answer a");
            break;
        case "b":
            System.out.println("answer b");
            break;
        case "c":
            System.out.println("answer c");
        }
        input.close(); // Close stream when we are done
    }
}