user2304942
user2304942

Reputation: 51

stop at anypoint upon user input?

I need to write a Java program that automatically runs, but can be stopped at any point upon user input. For example:

for (int i=0;i<1000000;i++){
   System.out.println(i);
}

when user type exit, the program should stop, how to do it?

Upvotes: 0

Views: 1189

Answers (2)

matt
matt

Reputation: 2429

You can do this in several ways. I've outlined a few that should cover most of the ones you might want.

  1. Multithreaded program with 2 threads, one of them for performing some arbitrary function and another dedicated to detecting if the user has typed 'exit'. This is quite crude and the user must press enter.
  2. JFrame that detects user input with a JTextField through one of two ways:
    • The user hits enter after typing 'exit'
    • The user simply types 'exit'
  3. Swap the JFrame/Console functionality in step 2. Display the arbitrary function in a JFrame somehow and stop it on the user typing 'exit' in the console. The user must press enter.
  4. Set the console to raw mode and subsequently detect if the user has typed 'exit' without the need for them to hit enter. There are several ways to do this and all of them involve external libraries. More information on your exact from this answer here and a similar problem with some different solutions here: Detecting and acting on keyboard direction keys in Java

Solution 1:

public class MultithreadedUserInput
{
    public static void main(String[] args)
    {
        InputDetector detector = new InputDetector();
        detector.start();

    for (int i = 0; i < 1000000; i++)
    {
        System.out.println(i);

        if (detector.getInput().equals("exit"))
        {
            break;
        }
    }

    //do something after user types exit
    }
}

and

import java.util.Scanner;

public class InputDetector implements Runnable
{
    private Thread thread;
    private String input;
    private Scanner scan;

    public InputDetector()
    {
        input = "";
        scan = new Scanner(System.in);
    }

    public void start()
    {
        thread = new Thread(this);
        thread.start();
    }

    @Override
    public void run()
    {
        while (!(input.equals("exit")))
        {
            input = scan.nextLine();
        }
    }

    public String getInput()
    {
        return input;
    }
}

Solutions 2 & 3:

There are if conditionals below that separate solution 2 from solution 3. The if before the break; statement either calls a method that checks the attribute input of the InputFrame. input is only updated after the user presses enter. The other if statement calls a method that simply checks the text in the JTextField.

import javax.swing.JFrame;

public class JFrameInput
{
    public static void main(String[] args)
    {
        InputFrame iFrame = new InputFrame();
        iFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        iFrame.pack();
        iFrame.setVisible(true);

        for (int i = 0; i < 1000000; i++)
        {
            System.out.println(i);
            if ((iFrame.getInput().equals("exit")))
            //if (iFrame.checkInput("exit"))    //use to exit without pressing enter
            {
                break;
            }
        }
        //do something after user types exit
    }
}

and

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JTextField;

public class InputFrame extends JFrame
{
    private String input;
    private JTextField text;

    public InputFrame()
    {
        super("Input Frame");
        input = "";
        text = new JTextField("");
        text.setToolTipText("Type 'exit' to stop the program.");

        text.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e)
            {
                input = text.getText();
            }
        });

        add(text);
        setResizable(false);
    }

    public String getInput()
    {
        return input;
    }

    public Boolean checkInput(String s)
    {
        if (text.getText().equals(s))
        {
            return true;
        }
        return false; //could use else to make this clearer
    }
}

Upvotes: 0

Christian Tapia
Christian Tapia

Reputation: 34146

You can use a do-while loop that checks on each iteration if the input is equal to "exit":

String input = "";
Scanner sc = new Scanner(System.in); // for input

do {
    input = sc.nextLine();
    // ...
} while (!input.equals("exit")) // if input is "exit", the loop finishes:

Upvotes: 1

Related Questions