not printing to textbox - java

I am trying to create a way of retrieving from a hashtable an authorID for the articleName that the user enters. Here is the code that is activated on the client's side when the user presses a button:
public String getAuthorID() // returns a String
{
try
{
articleName = txtArticleName.getText();
argAuthorID = new Vector();// create vector for the args
argAuthorID.addElement(articleName);// name to search for to get AuthorID
// make the call to the server
authorIDVector = (Integer)client.execute("GetSize.sendAuthorID", argAuthorID);
System.out.println(argAuthorID);
}
catch (XmlRpcException exception) {
System.err.println("JavaClient: XML-RPC Consumer Fault #" +
Integer.toString(exception.code) + ": " +
exception.getCause() + "" + exception.toString());
} catch (Exception exception) {
System.err.println("JavaClient: XML-RPC Consumer Fault #" + exception.toString());
}
String StrAuthorID = Integer.toString(authorID); // Cast AuthorID to String
return StrAuthorID;
}
This is the method on the server side:
public int sendAuthorID(String articleNameRequest) {
// get info from the hashtable
aNumber = (Integer) theHashtable.getAuthorID(articleNameRequest); // was this.
return aNumber;
}
This is the code in the class that contains the hashtable:
public int getAuthorID(String articleName)
{
int intfoundit;
String foundit = (String)hashtab.get(articleName);
System.out.print(foundit);
intfoundit = Integer.parseInt(foundit);
System.out.print(foundit);
System.out.print(intfoundit);
return intfoundit;
}
The program can retrieve the AuthorID but won't input it into the textbox. Via testing I discovered that the exception was thrown by this code:
catch (XmlRpcException exception) {
System.err.println("JavaClient: XML-RPC Consumer Fault #" +
Integer.toString(exception.code) + ": " +
exception.getCause() + "" + exception.toString());
This is the error that is given:
'JavaClient: XML-RPC Consumer Fault #0:
nullorg.apache.xmlrpc.XmlRpcException: java.lang.Exception:
java.lang.NumberFormatException: For input string: " 3377"'
UPDATE: removed the space before the ID number in the hashtable and it doesn't throw an error anymore but it still isn't inputting the ID number into the textbox instead it just inputs a '0'

It seems to be failing in cases when you have spaces in your string. As we can see in your exception trace that parseInt failed to parse " 3377" and it threw NumberFormatException while executing:
intfoundit = Integer.parseInt(foundit);
So you may try to trim the string and see whether it solves your problem:
intfoundit = Integer.parseInt(foundit.trim());
Better you should do the trim where you are saving/putting the key/value in the hashtable.

The answer to the first problem was space before ID number on the hashtable because the space couldn't be converted to an Integer.
The answer to the second problem was that the following line was trying to convert the wrong variable
String StrAuthorID = Integer.toString(authorID); // Cast AuthorID to String
because the Integer was in the AuthorID variable
I corrected this by changing
authorIDVector = (Integer)client.execute("GetSize.sendAuthorID", argAuthorID);
to
authorID = (Integer)client.execute("GetSize.sendAuthorID", argAuthorID);

Related

How do I print out information with CSV spreadsheet?

I'm currently working on a project with CSV. In the task, I am supposed to type a country name in the tester method, and when I call the tester method, it will print the information of the country. For example, "Germany Chemical 32000." However, no matter what country name I put(I'm sure that country exists in the spreadsheet), it always prints out "NOT FOUND," which I don't understand how. I'm guessing the problem is in the if statement of the countryInfo method. However, I can't find the problem probably due to a lack of domain knowledge, so I hope someone can inform me or give me a hint.
public void tester(){
FileResource fr = new FileResource();
CSVParser parser = fr.getCSVParser();
String GermanyInfo = countryInfo(parser,"Peru");
System.out.println(GermanyInfo);
}
public String countryInfo(CSVParser parser, String country){
String countryInfo = " ";
for (CSVRecord record : parser){
String nation = record.get("Country");
if (nation.contains(country)){
String countryExport = record.get("Exports");
String exportValue = record.get("Value (dollars)");
countryInfo = country + ": " + countryExport + " " + exportValue;
}else{
countryInfo = "NOT FOUND";
}
}
return countryInfo;
}
Debug Process:
Hey guys, after more testing and trying, I found out the problem is really part of the if statement. My for-each loop is running through the parser, one row at a time. The way I have this written, my if statement is checking to see whether that row contains any matching country name in the Country column, but once it finds it, it just keeps going and doesn't stop because I haven't told it to do so. It would find Germany but then move on to the next rows and bypass it until the end of the file, where it will return "not found." In order for me to fix this, I need to have a return statement following the exportValues = record.get line instead of the end of my method, OR simply type in a line that says "break;" after the money line, which will end the loop and then go to the return statement at the bottom.
If you're sure that the country search in your loop works fine, just add the return statement in the right place. I would suggest to change your method like this:
public String countryInfo(CSVParser parser, String country) {
for (CSVRecord record : parser) {
String nation = record.get("Country");
if (nation.contains(country)) {
String countryExport = record.get("Exports");
String exportValue = record.get("Value (dollars)");
return country + ": " + countryExport + " " + exportValue;
}
}
return "NOT FOUND";
}
In this case - as soon as the country is found - the method will return information about it. If no country is found - the method will return String "NOT FOUND"

