Getting input from users command and using .equals - java

Im trying to read the users input from the command box of my program and based on what the user enters into this command box the program should output appropriate messages. For example when the user enters quit the program is supposed to stop and I have implemented this correctly. SO what I am trying to achieve is when the users doesnt enter the words :"QUIT", "ROLL","property", "Buy" , "help" "done ,"balance" the program should displau an error message.
I need the command to work simultaneously so that if any 7 commands entered an appropriate message is returned
Here is my code so far:Thanks ,
private void echo () {
String command ;
String command2;
ui.display();
ui.displayString("ECHO MODE");
do {
command = ui.getCommand();
ui.displayString(command);
} while (!command.equals("quit"));
{
ui.displayString("The game is over.");
}
do{
command = ui.getCommand();
ui.displayString(command);
}while (!command.equals("help")||(!command.equals("buy"))||(!command.equals("roll"))||(!command.equals("done"))||(!command.equals("property"))||(!command.equals("balance")));
{
ui.displayString("Please enter a valid command");
}
return;

Your last do/while's condition looks almost good, but it should be using && instead of || : you want to display the error message when the command input isn't the first expected one, and not the second expected one, etc.
A prettier syntax would be to use a List of accepted commands and check whether it contains the received command :
List<String> acceptedCommands = new ArrayList<>();
acceptedCommands.add("help");
acceptedCommands.add("quit");
// [...]
do { command = ui.getCommand(); }
while (!acceptedCommands.contains(command));
Note that the do/while construct is rarely used (altough it can sometime be more appropriate than a standard while) and that you seem to misuse it ; you've used twice that same pattern :
do { actions }
while (condition)
{ more actions }
This is probably not doing what you want, since the last block isn't part of the do/while but just an anonymous code block, with its own scope but not much else.
After discussion I think you want something along those lines :
private void echo() {
String command = null;
while (!"quit".equals(command)) {
command = ui.getCommand();
if (!acceptedCommands.contains(command)) {
ui.displayString("Please enter a valid command");
} else if (!"quit".equals(command)) {
// handle other commands
}
}
ui.displayString("The game is over.");
// no need for "return;", it's implicit
}

Related

Im trying to make a text based game that looks like a PC terminal, i cant find a way to tell the user if they use a wrong sentence

//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);
}
}
}
}

Exception handling when dealing with user input for a beginner

I have to do a little program based in a shop, I have to add new clients to the shop customer collection, new items to the shop stock, edit them etc, so I use user input(scanner) to create this new objects. I have all the methods I need for this already without exceptions.
I would like some simple java exception handling for when the user introduces a string were he is supposed to enter a integer or viceversa.
For example if I'm executing a method to create a item for the shop and when I ask the user to introduce the stock(integer) the user types hello instead of a number the program crashes, I would like to handle the exception, show a error message, don't create the object and relaunch the item creation method from the beggining(or relaunch the submenu it was right before)
should I use try and catch? the method in try, when it fails catch throws message of error and relaunches the item creation menu? How should i do this? I've been searching and found a interesting method for integers here:
Exception Handling for no user input in Java
The problem is I don't know how I could handle possible exceptions for when introducing the ID for the user(which would be a string composed of 8 numbers and a letter like for example: 13234354A, so how could I show a error if a user introduces "sjadsjasdj" as a ID instead of something sort of realistic ) or some other things like handling exceptions for a few enum or boolean variables I use when creating this objects.
I've been looking in this site and searching google but I haven't found what I need or are more complex than what I understand with my little knowledge, also English is not my native language so my searches may be a little off.
Thanks for your time!
When you are reading the input just read in the the entire ID 123A for example and verify that each character is valid using for example Character.isDigit() and Character.isLetter(). With a 4 letter case
import java.util.Scanner;
public class Test {
public static void main(String[]args) {
boolean flag = false;
Scanner kb = new Scanner(System.in);
while(!flag) {
String id = kb.next();//To get the next word
flag = true;//by default its assumed to be valid input
if(id.length() == 4) {
for(int i = 0; i < 3; i++) {
if(!Character.isDigit(id.charAt(i))) {
flag = false;
}
}
if(!Character.isLetter(id.charAt(3))) {
flag = false;
}
}
else {
flag = false;
}
System.out.println("ID is "+ (flag == true?"Valid":"Invalid"));
}
}
}
Output
1234
ID is Invalid
123A
ID is Valid
You could throw your own error at the end if you want or just loop back to the beginning to take a new input.

How to Use Command Line Arguments to Dictate Flow of Program?

