how to convert object into string? - string

I have this problem converting object into string... I make use of the toString() function... and since the conversion of object into string were inside the try{}catch(exception e){}, i keep on receiving an output error: For input string: ""
What should be the problem if i keep on receiving an error message like that?
More elaboration:
the Object came from a jComboBox
which consists of items from a
database.
I am using a JFrame Form instead of
a Java Class.
All i want to do is to capture the selected Item from the JComboBox which happens to be an object. And then after capturing it. I'll use the value for my query in the database.
Here's my code(partial):
private void SUBMITActionPerformed(java.awt.event.ActionEvent evt) {
try {
Class.forName(Connect.DRIVER);
Connection con = DriverManager.getConnection(Connect.CONNECTION_STRING,
Connect.USERNAME, Connect.PASSWORD);
Object obj = jComboBox1.getSelectedItem();
String item_name = obj.toString();
int month = jMonthChooser.getMonth();
int q_box = Integer.parseInt(quantity_box_txtbox.getText());
double unit_price_box = 0;
int q_pc = Integer.parseInt(quantity_pc_txtbox.getText());
double unit_price_pc = 0;
double sub_total_box = 0;
double sub_total_pc = 0;
double grand_total = 0;
//Testing
System.out.println(jMonthChooser.getMonth());
System.out.println(item_name);
} catch (Exception e) {
System.out.println("Error: "+e.getMessage());
}
}
If you have anything you don't understand regarding with the way I explain my question please tell me... i'll try my best to elaborate further.
Thanks in advance.
:)
here's the complete error:
Error: java.lang.NumberFormatException : For input string: ""

Well, to start with:
Don't catch just Exception; catch specific subclasses
Don't just catch the exception; you almost certainly want to propagate it up to the caller
Don't log just the message - log the whole exception, including the stack trace and exception type.
The exception looks like it's trying to parse a string - not trying to convert an object to a string. I strongly suspect that the problem is one of these lines:
int q_box = Integer.parseInt(quantity_box_txtbox.getText());
int q_pc = Integer.parseInt(quantity_pc_txtbox.getText());
My guess is that one of the textboxes is empty - so you're effectively calling Integer.parseInt("") which is failing.

Related

Return result of Invoking a Delegate from another thread

I've got a GUI with a TabControl. Each new TabPage is created via a new Thread. I want to call this->tabControl->TabCount, but the tabControl is owned by a thread other than the one I'm calling from. Therefore, I need to Invoke a delegate. However, all the examples I find online show printing to std::cout from each of the delegate methods. I need a return value, in this case an int.
delegate int MyDel();
int InvokeTabCount()
{
if (this->InvokeRequired)
{
MyDel^ del = gcnew MyDel(this, &MyTabControl::InvokeTabCount);
auto temp = this->Invoke(del); // can't just "return this->Invoke(del)"
return temp; // Invoke() returns a System::Object^
}
else
{
return this->tabControl->TabCount;
}
}
void CreateNewTab()
{
// do stuff
this->tabControl->TabPages->Insert(InvokeTabCount() - 1, myNewTab); // insert a tab
this->tabControl->SelectTab(InvokeTabCount() - 2); // OutOfBounds and tabPageNew
}
System::Void MethodToAddNewTabPage() //actually a click event but whatever
{
System::Threading::Thread^ newThread =
gcnew System::Threading::Thread(
gcnew System::Threading::ThreadStart(this, &MyTabControl::CreateNewTab));
newThread->Start();
}
Currently, my InvokeTabCount() method is returning -1 when I simply this->Invoke(del) without returning it. And I am unable to return it because my method expects to return an int instead of a System::Object^ which is what Invoke() returns. However, when debugging I find that auto temp contains the value 2 which is correct. And temp->ToString() contains the value "2" which would also be correct.
How do I return this->Invoke(del)?
Do I need to set the value of a global variable from within my InvokeTabCount() method? I suppose I could find a way to translate from System::String^ to std::string to utilize std::stoi(), but that seems like an odd workaround.
Current solution:
delegate int MyDel();
int InvokeTabCount()
{
if (this->InvokeRequired)
{
MyDel^ del = gcnew MyDel(this, &MyTabControl::InvokeTabCount);
auto temp = this->Invoke(del);
return int::Parse(temp->ToString());
}
else
{
return this->tabControl->TabCount;
}
}
The result is an integer, boxed and contained in an Object^ reference. You should be able to simply cast it to int.
If you want to be extra safe, do a null check and verify that temp->GetType() returns int::typeid, but that's probably overkill since you're creating the delegate (still in the typed form) right there.

