当前位置: 首页 > 知识库问答 >
问题:

停止扫描仪等待输入

殳智志
2023-03-14

为此,我创建了一个名为InputManager的单例。这个类处理所有的输入阅读内容。我创建了一个名为ask的方法,它将回调作为参数。在这个方法中,我创建了一个新线程,并在其中等待使用scanner.hasnextInt的输入。这个类还有CloseInput方法,它向上面描述的线程发送中断消息。下面是该类的当前实现:

class InputManager{
    private Thread thread;
    private InputManager(){}
    private static InputManager instance;
    private static InputManager getInstance(){
        if(instance == null){
            instance = new InputManager();
        }
        return instance;
    }

    /**
     * Ask user to type a number.
     * @param onSelected When the user has made his choice, this callback will be executed
     */
    public static void ask( Consumer<Integer> onSelected){
        getInstance().thread = new Thread(() -> {
            System.out.println("Type a number:");

            Scanner sc = new Scanner(System.in);
            int selection = -1;
            while (selection == -1) {
                if(Thread.currentThread().isInterrupted()){
                    return;
                }
                if(sc.hasNextInt()){
                    selection = sc.nextInt();
                    onSelected.accept(selection);
                } else {
                    sc.next();
                    selection = -1;
                }
            }
        });
        getInstance().thread.start();
    }

    /**
     * Reset input stream (?)
     */
    public static void closeInput(){
        try {
            getInstance().thread.interrupt();
        } catch(NullPointerException e){
            // do nothing
        }
    }
}

这个代码极不可靠。我一会儿就告诉你我的意思。我制作了一个名为Client的玩具类,在Main中,我用计时器模拟了TimerEnd消息收入。

class Client {
    /**
     * Ask user to type a number and send it to the server
     */
    void makeRequest(){
        InputManager.closeInput();
        InputManager.ask((selected) -> {
            System.out.println("Sent message: " + selected);
        });
    }

    public static void main(String[] args) {
        Client client = new Client();

        client.makeRequest();

        // Simulate Server messages
        Timer timer = new Timer();
        timer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                System.out.println("Message received");
                client.makeRequest();
            }
        }, 5000, 5000);
    }
}

以下是它的工作原理:

Type a number:
2
Sent message: 2
Message received
Type a number:
3
Sent message: 3
Message received
Type a number:     // Here I don't type anything
Message received
Type a number:
Message received
Type a number:
Message received
Type a number:     // Here I can send multiple messages on the same "turn"
1
Sent message: 1
2
Message received

我知道这个问题非常长(也许是不必要的),既然你读了它,让我感谢你花时间。

package com.company;

import java.util.*;
import java.util.function.Consumer;



class InputManager{
    private Thread thread;
    private InputManager(){}
    private static InputManager instance;
    private static InputManager getInstance(){
        if(instance == null){
            instance = new InputManager();
        }
        return instance;
    }

    /**
     * Ask user to type a number.
     * @param onSelected When the user has made his choice, this callback will be executed
     */
    public static void ask( Consumer<Integer> onSelected){
        getInstance().thread = new Thread(() -> {
            System.out.println("Type a number:");

            Scanner sc = new Scanner(System.in);
            int selection = -1;
            while (selection == -1) {
                if(Thread.currentThread().isInterrupted()){
                    return;
                }
                if(sc.hasNextInt()){
                    selection = sc.nextInt();
                    onSelected.accept(selection);
                } else {
                    sc.next();
                    selection = -1;
                }
            }
        });
        getInstance().thread.start();
    }

    /**
     * Reset input stream (?)
     */
    public static void closeInput(){
        try {
            getInstance().thread.interrupt();
        } catch(NullPointerException e){
            // do nothing
        }
    }
}

class Client {
    /**
     * Ask user to type a number and send it to the server
     */
    void makeRequest(){
        InputManager.closeInput();
        InputManager.ask((selected) -> {
            System.out.println("Sent message: " + selected);
        });
    }

    public static void main(String[] args) {
        Client client = new Client();

        client.makeRequest();
        Timer timer = new Timer();
        timer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                System.out.println("Message received: thread interrupted");
                client.makeRequest();
            }
        }, 5000, 5000);
    }
}

共有1个答案

邵星光
2023-03-14

在我看来,您可以使用3种类型的线程:

  1. 主线程在用户之间切换,宣布玩家上场,检查获胜条件,并在每个回合启动计时器。
  2. 第二个线程不断读取用户输入。读取用户输入后,它通知主线程。
  3. 最后一个线程等待5秒,然后通知主线程。

所以我将使用2个生产者和1个消费者如下:

    null
import java.util.Scanner;

public class Main {
    private static final Scanner SCAN = new Scanner(System.in);

    //This is the Scanner's input Producer:
    private static class UserInputProducer extends Thread {
        private final UserInputConsumer uInConsumer;

        public UserInputProducer(final UserInputConsumer uInConsumer) {
            this.uInConsumer = uInConsumer;
        }

        @Override
        public void run() {
            while (true) {
                final int input = SCAN.nextInt();
                SCAN.nextLine(); //Ignore the new line character.
                uInConsumer.userInput(input); //Fire user input event (for the current user).
            }
        }
    }

    //This is the time out event Producer:
    private static class TimeOutEventProducer {
        private final UserInputConsumer uInConsumer;

        private int validReportId = Integer.MIN_VALUE; //IDs starting from Integer.MIN_VALUE and
        //going step by step to Integer.MAX_VALUE, which means about 4 billion resets can be done
        //to this Producer before an unhandled overflow occurs.

