Reputation: 51
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
Reputation: 2429
You can do this in several ways. I've outlined a few that should cover most of the ones you might want.
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;
}
}
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
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