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 :)
Related
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.
We were given a task to make a program that takes the input of the user. there two types of input the user can use, 1st is the "Type in the Size" and the second is "Type in the style" either way the user can just input in the 1st field or the 2nd field. when the users clicks ok the two inputs will be use to sortout a arraylist which contains the type of size and style in it.
public void viewResult(String style, String size) {
style = style.toLowerCase();
size = size.toLowerCase();
new_list = new ArrayList<>();
for(Items_container items:current_arrayList)
{
if (items.getStyle().toLowerCase().contains(style) && items.getSize().toLowerCase().contains(size))
{
new_list.add(items);
break;
}
else if (items.getSize().toLowerCase().contains(size)) {
new_list.add(items);
break;
}
else if (items.getStyle().toLowerCase().contains(style)) {
new_list.add(items);
break;
}
}
current_arraylist.clear();
adapter.filterSearch(new_list);
if (new_list.size() == 0) {
results.setText("Search not found");
} else {
results.setText("Results");
}
}
this is the method that I use to sortout out the Items_container now it does work fine (I guess)
but the problem is for example the user inputs "large" in the size input field and "blazzing" in the style input field the program must sort the items_container using the given inputs but it is not working because the program also includes all the items that has the same size or the same style.
I tried adding a break to the loop but now it only shows one data and what if there two or more data that matches the givens inputs, how can I do that?
You should check first if both conditions are set. That way you can separate if either one matches and if both match. Maybe put singular matches in a separate list in case no items match both conditions, but that's up to you.
And as others already said, break stops the loop, continue moves to the next item.
like code below:
for (int i = 0; i <current_arrayList.size() ; i++) {
if(current_arrayList.get(i).getStyle().toLowerCase().contains(style)
&& current_arrayList.get(i).getSize().toLowerCase().contains(size))
{
new_list.add(current_arrayList.get(i));
//if used break ,stop loop
}
else if (current_arrayList.get(i).getSize().toLowerCase().contains(size)) {
new_list.add(current_arrayList.get(i));
}
else if (current_arrayList.get(i).getStyle().toLowerCase().contains(style)) {
new_list.add(current_arrayList.get(i));
}
}
current_arraylist.clear();
adapter.filterSearch(new_list);
adapter.notifyDataSetChanged();
I have a registration page where the user has to enter personal information about themselves, if something entered is invalid then error notifications should pop up
if (!PhoneNumber.startsWith("055") || !PhoneNumber.startsWith("050") || !PhoneNumber.startsWith("056") || !PhoneNumber.startsWith("052")) {
// does not match
contact_number.setError("Please enter a valid phone number");
return;
}
if (TextUtils.isEmpty(password) )
{
VendorRegPassword.setError("Please enter your password");
return;
}
else if (password.length() < 6)
{
VendorRegPassword.setError("Please use more than 6 characters");
return;
}
if (TextUtils.isEmpty(email) || !email.contains("#") )
{
VendorRegEmail.setError("Please enter a valid email address");
}
Independently they work on their own but when put together it does not work properly, also the phone number error does not work properly, can somebody help me with this?
The other answer is correct; the return statement simply prevents all checks to be executed. And in this case, you want all validations to take place, as each validation has a different way of informing the user about the problem.
Beyond that: from a "clean code" perspective you should be careful to simply stuff all validations into the same poor method. Instead: structure your code so that it clearly expresses what is going on, like:
private void validateAll(PhoneNumber number, Email email, Password password) {
validatePhoneNumber(number);
validateEmail(email);
...
and separate helpers like
private void validatePhoneNumber(number) {
boolean validPrefix = false;
for (String validPrefix : PREFEIXES) {
if (phoneNumber.startsWith(validPrefix) {
validPrefix = true;
}
}
if (!validPrefix) {
contact_number.setError("Please enter a valid phone number");
}
}
for example. And please note - I fixed another bad practice (your idea to simply hard-code all valid prefixes). You always want to put such information into some constant set/list; so that you have exactly one place in your code that knows what those prefixes are.
They are not working together properly because you are returning from the method in if or else ifconditions. Remove return statements from if and else. Because return will terminate the execution of method, so further code will never be executed due to return.
They are working separately because, there is no need to execute further conditions (no further conditions at all), so returning from method seems correct solution.
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
}
I'm sure if you read the snippet you'll understand what I'm trying to do. However, I tried it first with null and "". I think .eoln() won't work because I'm asking for multiple lines of input, of which all have an end of line. I would preferably have the loop terminate when the user returns an empty line. For some more background, I've used the ==/!= and .equals() operators/method to experiment. I also just tried a do/while to no avail.
The asterisks were added to test if the empty string was an issue for the while statement.
Can anyone explain what I clearly don't understand about Java/TextIO yet?
EDIT - Revised Code Snippet:
while(write){
pl("Begin writing content to fill file.");
pl("");
pl("Return a line with a single SPACE or");
pl("\"\\n\" to represent line breaks in your");
pl("");
pl("Return two asterisks ** when done writing,");
pl("and you will be then prompted to select a file");
pl("to save your writing to.");
String input = TextIO.getln();;
String value = new String();
while(!(input.equals(""))) {
if (input == " " || input == "\\n") {
value += "\\n" + "\\n";
} else {
value += input + " ";
} // end if/else //
input = TextIO.getln();
} // end while(input) //
TextIO.writeUserSelectedFile();
p(value);
TextIO.writeStandardOutput();
pl("Would you like to write to another file?");
Boolean cont = TextIO.getBoolean();
write = cont;
}
}