0

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?

user2304942
  • 41
  • 2
  • 6
  • Are you looking for something with functionality to detect what the user input is or are you just looking to stop the entire program on some arbitrary input? – Mdev Apr 06 '14 at 22:07

2 Answers2

1

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:
Christian Tapia
  • 33,620
  • 7
  • 56
  • 73
  • that sounds dangerous to me, what if I haven't be able to finish "exit" but just "exi" on an iteration? Does the input reset? – user2304942 Apr 06 '14 at 22:24
  • If you type `"exi"` then the loop won't finish. Of course that you can validate the input so it shows again until a valid input is entered. – Christian Tapia Apr 06 '14 at 22:27
  • 2
    The console will wait for user input each time the `input = sc.nextLine();` statement is encountered. The user has to hit enter, so if they type `exi` and hit enter then it's 'their fault' and the loop will continue. Are you looking to detect user input without the user hitting enter? And is this something you want implemented solely in the console or is it okay if you use Swing/Awt? – Mdev Apr 06 '14 at 22:27
0

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
    }
}
Community
  • 1
  • 1
Mdev
  • 2,440
  • 2
  • 17
  • 25