I have scoured all of Google it seems and I cannot find anything regarding how to use command line arguments to tell the Java program which subsequent method to perform. I am trying to create a Java program with several different aspects of a student grading application.
The main program is a GUI form where the user can input grades for each student in a specific class. Along with this, I need a control program that accepts 3 command arguments. The first is a number to indicate the type of file to load (1. XML 2. JSON 3. TXT). The second is a letter to indicate the file material (C indicates Course data, S indicates Student data). The last argument is the name of the specific data file to upload, which will then be extracted and uploaded to a database to be used by the GUI program.
I have the rest of the program already coded except for the command arguments because I have absolutely no idea what I am doing. The command argument code is supposed to look something like this:
public class Load
{
//Define global variables
static String inputDataChoice;
static String inputTableChoice;
static String inputFileName;
public static void main(String[] arg)
{
if (userChose == arg[0], arg[3], arg[5])
{
//If user chose 1 (XML), S (Student), and xmltest.xml
//Go to ParseXMLStudentFile();
}
if (userChose == arg[1], arg[4], arg[6])
{
//If user chose 2 (JSON), C (Course), and jsontest.json
//Go to ParseJSONCourseFile();
}
if (userChose == arg[2], arg[3], arg[7])
{
//If user chose 3 (TXT), S (Student), and test.txt
//Go to ParseTXTStudentFile();
}
}
}
I know that the above code is bogus, but that is the general idea. How do I accept command arguments from the user and then use that input to decide which method is executed? Would this program use the console window to accept user input? Please help!
arg contains the parameters passed to the command line, i.e. if you call the prog with prog.jar XML S xmltest.xml:
String fileType = arg[0]; // == XML
String material = arg[1]; // == S
String fileName = arg[2]; // == xmltest.xml
if (fileType.equals("XML") && material.equals("S")) {
parseXMLStudentFile(fileName);
} else { // ...
}

Handle one or multiple words in Java Socket .readLine()

I am building an application where I have a server and a client that talk to each other -over telnet. (via socket). The server program is monitoring a tank of some gass, and sends temperature level and preassure level via socket to the accepted clients.
I have managed to get the client and server to talk to each other when I write stuff --in telnet--, but...
I need some help to handle the data that I send.
I have made a loginscript to determine if the user is a valid user or not.
So I can write two words like "myname" "space" "mypassword" and I get a green light and returns a valid user.
But when I only write one word, and hit enter, it gives me:
Exeption in thread... java.lang.Array.IndexOutOfBoundsExeption EXEPT for when I write exit or logout!
(All users are hardcoded in the script for ease of use for testing. (The login script works fine by it self, and returns valid user = false when I write something wrong.)
Here is my code. Some pseudo code is added since I am not 100% sure of what to do...;)
String telNetCommand = dataIn.readLine();
System.out.println(telNetCommand);
String dataInArray[] = telNetCommand.split(" ");
user.isValid(dataInArray[0], dataInArray[1]);
if (dataInArray[1] == "\n") {
//Ignore login request and continue telnet-logging?
}
The client application has a button for each command, like:
"Send me every n'th data", or "Send me a batch of data every n'th second. If command equals exit, or logout - > break operation....
// --------------// USER INPUT FROM CLIENT APP //--------------------------//
// --------------// CONTINUE ? //----------------------------//
if (command.equals("CONTINUE")) {
continueSession();
else { //..Kill session
}
}
// --------------// SKIP <N> //----------------------------//
if (command.equals("SKIP_N")) {
skipEveryNthData();
}
// --------------// BATCH <N> //---------------------------//
if (command.equals("BATCH_N")) {
batchEveryNthData();
}
// --------------// LOGG OUT #1 //-------------------------//
if (command.equals("logout") || command.equals("exit")) {
break;
}
Maybe I am getting a bit confused now, but I think that I need to put all data into an array, and check
if
dataInArray[0] == "CONTINUE"
dataInArray[0] == "SKIP_N", or
dataInArray[0] == "BATCH_N"
(then send some data back)...
and...
if dataInArray[1] == "enter" ("\n") execute the single word commands ...??
if dataInArray[0] == "LOG_IN" or "PASSWORD" check if valid user is true..
Thanks for any help, and/or tips! :)
In this part of your code:
String dataInArray[] = telNetCommand.split(" ");
user.isValid(dataInArray[0], dataInArray[1]);
You assume that the telNetCommand string contains a space. If it does not, dataInArray will only contain one element and dataInArray[1] will throw an IndexOutOfBoundsExeption.
You should check the size of the array:
if (dataInArray.length < 2) {
//no space in the command - do what you need to do
//for example an error message
}
The IndexOutOfBoundsExeption more than likely being caused by:
user.isValid(dataInArray[0], dataInArray[1]);
Make sure that the incoming String telNetCommand contains at least one space so that you have at 2 Strings in the array. You could do this checking the size of the array:
if (dataInArray.length < 2) {
throw new IllegalArgumentException(telNetCommand + " only contains " + dataInArray.length + " elements");
}
Also, on a different note, make sure to use String.equals when checking String content:
if ("\n".equals(dataInArray[1])) {
Thanks guys. I don't get any errors now... And here is what I ended up doing.
I had to set it == 2 in order not to get any errors.
while (true) {
String telnetCommand = dataIn.readLine();
System.out.println(telnetCommand);
String dataInArray[] = telnetCommand.split(" ");
if (dataInArray.length == 2) {
user.isValid(dataInArray[0], dataInArray[1]);
}
if (dataInArray.length < 2) {
if (telnetCommand.equals("CONTINUE")) {
continueThisSession();
System.out.println("Running method continueThisSession");
}
if (telnetCommand.equals("SKIP_N")) {
skipEveryNthData();
System.out.println("Running method skipEveryNthData");
}
if (telnetCommand.equals("BATCH_N")) {
batchEveryNthData();
System.out.println("Running method batchEveryNthData");
}
if (telnetCommand.equals("logout") || telnetCommand.equals("exit")) {
break;
}
}
}
Peace :)

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