Detect a key press in console - java

I want to execute a certain function when a user presses a key. This will be run in the console, and the code is in Java. How do I do this? I have almost zero knowledge of key presses/keydowns, so I could really use an explanation as well.

You can't detect an event in the command line environment. You should provide a GUI, and then you can use the KeyListener class to detect a keyboard event.
Alternatively you can read commands from standard input and then execute a proper function.

If you want to play with the console, you can start with this:
import java.util.Scanner;
public class ScannerTest {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
boolean exit = false;
while (!exit) {
System.out.println("Enter command (quit to exit):");
String input = keyboard.nextLine();
if(input != null) {
System.out.println("Your input is : " + input);
if ("quit".equals(input)) {
System.out.println("Exit programm");
exit = true;
} else if ("x".equals(input)) {
//Do something
}
}
}
keyboard.close();
}
}
Simply run ScannerTest and type any text, followed by 'enter'

Related

How do I go back to the menu after taking several questions?

I am currently creating a program where the user enters a specific set of questions. And the program must go back to the menu after completely answering all questions. How should I do it?
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("""
\n \nAre you ready to take the quiz?
Enter "Y" to proceed or "N" to exit the program:""");
String TakeQuiz = input.nextLine();
if (TakeQuiz.equalsIgnoreCase("Y"))
do {
//blocks of code
}
}
}
System.out.println("Do you want to take the quiz again?");
String RetakeQuiz = input.nextLine();
while (RetakeQuiz.equalsIgnoreCase("Y")) ;
else {
System.out.println("We hope to see you again soon!");
System.exit(0);
}
}
}
There are many ways to achieve what you want, I would not clutter the main method and break the code to another function and loop there.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
for(;;)
takeQuiz();
}
public static void takeQuiz(){
Scanner input = new Scanner(System.in);
System.out.print("\n \nAre you ready to take the quiz?" +
"Enter \"Y\" to proceed or \"N\" to exit the program:");
String takeQuiz = input.nextLine();
if (takeQuiz.equalsIgnoreCase("Y")) {
System.out.println("Running code...");
System.out.println("Question 1");
System.out.println("Question 2");
System.out.println("Question 3");
}
// retake
if (takeQuiz.equalsIgnoreCase("R")){
takeQuiz();
}
if (takeQuiz.equalsIgnoreCase("N")){
System.out.println("We hope to see you again soon!");
System.exit(0);
}
}
}
Notice the escape character for quotes \" and the + for multiline Strings
Java 15 and beyond allows triple quotes as Java Text Blocks
so your String message should be valid
The basic structure is something like this:
boolean continueWithQuiz = true;
while (continueWithQuiz) {
// Put the code here for handling the quiz
...
// Should we keep going?
System.out.println("Do you want to take the quiz again?");
String retakeQuiz = input.nextLine();
continueWithQuiz = retakeQuiz == "Y";
}
One more comment. Please follow Java naming standards. Class names begin with an upper case letter. Constants should be ALL_CAPS. Everything else is in lower case.

Continuous Scanner input