How to catch an NSRangeException with do...catch?

I am translating this Java code to swift:
for (int i = 0 ; i < groups.length ; i++) {
try {
groups[i] = integerPart.substring (i * 3, i * 3 + 3);
} catch (IndexOutOfBoundsException ex) {
groups[i] = integerPart.substring (i * 3);
}
groups[i] = new StringBuilder (groups[i]).reverse ().toString ();
groups[i] = get1To3DigitString (groups[i]) + " " + getTheWord (i) + " ";
}
Note:
integerPart is a string.
groups is a string array.
please ignore get1To3DigitString and getTheWord.
My thoughts and tries:
Since swift's string is really annoying (can't be indexed with Int), I decided to use NSString's substringFromIndex and substringWithRange methods to do the substring Java method. So I wrote these 2 methods to help me:
func substring (s: String, start: Int, end: Int) throws -> String{
let ns = NSString(string: s)
return String(ns.substringWithRange(NSRange(start..<end)))
}
func substring (s: String, start: Int) -> String {
let ns = NSString(string: s)
return String(ns.substringFromIndex(start))
}
And I know that the two substring methods from NSString throws an NSRangeException, just like Java's IndexOutOfBoundsException. So here's my swift code:
for var i = 0 ; i < groups.count ; i++ {
do {
try groups[i] = substring(integerPart, start: i * 3, end: i * 3 + 3)
} catch NSRangeException {
groups[i] = substring(integerPart, start: i * 3)
}
groups[i] = String (groups[i].characters.reverse())
groups[i] = get1To3DigitString (groups[i]) + " " + getTheWord (i) + " "
}
And I get an error saying the catch pattern does not match ErrorType! I thought it does match ErrorType, because if it doesn't, how am I supposed to catch the exception? So I deleted the word NSRangeException.
I thought if an exception is thrown in substring, I would catch it in the catch part. But when I tested it, an exception occurred on the try line! I think this is because I wrote the catch pattern incorrectly.
How should I catch NSRangeException?
Just like in Java you never ever ever catch a IndexOutOfBoundsException you never ever ever catch a NSRangeException in Swift or Objective-C.
Those exceptions are caused because you as the developer screwed up, not the application or some outside factor, or the user with his input. In Java you have the term checked exceptions and unchecked exceptions. The first one you can and should or even have to catch, the second ones occur at runtime and signal mostly bugs in the program.
You simply must not substring a String of length 5 until its tenth char - that is something you as the developer could and have to know and be aware of. If you do this, the program should crash.
I am not sure if you actually can catch a NSRangeException - I would be very happy if you cannot do it. For regular Errors you define custom errors types:
enum LevelParsingException : ErrorType {
case MalformedJson
case InvalidLevelContent
}
Then you have some function which might throw them:
func parseLevel() throws {
guard someCondition {
throw LevelParsingException.InvalidLevelContent
}
}
And then you call that method and catch all the different errors that you know might arise:
func call() {
do {
try parseLevel()
} catch LevelParsingException.InvalidLevelContent {
print("something")
} catch {
print("something else")
}
}
The apple docs explain that all relatively well.

