I've been making a instant chat program, and wanted to make it possible for users to "whisper" or private message one another. The way I implemented that is the user would type:
/w [username] [message]
I then send it to the server which sends it to all the users. The users then have to check to see if its sent to them, this is that method:
if (message.startsWith("/msg/")) {
message = message.trim();
message = message.substring(5);
String[] words = message.split("//s");
String UserName = null;
try {
String username = words[2];
UserName = username;
System.out.println(UserName);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Error reading the whisper command!");
}
if (UserName == client.getName()) {
List<String> list = new ArrayList<String>(Arrays.asList(words));
list.removeAll(Arrays.asList(2));
words = list.toArray(words);
String text = words.toString();
text = "You've been whispered! " + message;
console(text);
}
Everytime I send a /w when I'm testing it always give the ArrayIndexOutOfBoundsException. I also modify the message in the sending. Heres that method:
else if (message.toLowerCase().startsWith("/w")) {
message = "/msg/" + client.getName() + message;
message = "/m/" + message + "/e/";
txtMessage.setText("");
}
I also added a whole bunch more options for the actual code for the users, I made it /whisper, /m, /msg, and /message, but those are all just copies of this with a different input. Why is it giving me an ArrayIndextOutOfBoundsException, when the 3rd place in the words array SHOULD be the username that the sender is trying to send it to. Obviously this probably isn't the best way to send private messages, and if any of you guys have a simpler way I can implement to my server, please go ahead and let me know! Just know that I am a young, new programmer and so I will probably have a lot of questions.
The slashes in your split() regex are backwards. You need
String[] words = message.split("\\s");
You can also just use a space
String[] words = message.split(" ");
Related
I am programming a little server-client-programm, which sends a text from one client who is writing on a file, to the other clients with the same filename, and got the following error
But I am just sending an integer and no other characters...
Here's the code:
Server
String[] splitter = scanText.split("\n");
String length = splitter.length + "";
//sending scanText to clients
for (PrintWriter pw2 : userMap.get(filename) ) {
if(!pw2.equals(pw))
{
pw2.println(length + "\n" + scanText);
}
}
Client
class "UpdateInBackground" is a class which is in the Client-class
class UpdateInBackground extends Thread {
#Override
public void run() {
int lines; //to know how much lines are send from the server
String scanText;
while (!this.isInterrupted()) {
scanText = "";
lines = Integer.parseInt(sc.nextLine()); //here I get the error
while (lines-- > 0) {
scanText += sc.nextLine() + "\n";
}
output.setText(scanText);
}
}
}
#asparagus, please define sc in line sc.nextLine(), considering this is an object from class Scanner, I need to know the input. The question must be self explainable with the definitions of variables and what are the inputs.
In Class UpdateInBackground,
lines = Integer.parseInt(sc.nextLine());// here nextLine() is for any String , please refer documentation
Reason for NumberFormatException : You are converting the value to int, without knowing, what is getting as input.
Try to use exception handling, to know what types of errors, might just come, to avoid the program getting struck.
Really needing help on this have been trying for the past hour playing around and can't seem to get it. Have looked for the question online and getting a lot of solutions that are similar but not quite accomplishing the task would appreciate if someone could help me with this?
I am currently working on a dropBox API and am trying to create a JOptionPane that prompts the user to enter the code generated from dropBox API and the program to read the input and verify.. I have done the System.in with success but this is for a GUI so obviously not helpful.
System.out.println("Enter Your auth code in this prompt and hit enter and wait..");
String result = JOptionPane.showInputDialog(null, "Enter Code Here: ");
String code = new BufferedReader(new InputStreamReader(System.in)).readLine();
// Want JOptionPane to function the same way this ^ would behave
String info = JOptionPane.showInputDialog(code +" test " );
if(code == null){
System.exit(1);
return;
}
code = code.trim();
// This will fail if the user enters an invalid authorization code.
DbxAuthFinish authFinish = webAuth.finish(code);
String accessToken = authFinish.accessToken;
DbxClient client = new DbxClient(config, accessToken);
System.out.println("Linked account: " + client.getAccountInfo().displayName);
JOptionPane.showMessageDialog(null, "Hello..."+
client.getAccountInfo().displayName+
" And Welcome To Our Community!");
The String 'result' should hold the code they entered into the JOptionPane.
EDIT #1:
String result = JOptionPane.showInputDialog(null, "Enter your auth code here:"); //Prompt for the auth code.
//If they didn't enter anything into the JOptionPane then close the program with code 1.
if (result.isEmpty()) {
System.exit(1);
}
System.out.println(result.trim()); //For testing purposes print the trimmed auth code to console.
// [Omitted Code] //
Also, you don't need to call return after a System.exit(#) because the program will never get to that code anyway.
i am really confused about some thing, and as i searched every thing is ok in my coding !
here when i use this code
sOutput.writeObject(theuser);
sOutput.writeObject(thepass);
sOutput.writeObject(thename);
sOutput.writeObject(themail);
sOutput.writeObject(thephone);
and recieve with this
String theuser = (String) sInput.readObject();
display(theuser);
String thepass = (String) sInput.readObject();
display(thepass);
String thename = (String) sInput.readObject();
display(thename);
String themail = (String) sInput.readObject();
display(themail);
String thephone = (String) sInput.readObject();
display(thephone);
everything works fine, but when i add these to the ready and write
int RID = (int) sInput.readInt();
to the read and
sOutput.writeInt(RID);
to the write
then it throws no exception, no error, just my server stops there at reading it ! RID is defined Int in sender ,its been given a random number. can you please help me?
When the reading program is stuck waiting for the input, and you know for sure that the writing program writes the data to its output, it is often the case that this happens because the written data has been buffered. In other words, it's been placed in a holding location on the sender, and not put on the wire to be sent to the receiver.
A simple way to fix this is to call flush() after writing the last element of data, like this:
sOutput.writeInt(RID);
sOutput.flush();
I have a mailbox file containing over 50 megs of messages separated by something like this:
From - Thu Jul 19 07:11:55 2007
I want to build a regular expression for this in Java to extract each mail message one at a time, so I tried using a Scanner, using the following pattern as the delimiter:
public boolean ParseData(DataSource data_source) {
boolean is_successful_transfer = false;
String mail_header_regex = "^From\\s";
LinkedList<String> ip_addresses = new LinkedList<String>();
ASNRepository asn_repository = new ASNRepository();
try {
Pattern mail_header_pattern = Pattern.compile(mail_header_regex);
File input_file = data_source.GetInputFile();
//parse out each message from the mailbox
Scanner scanner = new Scanner(input_file);
while(scanner.hasNext(mail_header_pattern)) {
String current_line = scanner.next(mail_header_pattern);
Matcher mail_matcher = mail_header_pattern.matcher(current_line);
//read each mail message and extract the proper "received from" ip address
//to put it in our list of ip's we can add to the database to prepare
//for querying.
while(mail_matcher.find()) {
String message_text = mail_matcher.group();
String ip_address = get_ip_address(message_text);
//empty ip address means the line contains no received from
if(!ip_address.trim().isEmpty())
ip_addresses.add(ip_address);
}
}//next line
//add ip addresses from mailbox to database
is_successful_transfer = asn_repository.AddIPAddresses(ip_addresses);
}
//error reading file--unsuccessful transfer
catch(FileNotFoundException ex) {
is_successful_transfer = false;
}
return is_successful_transfer;
}
This seems like it should work, but whenever I run it, the program hangs, probably due to it not finding the pattern. This same regular expression works in Perl with the same file, but in Java it always hangs on the String current_line = scanner.next(mail_header_pattern);
Is this regular expression correct or am I parsing the file incorrectly?
I'd be leaning toward something much simpler, by just reading lines, something like this:
while(scanner.hasNextLine()) {
String line = scanner.nextLine();
if (line.matches("^From\\s.*")) {
// it's a new email
} else {
// it's still part of the email body
}
}
I'm trying to send a lot of sms texts all at once, it works fine when i pull the numbers from the contacts themselves, but when i get them from the group i get an IllegalArgumentException that says "invalid destination address: trailing characters:" followed by the recipient's number.
I get the numbers from the contacts like this:
private void addContactGroup(BlackBerryContactGroup group) {
BlackBerryContact contact;
for(int i=0;i<group.numContacts();i++) {
_cntctsNmbrs.addElement(group.getAddress(i).trim());
}
}
And then i send the message:
try {
_conn = (MessageConnection)Connector.open("sms://");
final TextMessage msgOut = (TextMessage)
_conn.newMessage(MessageConnection.TEXT_MESSAGE,
"sms://"+_cntctsNmbrs.elementAt(i)+":0");
msgOut.setPayloadText(frmtdMsg);
_conn.send(msgOut);
} catch (final Exception e) {}
I searched all over but couldn't find this error anywhere.
it turns out that some of the rim oses add invisible control characters to the strings of group's addresses, i just called stringbuf.deleteCharAt(0) for each address and it worked out