I'm writing sort of main practice project, where I can just continually add classes that do completely different fun things. For example, I have a CoinFlipperCmd and a poker PotOddsCmd, and the code currently works fine, but I want to be able to repeatedly enter commands without having to rerun the program. Example console currently:
FLIP 10 // coinflips 10 times and notes the outcome
You flipped 5 heads and 5 tails
After this, the code will exit, but I want to be able to keep entering commands. Like so:
FLIP 5
You flipped 4 heads and 1 tails
FLIP 6
You flipped 3 heads and 3 tails
POTODDS 0.5 1
You have pot odds of 2:1
I'm using a scanner for input
import java.util.Scanner; // Import the Scanner class
public class Main {
public static void main(String[] args) {
InputScanner();
}
private static void InputScanner() {
Scanner myObj = new Scanner(System.in); // Create a Scanner object
System.out.println("Enter command");
String command = myObj.nextLine(); // Read user input
ParseAndDirect(command);
}
private static void ParseAndDirect(String command) {
String[] commandSplit = command.split(" ", 2);
String usercommand = commandSplit[0];
if (usercommand.equals("FLIP")){
CoinFlipperCmd.CoinFlipperCmd(commandSplit[1]);
} else if (usercommand.equals("POTODDS")){
PotOddsCmd.PotOddsCmd(commandSplit[1]);
} else System.out.println("Invalid Command");
}
}
You need to put the input part inside a loop e.g.
private static void InputScanner() {
Scanner myObj = new Scanner(System.in); // Create a Scanner object
String command;
do {
System.out.print("Enter command (q to quit): ");
command = myObj.nextLine(); // Read user input
if (!command.equalsIgnoreCase("q")) {
ParseAndDirect(command);
}
} while (!command.equalsIgnoreCase("q"));
}
Another way of using the loop can be as follows:
private static void InputScanner() {
Scanner myObj = new Scanner(System.in); // Create a Scanner object
String command;
while(true)
System.out.print("Enter command (q to quit): ");
command = myObj.nextLine(); // Read user input
if (command.equalsIgnoreCase("q")) {
break;
}
ParseAndDirect(command);
}
}
On a side note (because it won't have any impact on the execution of the program), you should always follow Java naming conventions e.g the method, ParseAndDirect should be named as parseAndDirect and InputScanner should be named as inputScanner.
Apart from allowing the user to repeatedly enter commands, I think you should also allow some way to quit the program (besides having to kill it via the operating system :-) In the below code, I have arbitrarily used the word quit as the way to exit the loop. Feel free to use a different string.
Scanner myObj = new Scanner(System.in);
String command = "";
while (!"quit".equalsIgnoreCase(command)) {
System.out.println("Enter command");
if (!"quit".equalsIgnoreCase(command)) {
ParseAndDirect(command);
}
}
By the way, according to java naming conventions the method name should be parseAndDirect, i.e. it should start with a lowercase letter.

Teach me why this code fails to check if my input is a int, and how I can fix it

import java.util.Scanner;
public class HelloWorld {
public static int num;
public static Scanner scan;
public static void main(String[] args) {
System.out.println("Hello World");
/* This reads the input provided by user
* using keyboard
*/
scan = new Scanner(System.in);
System.out.print("Enter any number: ");
// This method reads the number provided using keyboard
check();
// Closing Scanner after the use
// Displaying the number
System.out.println("The number entered by user: "+num);
}
public static void check(){
try{
num = scan.nextInt();
}
catch (Exception e){
System.out.println("not a integer, try again");
check();
}
}
}
Im new to coding, and am taking this summer to teach myself some basics. I was wondering if someone could advise me on how I can create this method to take in a int, and check the input to make sure thats its a int. If the input is not a int, I would like to re run in.
Simple. Say you have something as shown below . . .
NumberThing.isNumber(myStringValue);
.isNumber() determines if your string is a numerical value (aka a number). As for putting the code in a loop to continue to ask the user for input if their input is invalid, using a while loop should work. Something like . . .
while (. . .) {
// use something to exit the loop
// depending on what the user does
}
You might consider moving the user request code to the check method. Also, use a break statement to exit your while loop after a valid number is entered.
while ( true )
{
System.out.println( "Enter an integer.");
try
{
num = scan.nextInt();
break;
}
catch (Exception e)
{
System.out.println("not a integer");
}
}

Loop in Java until the user presses any key (not just the Enter key) in a console app [duplicate]

I want to execute a certain function when a user presses a key. This will be run in the console, and the code is in Java. How do I do this? I have almost zero knowledge of key presses/keydowns, so I could really use an explanation as well.
You can't detect an event in the command line environment. You should provide a GUI, and then you can use the KeyListener class to detect a keyboard event.
Alternatively you can read commands from standard input and then execute a proper function.
If you want to play with the console, you can start with this:
import java.util.Scanner;
public class ScannerTest {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
boolean exit = false;
while (!exit) {
System.out.println("Enter command (quit to exit):");
String input = keyboard.nextLine();
if(input != null) {
System.out.println("Your input is : " + input);
if ("quit".equals(input)) {
System.out.println("Exit programm");
exit = true;
} else if ("x".equals(input)) {
//Do something
}
}
}
keyboard.close();
}
}
Simply run ScannerTest and type any text, followed by 'enter'

Continuous input commands

My program will read user keyboard commands in the form of "command parameter" with a space in between. It keeps carrying out individual commands until the next command is "exit". Also, if the user messes up, the program should show an error but continue asking for commands (a feature I don't think I have completed)..
Is the following code a good way of implementing this? Could it handle the user simply pressing the enter key w/o a command, junk input, etc? If anything, I would love to know if there is a better idiomatic way implementing this.
String command = "";
String parameter = "";
Scanner dataIn = new Scanner(System.in);
while (!command.equals("exit")) {
System.out.print(">> ");
command = dataIn.next().trim();
parameter = dataIn.next().trim();
//should ^ these have error handling?
if (command.equals("dothis")) {
//do this w/ parameter..
} else if (command.equals("dothat")) {
//do that w/ parameter..
} //else if... {}
else {
system.out.println("Command not valid.");
}
}
System.out.println("Program exited by user.");
Note: I took this class without a single notion of what exception handling is, so any pointers in that area is greatly appreciated :)
This is a simple way to implement an input loop:
Scanner sc = new Scanner(System.in);
for (prompt(); sc.hasNextLine(); prompt()) {
String line = sc.nextLine().replaceAll("\n", "");
// return pressed
if (line.length == 0)
continue;
// split line into arguments
String[] args = line.split(" ");
// process arguments
if (args.length == 1) {
if (args[0].equalsIgnoreCase("exit"))
System.exit(0);
if (args[0].equalsIgnoreCase("dosomething"))
// do something
} else if (args.length == 2) {
// do stuff with parameters
}
}
Assuming prompt() prints out the prompt here.

Categories

Resources