I am having a problem passing Strings to a server / client simple example pay system. Basically I can pass double/s however I would like to send and recieve the Employee name also this is my code and it doesn't work, can anyone help or suggest something, thank you
MY CODE:
if (e.getSource() == calculate) {
try {
//Get the employee name, employee id, payrate & hours from the text fields
String empname = jtfEname.getText();
double empid = Double.parseDouble(jtfEid.getText().trim());
double payrate = Double.parseDouble(jtfPayRate.getText().trim());
double hours = Double.parseDouble(jtfHours.getText().trim());
//send the employee name, employee id, payrate & hours to the server
outputToServer.writeString(empname);
outputToServer.writeDouble(empid);
outputToServer.writeDouble(payrate);
outputToServer.writeDouble(hours);
outputToServer.flush();
//Get pay from the server
double pay = inputFromServer.readDouble();
//Display to the text area
jta.append("Employee Name is " + jtfEname + "\n");
jta.append("Employee ID is " + jtfEid + "\n");
jta.append("PayRate is " + jtfPayRate + "\n");
jta.append("Hours is " + jtfHours + "\n");
jta.append("Pay received from the server is " + pay + '\n');
jtfPayRate.setText("");
jtfHours.setText("");
}
You should use DataInputStream and DataOutputStream.
Then you can simply use the readUTF() and writeUTF() methods:
// Client: send String
DataOutputStream out = ...;
out.writeUTF("Some string");
// Server: receive String
DataInputStream in = ...;
String text = in.readUTF();
Related
I am working on an android app that summarizes text messages that are sent to clients from Financial services provider, a text message is sent as a notification each time a user makes a transaction.
Here is a sample message
[-ZAAD SHILLING-] Ref:1141125019 SLSH4,000 sent to AXMED XASAN
WARSAME(634458520) at 12/05/19 22:33:03, Your Balance is
SLSH44,222.62.
So I want to extract several portions of this message like
Ref:1141125019
Amount Sent: SLSH4,000
Recipient Name: AXMED XASAN WARSAME
Recipient Phone: 634458520
Date: 12/05/19
Time: 22:33:03
Balance: SLSH44,222.62
I have already got the text messages to appear in a listview, I now want to customize it, I don't want the whole message to appear, I just want the portion I mentioned above to appear.
Here is a Sample Code
if (Data.contains("Ref:")){
String[] Tx = Data.split("Ref:");
String TxID = Tx[1];
}
This problem would probably be best solved using regular expressions (regex)
Regular expressions allow you to match a string based on a pattern, and extract information from the string.
public static void main(String[] args) {
String data = "( [-ZAAD SHILLING-] Ref:1141125019 SLSH4,000 sent to AXMED XASAN WARSAME(634458520) at 12/05/19 22:33:03, Your Balance is SLSH44,222.62. )";
String headerReg = "\\[-([a-zA-Z\\s]+?)-]";
String refReg = "Ref:([0-9]+)";
String amountReg = "([,.\\w]+)";
String nameReg = "([\\w\\s]+?)";
String accountReg = "\\([0-9]+\\)";
String dateReg = "([0-9]{2}/[0-9]{2}/[0-9]{2})";
String timeReg = "([0-9]{2}:[0-9]{2}:[0-9]{2})";
String balanceReg = "([,.\\w]+?)";
String finalReg = "\\( " + headerReg + " " + refReg + " " + amountReg + " sent to " + nameReg + accountReg + " at " + dateReg + " " + timeReg + ", Your Balance is " + balanceReg + ". \\)";
Pattern pattern = Pattern.compile(finalReg);
Matcher matcher = pattern.matcher(data);
if (matcher.find()) {
MatchResult result = matcher.toMatchResult();
int groups = result.groupCount();
for (int i = 0; i < groups; i++) {
System.out.println(result.group(i + 1));
}
}
}
Using this, we can find the relevant data from your input string.
If the message syntax is always the same then you can use some tricky split strings like this:
String msg = "( [-ZAAD SHILLING-] Ref:1141125019 SLSH4,000 sent to AXMED XASAN WARSAME(634458520) at 12/05/19 22:33:03, Your Balance is SLSH44,222.62. )";
String ref = msg.split("Ref:")[1].split(" ")[0];
String amount = msg.split("Ref:")[1].split(" ")[1].split(" ")[0];
String recipient = msg.split("Ref:")[1].split("sent to ")[1].split("\\(")[0];
String phone = msg.split("Ref:")[1].split("sent to ")[1].split("\\(")[1].split("\\)")[0];
String date = msg.split("Ref:")[1].split("sent to ")[1].split("\\(")[1].split(" at ")[1].split(" ")[0];
String time = msg.split("Ref:")[1].split("sent to ")[1].split("\\(")[1].split(" at ")[1].split(" ")[1].split(",")[0];
String balance = msg.split("Your Balance is ")[1].split("\\)")[0];
System.out.println("ref: "+ref);
System.out.println("amount: "+amount);
System.out.println("recipient: "+recipient);
System.out.println("phone: "+phone);
System.out.println("date: "+date);
System.out.println("time: "+time);
System.out.println("balance: "+balance);
Result is:
ref: 1141125019
amount: SLSH4,000
recipient: AXMED XASAN WARSAME
phone: 634458520
date: 12/05/19
time: 22:33:03
balance: SLSH44,222.62.
I am wondering what the easiest way to write the output (last line of non-commented code below) to a .rtf file so that I can format some aspects with italics as well as keep a continuous, copy and paste-able, list of all my citations. Is there a way to do what I want that is simple? I am a beginner at Java and don't want anything too complicated to deal with.
/* (c) Tyler Holley January, 2018
* CitationGenerator Version 0.2
*
* User inputs academic source information and gets a proper citation back ready for copy and pasting into a Works Cited page.
*/
import java.util.Scanner;
class CitationGenerator {
public static String bookFormat(String author, String title, String publisher, int pubDate) {
//
String bFormat = author + ". " + title + ", " + publisher + ", " + pubDate + ".";
return bFormat;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String error1 = "ERROR: INVALID INPUT."; // Catchall error
String errorN = "ERROR: No other formats are currently supported in this version."; // Filler error while WIP
System.out.println("Welcome to CitationGenerator v0.1!");
System.out.print("What format is your citation in? MLA/APA/Chicago: "); // Add APA/Chicago support
String format = in.next();
if (format.equalsIgnoreCase("MLA")) { // equalsIgnoreCase ignores case inputted so MLA, mLa, mla, etc. are all valid
System.out.print("\nIs your source a book, website, or other? ");
String sourceType = in.next();
// Try and figure out how to clear the console after the user inputs sourceType
if (sourceType.equalsIgnoreCase("book")) {
System.out.print("\nAuthor's First Name: ");
String fName = in.next();
System.out.print("Author's Last Name: ");
String lName = in.next();
in.nextLine();
System.out.print("\nBook Title: ");
String title = in.nextLine();
System.out.print("\nPublisher Name: ");
String publisher = in.nextLine();
System.out.print("\nPublication Date: ");
int pubDate = in.nextInt();
String author = lName + ", " + fName; // Converts fName and lName to one concatonated String
System.out.println("\n\nHere is your citation! Don't forget to italicize the title!\n");
// Try to automatically italicize text when converting program to a .rtf
System.out.println(bookFormat(author, title, publisher, pubDate));
// GOAL: Alternate to the println below :
//System.out.println("\n\nYour citation is ready, would you like to save it to a/the .rtf document? y/n");
// This would branch into an if/else statement to print either to a document or continue to terminal output.
}
}
}
Pretty similar to writing to any file:
DataOutputStream dos;
File file = new File("\\your\\file\\path\\file.rtf");
try {
dos = new DataOutputStream(new FileOutputStream(file));
dos.writeBytes(bookFormat(author, title, publisher, pubDate));
dos.close();
catch( //IOexception or similar etc
Output:
surname, firstname. booktitle, bookpublisher, 1234.
I'm trying to read separate names and instruments up until the total number of bandmembers(asked earlier in the program) is reached. The program reads the amount, and reads the first name. However after that it fails in that it only reads the first name, it does not print any name or instrument after.
The while loop below is the most likely source of the problem:
i = counter
while(i <= bandMembers)
{
System.out.println("What is band member " + i + "'s name?");
kb.nextLine();
String bName = kb.nextLine();
System.out.println("What instrument does " + bName + " play?");
kb.nextLine();
String bNamePlay = kb1.nextLine();
list = list + i + ":" + " " + bName + " - " + bNamePlay+ "\n";
i++;
}
This is what it prints if I entered the first name as bName1:
Band Members
--------------
1: bName1 -
2: -
3: -
Any help appreciated, thanks.
Use BufferedReader instead.This will fix your problem.:-
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
i=counter;
while(i<=bandMembers){
System.out.println("Enter band member "+i+" name:-");
String bName=br.readLine();
System.out.println("What instrument does "+bName+" play?");
String bNamePlay=br.readLine();
list = list + i + ":" + " " + bName + " - " + bNamePlay+ "\n";
i++;
}
You should be using
String bName = kb.next();
Under the assumption that you are using a Scanner.
When you call nextLine() it reads the remainder of the same line and does not wait for input.
I don't have enough rep to comment on the issue you're having:
I was using kb.next at first but it read each word separated by a space as the next name. For example I would input "Jimmy loose hands" and it would prompt for Jimmy's instrument correctly, but it would then ask for band member 2's name and "what instrument does loose play?" simultaneously. So it took the second word as the next name.
What you may want to do is remove the "kb.nextLine();" before "String bName = kb.nextLine();"
I don't have an IDE open to confirm it, but that may be the reason that it is taking the second word/string entered as the name.
I need some help writing a program
Using this code I am able to enter in a track name, artist, etc.
I have a problem that I cannot now show this information in JOptionPane to display all of my info
import java.util.Scanner;
import javax.swing.JOptionPane;
public class TestTrack
{
public static void main(String[] args)
{
Scanner myScan = new Scanner(System.in);
System.out.println("Track name");
String name = myScan.nextLine();
System.out.println("Artist");
String Artist = myScan.nextLine();
System.out.println("Track length seconds");
String seconds = myScan.nextLine();
System.out.println("Album");
String Album = myScan.nextLine();
JOptionPane.showMessageDialog(null,"Trackinfo:")
}
}
So I guess I would want the pop out window to say
Track Name: "blank"
Artist: blank
Another question I have is how to ask this question multiple times by using "while" and asking if I would like to add another track
Sorry if I am using any terminology incorrectly I just started to learn Java
This line: JOptionPane.showMessageDialog(null,"Trackinfo:")
Contains what the pop-up window will contain. You pass in what you want its contents to be as the 2nd parameter, which is currently "Trackinfo".
To incorporate a while loop, you'll have to have a loop control variable, or a condition that will break the loop. In my example I used a string. My example uses a while loop that will continue as long as the string is not equal to "quit".
String test = "";
while( ! test.equals("quit") ) {
//use Scanner to get the next value the user enters
//ask for track info
//display that info in a message box
}
To obtain this:
Note: the texts of the OK and Cancel buttons are localized, if your computer is set to US locale you doesn't see 'Annuler"... ;-)
code this:
int answer = 0;
do {
/*----------------------------------------------------------------------------
Here you put the code which set the variables name, artist, seconds... (1)
----------------------------------------------------------------------------*/
final String title = "Track info";
final String message =
"<html><table>" +
"<tr><td>Track name" + "</td><td>" + name + "</td></tr>" +
"<tr><td>Artist" + "</td><td>" + artist + "</td></tr>" +
"<tr><td>Track length seconds</td><td>" + seconds + "</td></tr>" +
"<tr><td>Album" + "</td><td>" + album + "</td></tr>" +
"</table>";
answer =
JOptionPane.showConfirmDialog(
null, message, title, JOptionPane.OK_CANCEL_OPTION );
} while( answer == JOptionPane.OK_OPTION );
(1) You may choose Scanner or GUI whith JOptionPane.showInputDialog()
JOptionPane.showMessageDialog(null,"Trackinfo:" + "\nArtist: " + Artist + "\nseconds: " + seconds + "\nAlbum: " + Album)
Each '\n' means a new line. for doing this multiple times, you should place your code in a while loop, something like this:
while(!(Artist == "end")) {
//your code
}
Use myScan.next() instead of myScan.nextLine()
To output the information into the Message Dialog, use
String trackInfo = "Track Name: " + name + " | Artist : " +artist+ " | Track Length: " + seconds + " | Album: " + album;
JOptionPane.showMessageDialog(null, trackInfo, "Trackinfo", JOptionPane.INFORMATION_MESSAGE);
I have a number of xml's that come in haphazardly that contain a Ocount, and Lnumber, as well as other data. I have created a class to get that data.
My problem is that how can I group xml's that have the same Lnumber(string), until it reaches the Ocount(int). (the xmls that have the same lnumber has the same Ocount). And eventually send out a email telling with xmls has been processed.
String readLine = FileHandler.checkListFile(sh.getShipmentHeader().getBillToCustomer());
if (!readLine.isEmpty())
{
int orderCount = 0;
int index = readLine.indexOf(";") + 1;
String customerName = readLine.substring(index, readLine.indexOf(";", index)).trim();
index = readLine.indexOf(";", index) + 1;
String to = readLine.substring(index, readLine.length()).trim();
if (!billMap.containsKey(sh.getShipmentHeader().getBillToCustomer()))
{
billMap.put(sh.getShipmentHeader().getBillToCustomer(), 1);
orderCount = 1;
}
else
{
billMap.put(sh.getShipmentHeader().getBillToCustomer(), ((int) billMap.get(sh.getShipmentHeader().getBillToCustomer())) + 1);
orderCount = (int) billMap.get(sh.getShipmentHeader().getBillToCustomer());
}
outboundMessage += sh.getShipmentHeader().getOrderNumber() + li ;
logger.info("On-Demand Outbound Export Info: " + orderCount + " processed out of " + sh.getShipmentHeader().getOrderCount() +
" for " + customerName);
if (orderCount == sh.getShipmentHeader().getOrderCount())
{
Email email = new Email();
billMap.remove(sh.getShipmentHeader().getBillToCustomer());
outboundMessage += li + "Total of #"+ sh.getShipmentHeader().getOrderCount() + " orders processed for "+ customerName + li ;
logger.info("On-Demand Email sent for " + customerName);
System.out.println(outboundMessage);
email.outboundEmail("TEST: Orders for " + customerName + " complete", outboundMessage, to);
outboundMessage = "";
email = null;
}}
I been working on this for days, where am I going wrong.
It seems like you are having difficulty obtaining information from xmls. I suggest using XStream [1]. It is capable of serialising objects to xml and back. By using XStream, you can get an Object from the xml and compare variables (Lnumber and Ocount) easily.
If you insist using this code, I suggest adding comments to notify us what you are doing, but if want an easier alternative to work with xml files using java, I highly suggest using XStream as a solution.
[1] http://x-stream.github.io/