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.
Related
//Code up
if (userinput.contains(help)) {
//Go on with the game
}
else {
System.out.println("Im sorry , couldnt understand that"); //here is where i want to go back up and
repeat the command
}
I tried almost everything a beginner would know and nothing , do while loops not working in my case (maybe you can find a way) , if i let the if like that the game closes if you get the wrong answer (something out of conttext) , some help would be great! Thx :D
You could use a 'Recursive' function (a function that calls itself).
So in this case, you could do something like:
public void getAndParseInput(){
String userInput = getUserInput() // Use whatever you're using to get input
if(userInput.contains(help)){
// If the user input contains whatever the help is (note: if you're looking for the specific word help, it needs to be in speech marks - "help").
continueWithGame...
}else{
System.out.println("Im sorry , couldnt understand that");
this.getAndParseInput();
}
}
You need to put that code inside a while loop and establish an exit condition.
boolean endGame = false;
/* Here read userinput */
While(!endGame) {
if (userinput.contains(help)) {
//Go on with the game
} else if(userinput.contains("quit"){
endGame = true;
} else {
System.out.println("Im sorry , couldnt understand that"); //here is where i want to go back up and
repeat the command
}
/* Here read userinput */
}
The Below code is similar to your code,reuse the code with appropriate changes as you required.
The code works as below.
1. Scans the input from the console
2. Compares the scanned input with the String "help"
3. If scanned input matches with help, then continue with the execution
4. Otherwise, if the user wants to continue then he can press the
letter 'C' and continues with the execution.
5. If user doesn't press 'C', then the control breaks the while loop
and comes out of the execution
public void executeGame() {
Scanner scanner = new Scanner(System.in);
String help = "help";
while(true) {
System.out.println("Enter the input for execution");
String input = scanner.nextLine();
if (input.contains(help)){
System.out.println("Continue execution");
} else {
System.out.println("Sorry Wrong input.. Would you like to continue press C");
input = scanner.nextLine();
if (input.equals("C")){
continue;
} else {
System.out.println("Sorry wrong input :"+input);
System.out.println("Hence Existing....");
System.exit(0);
}
}
}
}
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'
When I run the code I am not able to input to the scanner and continue through the code the way I want to. Can someone help me with some advice? I have imported the java.util.Scanner succesfully. BTW, I do call the method in the original program, I just removed it before I posted the question. I am using BlueJ.
public class Instructions extends ConsoleProgram
{
public boolean question(String prompt) {
Scanner s = new Scanner(System.in);
println(prompt);
String str = s.next();
boolean result = true;
while(!(str.equals("yes") || str.equals("no"))) {
str = s.next();
println("enter yes or no");
}
if (str.equals("yes")) {
result = true;
} else if (str.equals("no")) {
result = false;
}
return result;
}
Am I using the Scanner properly?
That isn't the problem. The real problem is a straight-forward bug in your application logic. This condition:
!(str.equals("yes") && str.equals("no"))
can never be false. A String cannot be both equal to "yes" AND equal to "no" at the same time. Therefore your while loop cannot terminate.
UPDATE
Following the edit, your code should more or less work. But this is not quite right.
while(!(str.equals("yes") || str.equals("no"))) {
str = s.next();
println("enter yes or no");
}
1) You are reading the next input token BEFORE you prompt for it.
2) You are not consuming the remaining characters after the first token of the line that the user just entered.
This is better
while(!(str.equals("yes") || str.equals("no"))) {
s.nextLine();
println("enter yes or no");
str = s.next();
}
I suggest you go back and read the javadocs for the Scanner class carefully.
It is also possible that new Scanner(System.in) is wrong. That is normally the right thing to do, but your requirements might require you to read use input from some other input stream.
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'
Okay, so the program that I'm trying to figure out how to code (not really fix), I have to use Java to accept continuous input from the user until they enter a period. It then must calculate the total characters that the user input up to the period.
import java.io.*;
class ContinuousInput
{
public static void main(String[] args) throws IOException
{
InputStreamReader inStream = new InputStreamReader (System.in);
BufferedReader userInput = new BufferedReader (inStream);
String inputValues;
int numberValue;
System.out.println("Welcome to the input calculator!");
System.out.println("Please input anything you wish: ");
inputValues = userInput.readLine();
while (inputValues != null && inputValues.indexOf('.')) {
inputValues = userInput.readLine();
}
numberValue = inputValues.length();
System.out.println("The total number of characters is " + numberValue + ".");
System.out.println("Thank you for using the input calculator!");
}
}
Please don't suggest the use of Scanner, the Java SE Platform we're stuck using is the SDK 1.4.2_19 model and we can't update it.
Explanation of empty braces: I thought that if I put in the empty braces that it would allow for continuous input until the period was put in, but clearly that wasn't the case...
Edit: Updated code
Current Error: won't end when . is inputted.
You have to switch the if/else statement with while.
Sample :
inputValues = userInput.readLine();
while (!".".equals(inputValues) {
//do your stuff
//..and after done, read the next line of the user input.
inputValues = userInput.readLine();
}
Note: Never compare the values of String objects with the == operator. Use the equals() method.
If you just want to test, whether the sentence the user inputs contains a . symbols, you just have to switch from equals() to contains(). It's a built-in method from the java.lang.String class.
Sample:
while (inputValues != null && !inputValues.contains(".")) {
//do your stuff
}