From C# after getting IBM MQ message how to identify message data type? Is it Object or String type?

In our company we are using IBM MQ server for message queueing. For the same queue we are putting both String and Object type data message with the help of methods WriteObject and WriteString.
The challenge is occured when it comes to consumption(read message) of queue. Since the Get data can be both Object or String we need to decide which method to use ReadString or ReadObject on the MQMessage instance. I made workaround like firstly using ReadObject method, if an exception occured then try it with ReadString.
I did not like this workaround, is there any way to identify message data type after calling MQQueue instance's Get method?
Here below you can find my workaround:
public object GetMessage(string queueName) {
MQQueueManager queueManager = new MQQueueManager("queueManagerName", "channel", "connection");
MQGetMessageOptions queueGetMessageOptions = new MQGetMessageOptions();
queueGetMessageOptions.Options = MQC.MQGMO_WAIT + MQC.MQGMO_FAIL_IF_QUIESCING + MQC.MQPMO_SYNCPOINT;
try {
queueRead = queueManager.AccessQueue(queueName, MQC.MQOO_INPUT_AS_Q_DEF + MQC.MQOO_FAIL_IF_QUIESCING);
queueMessage = new MQMessage();
queueMessage.Format = MQC.MQFMT_STRING;
queueRead.Get(queueMessage, queueGetMessageOptions);
try {
var readObject = queueMessage.ReadObject();
return readObject;
} catch (SerializationException) { } // if message in queue not a object
queueMessage.DataOffset = 0;
var stringMsg = queueMessage.ReadString(queueMessage.MessageLength);
return stringMsg;
} catch (MQException exp) {
if (exp.ReasonCode != 2033) {
log.ErrorFormat("MQException: ResonCode: {0}, {1}", exp.ReasonCode, exp.Message);
}
}
return "";
}
What a horrible design.
First off, why are you putting 2 different message types into the same queue? Bad, very bad idea. You should be using 2 different queues. What, does someone think queues are scarce or rare? You should be handing out queues like candy.
Secondly, if you really need to go with this design then you should read the MQ Knowledge Center on MQMD structure. It contains a field called 'Message Type'. Most applications use 'Message Type' to contain either 'MQMT_DATAGRAM' or 'MQMT_REQUEST' but you can set your own values starting with 'MQMT_APPL_FIRST'.
So, define a couple of constants:
public const int MY_MSG_OBJECT = MQC.MQMT_APPL_FIRST + 1;
public const int MY_MSG_STRING = MQC.MQMT_APPL_FIRST + 2;
Hence, the sending application putting a string message would do:
MQMessage sendmsg = new MQMessage();
sendmsg.Format = MQC.MQFMT_STRING;
sendmsg.MessageType = MY_MSG_STRING;
sendmsg.WriteString("This is a test message");
queue.Put(sendmsg, pmo);
and the sending application putting an object message would do:
MQMessage sendmsg = new MQMessage();
sendmsg.Format = MQC.MQFMT_NONE;
sendmsg.MessageType = MY_MSG_OBJECT;
sendmsg.WriteObject(someObject);
queue.Put(sendmsg, pmo);
The receiving application would do:
MQMessage rcvmsg = new MQMessage();
queue.Get(rcvmsg, gmo);
// Check the Message Type
if (rcvmsg.MessageType == MY_MSG_STRING)
{
readString = queue.ReadString();
}
else if (rcvmsg.MessageType == MY_MSG_OBJECT)
{
readObject = queue.ReadObject();
}
else
{
System.Console.Out.WriteLine("Error: Unknown message type.");
}

Why is the scanner not finding a line after the first iteration?