unexpected behavior in java exception flow

I have written following code snippet:-
public Collection<?> constructResponse (...........) throws RemoteException {
while (keyIterator.hasNext())
{
String keyValue = (String) keyIterator.next();
keyString = new StringBuilder(); // since multiple keys will be there in map need to ensure every time keyString and valueString is created
valueString = new StringBuilder();
keyString.append(keyValue + ";" + "name");
List<CustomValuePOJO> customPOJOlist = employeeValuesMap.get(keyValue );
for (CustomValuePOJO customPOJO : customPOJOlist )
{
if (protocol == null || protocol.equals(""))
{
valueString.append(rpNatPOJO.getDcnPort() + ":"+ rpNatPOJO.getProtocol() + ";");
}
else if (customPOJO .getProtocol().equals(protocol))
{
valueString.append(customPOJO .getPort() + ":"+ protocol + ";");
}
else
{ throw new RemoteException("Invalid Argument: Unsupported protocol "+ protocol);
}
}
if (valueString.length() == 0)
{
return generateErrorResponse("No info found");
}
responseMap.put(keyString.toString(), valueString.toString());
}
}
The weird behavior which is happening is that while iterating through the customPOJO its coming inside elseIf and also setting the value in valueString by executing below code:
else if (customPOJO .getProtocol().equals(protocol))
{
valueString.append(customPOJO .getPort() + ":"+ protocol + ";");
}
After this elseif its coming directly on line
throw new RemoteException("Invalid Argument: Unsupported protocol "+ protocol);
There is no error which is coming in append operation and checked in debug perspective the value is getting appended successfully in valueString.
Please tell what i am missing
Figure I should put this as an answer instead of just a comment...
This sort of behavior can occur when your code (what you are stepping through in the debugger) is out of sync with the compiled class files (that are actually running). Since debug information is associated with line numbers, the lines may be different in the class files than in the source code you see.
Try running a clean build and make sure that there are no duplicate jars on your classpath that may be causing this.

Custom exception message using JUnit assertEquals?

I'm using assert equals to compare two numbers
Assert.assertEquals("My error message", First , Second);
Then, when I generate the Test Report I get
"My error message expected (First) was (Second)"
How can I customize the part I've put in italic? And the format of the numbers?
You can use something like this:
int a=1, b=2;
String str = "Failure: I was expecting %d to be equal to %d";
assertTrue(String.format(str, a, b), a == b);
The message is hard-coded in the Assert class. You will have to write your own code to produce a custom message:
if (!first.equals(second)) {
throw new AssertionFailedError(
String.format("bespoke message here", first, second));
}
(Note: the above is a rough example - you'll want to check for nulls etc. See the code of Assert.java to see how it's done).
Thanks to your answer I've found in the Assert class this
static String format(String message, Object expected, Object actual) {
String formatted= "";
if (message != null && !message.equals(""))
formatted= message + " ";
String expectedString= String.valueOf(expected);
String actualString= String.valueOf(actual);
if (expectedString.equals(actualString))
return formatted + "expected: "
+ formatClassAndValue(expected, expectedString)
+ " but was: " + formatClassAndValue(actual, actualString);
else
return formatted + "expected:<" + expectedString + "> but was:<"
+ actualString + ">";
}
I guess I can't modify Junit Assert class, but I can create a new class in my project with the same name, just changing format, am I right? Or I can just change format in my class and it will affect the Exception thrown?

Java: 2 runtime errors I can't figure out