        public TimeOutEventProducer(final UserInputConsumer uInConsumer) {
            this.uInConsumer = uInConsumer;
        }

        public synchronized void reset() {
            new TimerOnce(this, ++validReportId).start(); //Start a new TimerOnce. Could be javax.swing.Timer with "setRepeats(false)".
        }

        /*sleepDone(...) is called by ALL TimerOnce objects... So we need an up-to-date id (the
        reportId) to verify that the LAST one TimerOnce finished, rather than any other.*/
        public synchronized void sleepDone(final int reportId) {
            if (reportId == validReportId) //Only the last one timeout is valid...
                uInConsumer.timedOut(); //Fire time out event (for the current user).
        }
    }

    //This is just a "Timer" object which blocks for 5 seconds:
    private static class TimerOnce extends Thread {
        private final TimeOutEventProducer timeout;
        private final int reportId;

        public TimerOnce(final TimeOutEventProducer timeout,
                         final int reportId) {
            this.timeout = timeout;
            this.reportId = reportId;
        }

        @Override
        public void run() {
            try { Thread.sleep(5000); } catch (final InterruptedException ie) {} //Wait.
            timeout.sleepDone(reportId); //Report that the time elapsed...
        }
    }

    //This is the Consumer:
    private static class UserInputConsumer {
        private final String[] names;
        private int input;
        private boolean timedOut, hasInput;

        public UserInputConsumer(final String[] names) {
            this.names = names;
        }

        public synchronized int play() {
            new UserInputProducer(this).start(); //Start scanning any user's input...
            final TimeOutEventProducer timeout = new TimeOutEventProducer(this);
            int i = -1;
            do {
                i = (i + 1) % names.length;
                hasInput = false;
                timedOut = false;
                timeout.reset(); //Start the input wait timer...
                System.out.print("User " + names[i] + " enter a number: "); //Clarify who's player is the turn.
                while (!hasInput && !timedOut)
                    try { wait(); } catch (final InterruptedException ie) {} //Wait for user input or timeout.

                //Interpret notification event (either user input, either timeout):
                if (timedOut)
                    System.out.println("Sorry, out of time.");
                else if (!hasInput)
                    throw new UnsupportedOperationException("Probably messed with the flags in the while-condition.");
            }
            while (input != 5); //Here you test the win/loss condition.
            //Lets say, for example, the user that enters number '5' wins...

            return i; //Return the winner's index.
        }

        public synchronized void timedOut() {
            timedOut = true;
            notify();
        }

        public synchronized void userInput(final int input) {
            this.input = input;
            hasInput = true;
            notify();
        }
    }

    public static void main(final String[] args) {
        System.out.print("Enter number of players: ");
        final int numPlayers = SCAN.nextInt();
        SCAN.nextLine(); //Ignore the new line character.
        final String[] names = new String[numPlayers];
        for (int i=0; i<names.length; ++i) {
            System.out.print("User " + (i+1) + " enter your name: ");
            names[i] = SCAN.nextLine();
        }

        //Start the consumer (which in turn starts the producers) and start the main logic:
        System.out.println(names[new UserInputConsumer(names).play()] + " wins!");
    }
}
 类似资料:
  • 我对编程相当陌生。目前我正在做一个uni项目,用java创建一个基本的文本游戏。我遇到的问题是,如何实现一个不允许用户输入相同名称的业务规则。我把它设置好了,这样扫描仪就可以读取阵列了。我使用的是Java,这是我第一次使用这个论坛,所以我非常感谢大家提供的帮助,并提前感谢大家!:) 并为糟糕的格式道歉,我不知道如何正确发布。

  • 我正在使用Java的扫描仪读取用户输入。如果我只使用nextLine一次,它可以正常工作。对于两个nextLine,第一个不等待用户输入字符串(第二个)。 输出: X:Y:(等待输入) 我的代码 你知道为什么会发生这种事吗?谢谢

  • 我想在我的代码中手动读取一些值。除了最后一个(lambda2)之外,它对所有值都有效。我可以无限地继续键入值,即使它们不是双精度的,也不会发生任何事情。如果我用任何其他值键入其他值,我会收到一条错误消息,以及第一次输入lambda2时的错误消息。我在另一个代码中以类似的方式(最终只创建了一个不同的对象)进行了操作,并且效果很好。

  • 我这里有两个代码块。一个扫描器正确地等待用户输入,另一个则直接通过它并调用,返回。下面是工作的块: 下面是没有的块: 这两个都是单独的类,并且是从另一个类中的main方法调用的。基本上,调用,后者又调用某个Player类的方法...这是非工作代码所在的地方。程序中是否有不适合接受输入的时候?我的印象是,任何时候我需要用户输入,我都可以使用这种方法。谢谢!

  • 对于作业,我必须编写以下代码: 当我尝试编译它时,它在命令提示符下给了我3个错误,说“无法解析符号,符号:类扫描仪,位置:类单词,扫描仪用户输入=新扫描仪(System.in)”。我不确定错误在哪里。我应该使用BufferedReader作为输入吗?

  • 问题内容: 我正在使用Java的扫描仪读取用户输入。如果我仅使用nextLine一次,那就可以了。使用两个nextLine时,第一个不会等待用户输入字符串(第二个会输入)。 输出: X:Y :(等待输入) 我的密码 任何想法为什么会发生这种情况?谢谢 问题答案: 您可能像以前那样调用方法。这样的程序是这样的: 演示您所看到的行为。 问题是不消耗,因此下一个调用将消耗它,然后等待读取的输入。 您需要