I'm writing a program that basically acts as an email client as a part of a homework assignment for a class in java. I don't normally resort to the internet to answer my questions, but this is something that goes beyond what the professor is trying to get us to learn/practice, and I need to find a way to fix it.
The Problem: If I run the program, and input the second command (ri), it will prompt me for the number, and then finish by displaying the message, but immediately after, when it goes back into the second iteration of the .run() method the console returns:
Exception in thread "main" java.util.NoSuchElementException: No Line Found
at java.util.scanner.nextLine(Unknown Source)
Here's the code (I'm only including the important stuff...or at least what I think is important).
public class CmdLoop {
private MailClient _client;
Scanner kbd;
private Hashtable<String, ICommand> _commands = new Hashtable<String, ICommand>();
public CmdLoop(MailClient client) {
_client = client;
_commands.put("h", new client.cmd.Help());
_commands.put("ri", new client.cmd.ReadInbox());
kbd = new Scanner(System.in);
}
public void run2() {
System.out.print("\nMail: ");
String command = kbd.nextLine();
ICommand call = _commands.get(command);
if (command.equals("q"))
return;
else if (call == null)
System.out.println(command + " not understood, type h for help");
else if (call.equals(""))
System.out.println(command + " not understood, type h for help");
else call.run(_client);
this.run2();
}
and the ri class:
public class ReadInbox implements ICommand {
#Override
public void run(MailClient client) {
Scanner sc = new Scanner(System.in);
MailBox in = client.getInbox();
if(in.count() < 1)
System.out.println("Inbox empty");
else {
System.out.print("Enter the number of the message you would like to read: ");
int n = Integer.parseInt(sc.nextLine());
if(n > in.count())
System.out.println("Message number " + n + " can't be found");
else
in.getMessage(n - 1).show();
}
sc.close();
}
}
Basically it gets to the end of the ReadInbox.run() call, then it calls this.run2(), returns to the top, outputs "Mail: " and then returns the error. This is what the console looks like in my test:
Mail: ri
Enter the number of the message you would like to read: 1
Date: 2015/04/29 20:24:17
From: Charles Barkley (Charlie) <Charles#gmail.com>
Subj: testerino
this is another test
Mail: Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Unknown Source)
at client.CmdLoop.run2(CmdLoop.java:28)
at client.CmdLoop.run2(CmdLoop.java:37)
at Main.main(Main.java:29)
If I'm correct, getting it so they both operate off the same scanner would solve my problem, and I feel like I should know how to do that, but I'm drawing a blank. Is there another way as well?
According to the documentation a Scanner will throw that exception "if no line was found". You can prevent that by first calling kbd.hasNextLine() which will tell you if there is something to get. That will wait for a line to be entered as long as the scanner is not closed.
Try this in your run2 method:
String command = null;
if (kbd.hasNextLine())
command = kbd.nextLine();
ICommand call = _commands.get(command);
I found the answer. I got rid of sc.close(); in the ReadInbox class. I have 0 clue why this works, but it does. If anyone has an explanation to offer, much appreciated, otherwise, whatever, at least it works.

Removing part of a String^ in MFC C++