I am working on a homework assignment, and I am going a little "above and beyond" what is called for by the assignment. I am getting a run-time error in my code, and can not for the life of me figure out what it is that I have done wrong.
Here is the assignment:
Write a program that displays a simulated paycheck. The program should ask the user to enter the date, the payee’s name, and the amount of the check. It should then display a simulated check with the dollar amount spelled out.
Here is my code:
CheckWriter:
/* CheckWriter.java */
// Imported Dependencies
import java.util.InputMismatchException;
import java.util.Scanner;
public class CheckWriter {
public static void main(String args[]) {
Scanner keyboard = new Scanner(System.in);
// Try to get the name
String name = "";
NameValidator validateName = new NameValidator();
while (validateName.validate(name) == false) {
System.out.println("Enter the name: ");
name = keyboard.nextLine();
if (validateName.validate(name) == false) {
System.out.println("Not a valid name.");
}
}
// Get the date
String date = "";
DateValidator validateDate = new DateValidator();
while (!validateDate.validate(date)) {
System.out.println("Enter the date (dd/mm/yyyy): ");
date = keyboard.nextLine();
if (!validateDate.validate(date)) {
System.out.println("Not a valid date.");
}
}
// Try to get the amount of the check
String checkAmount = "";
CurrencyValidator validateCurrency = new CurrencyValidator();
while (!validateCurrency.validate(checkAmount)) {
System.out.print("Enter the Check Amount (XX.XX): $");
checkAmount = keyboard.nextLine();
if (!validateCurrency.validate(checkAmount)) {
System.out.println("Not a valid check amount.");
}
}
String checkWords = checkToWords(checkAmount); // ERROR! (48)
System.out
.println("------------------------------------------------------\n"
+ "Date: "
+ date
+ "\n"
+ "Pay to the Order of: "
+ name
+ " $"
+ checkAmount
+ "\n"
+ checkWords
+ "\n"
+ "------------------------------------------------------\n");
}
private static String checkToWords(String checkAmount) {
/**
* Here I will use the string.split() method to separate out
* the integer and decimal portions of the checkAmount.
*/
String delimiter = "\\.\\$";
/* Remove any commas from checkAmount */
checkAmount.replace(",", "");
/* Split the checkAmount string into an array */
String[] splitAmount = checkAmount.split(delimiter);
/* Convert the integer portion of checkAmount to words */
NumberToWords intToWord = new NumberToWords();
long intPortion = Long.parseLong(splitAmount[0]); // ERROR! (84)
intToWord.convert(intPortion);
String intAmount = intToWord.getString() + " dollars";
/* Convert the decimal portion of checkAmount to words */
String decAmount = "";
long decPortion = Long.parseLong(splitAmount[1]);
if (decPortion != 0) {
NumberToWords decToWord = new NumberToWords();
decToWord.convert(Long.parseLong(splitAmount[1]));
decAmount = " and " + decToWord.getString() + " cents.";
}
return (intAmount + decAmount);
}
}
Note that I am using external class files to handle validation of the name, date, currency, and conversion from numbers to words. These class files all work as intended.
The error I am getting is:
Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Long.parseLong(Unknown Source)
at java.lang.Long.parseLong(Unknown Source)
at CheckWriter.checkToWords(CheckWriter.java:82)
at CheckWriter.main(CheckWriter.java:46)
I have commented the lines in my code that are causing the errors that I am experiencing.
Could someone please assist me in figuring where my code is going wrong? I can include the other class files if you feel that it would be needed.
EDIT: When I run the code, it asks for the name and date. Before asking for the check amount is when it throws the error.
EDIT 2: A huge thank you to cotton.m! Thanks to his advice, I have changed the while statements to look like this:
while(!validateDate.validate(date) && date == "")
This has now fixed my issue. It would appear that when validating data with a regex expression, an empty string will return true.
The String you are trying to parse in an empty length string.
My suggestion would be to
1) Check the value of checkAmount at the start of checkToWords - if it is blank there's your problem
2) Don't do that split. Just replace the $ like you did the , (I think this is your real problem)
Also you are going to have another issue in that 10000.00 is not a long. I see you are splitting out the . but is that really what you want?
It is NumberFormatException, the value in checkAmount (method parameter) is not a valid Number.
You need to set checkAmount=checkAmount.replace(",", "");
Otherwise checkAmount will still have , inside and causes NumberFormatExcpetion.
Your issue is with your delimiter regex, currently you are using \.\$ which will split on a literal . followed by a literal $. I'm assuming that what you are actually intending to do is to split on either a . or a $, so change your delimiter to one of the following:
String delimiter = "\\.|\\$"
or
String delimiter = "[\\.\\$]"
As your code is now, checkAmount.split(delimiter) is not actually successfully splitting the string anywhere, so Long.parseLong(splitAmount[0]) is equivalent to Long.parseLong(checkAmount).
It should be:
String delimiter = "[\\.\\$]";
and then you have to check that splitWord[i] is not empty.

Categories