So far I've only written console applications. My first application using MFC (in Visual Studio 2010) is basically a form with two multiline boxes (using String[] arrays noted with String^) and a button to activate text processing. It should search the String^ for a [, look for the ] behind it and delete all characters between them (including the []). With 'normal' C++ strings, this isn't difficult. String^ however is more like an object and MSDN tells me to make use of the Remove method. So, I tried to implement it.
public ref class Form1 : public System::Windows::Forms::Form
{
public:
Form1(void)
{
InitializeComponent();
//
//TODO: Add the constructor code here
//
}
String^ DestroyCoords(String^ phrase)
{
int CoordsStart = 0;
int CoordsEnd = 0;
int CharCount = 0;
for each (Char ch in phrase)
{
if (ch == '[')
CoordsStart = CharCount;
if (ch == ']')
{
CoordsEnd = CharCount;
//CoordsEnd = phrase->IndexOf(ch);
phrase->Remove( CoordsStart , CoordsEnd-CoordsStart );
}
CharCount++;
}
return phrase;
}
The button using the method:
private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e) {
TempString = String::Copy(BoxInput->Text);
DestroyCoords(TempString);
BoxOutput->Text = TempString;
The function seems to hit the correct places at the correct time, but the phrase->Remove() method is doing absolutely nothing..
I'm no OO hero (as said, I normally only build console applications), so it's probably a rookie mistake. What am I doing wrong?
In C++/CLI, System::String is immutable, so Remove creates a new String^. This means you'll need to assign the results:
phrase = phrase->Remove( CoordsStart , CoordsEnd-CoordsStart );
The same is true in your usage:
TempString = DestroyCoords(TempString);
BoxOutput->Text = TempString;
Note that this will still not work, as you'd need to iterate through your string in reverse (as the index will be wrong after the first removal).
No MFC here, that's the C++/CLI that Microsoft uses for writing .NET programs in C++.
The .NET System::String class is immutable, so any operations you expect to modify the string actually return a new string with the adjustment made.
A further problem is that you're trying to modify a container (the string) while iterating through it. Instead of using Remove, have a StringBuilder variable and copy across the parts of the string you want to keep. This means only a single copy and will be far faster than repeated calls to Remove each of which makes a copy. And it won't interfere with iteration.
Here's the right approach:
int BracketDepth = 0;
StringBuilder sb(phrase->Length); // using stack semantics
// preallocated to size of input string
for each (Char ch in phrase)
{
if (ch == '[') { // now we're handling nested brackets
++BracketDepth;
}
else if (ch == ']') { // and complaining if there are too many closing brackets
if (!BracketDepth--) throw gcnew Exception();
}
else if (!BracketDepth) { // keep what's not brackets or inside brackets
sb.Append(ch);
}
}
if (BracketDepth) throw gcnew Exception(); // not enough closing brackets
return sb.ToString();

BackgroundWorker, can't send other variable other than numeric values to the function callback

Background worker, passing variables are not working, in my example I explain everything, I put only the functions that were important, I have the other functions from the BackgroundWorker.
int TheFunction(unordered_map<std::string,std::string> options, BackgroundWorker^ worker, DoWorkEventArgs ^ e){
if(options["option1"].compare("options") == 0){
//...
}
return 0;
}
void backgroundWorker2_DoWork(Object^ sender, DoWorkEventArgs^ e ){
BackgroundWorker^ worker = dynamic_cast<BackgroundWorker^>(sender);
//e->Result = TheFunction( safe_cast<Int32>(e->Argument), worker, e ); //That's how I do to send an integer value and works just fine, but I don't know how to send non-numeric values with safe_cast or something that works, in the function it looks like this: TheFunction(int index, ...) it works fine, I want to know with unordered_map or with strings also would work, I want more than one argument if you can do with std::string
e->Result = TheFunction(safe_cast<unordered_map<std::string,std::string>>(e->Argument)); //I tried this, and it didn't work
}
void CallBackgroundWorker(){
this->backgroundWorker2 = gcnew System::ComponentModel::BackgroundWorker;
this->backgroundWorker2->WorkerReportsProgress = true;
this->backgroundWorker2->WorkerSupportsCancellation = true;
this->backgroundWorker2->DoWork += gcnew DoWorkEventHandler( this, &GUISystem::backgroundWorker2_DoWork );
this->backgroundWorker2->RunWorkerCompleted += gcnew RunWorkerCompletedEventHandler( this, &GUISystem::backgroundWorker2_RunWorkerCompleted );
this->backgroundWorker2->ProgressChanged += gcnew ProgressChangedEventHandler( this, &GUISystem::backgroundWorker2_ProgressChanged );
unordered_map<std::string,std::string>* options = unordered_map<std::string,std::string>();
options["option1"] = "valor1";
options["option2"] = "valor2";
this->backgroundWorker2->RunWorkerAsync(options);
}
So how do I do to send the unordered_map or a std::string (more than 1 arguments) ?
thanks in advance. that would help a lot.
This line:
unordered_map<std::string,std::string>* options = unordered_map<std::string,std::string>();
isn't legal even in standard C++. A pointer needs to store an address, not an object. So probably you meant to say new to use dynamic allocation (after all, the object needs to survive until the callback runs on the other thread).
At that point, you can wrap the pointer inside System::IntPtr, and in the callback, cast the result of ToPointer().

Resources