java8 - Optional- How to use it correctly? - java

The cityStr is a String, and it would be a null or "". I want to turn it to a int and if it's greater than 0, then I will print "the city is exist".
if (StringUtils.isNotBlank(cityStr)) {
if (Integer.parseInt(cityStr) > 0) {
System.out.println("the city is exist");
}
}
I want to used the below code to replace the above code, but I got a exception. How can I use it correctly? Thanks so much for your answer.
if (Optional.ofNullable(cityStr)
.map(Integer::parseInt)
.filter(city -> city > 0)
.isPresent()) {
System.out.println("the city is exist");
}
And the below is the exception information:
Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:592)
at java.lang.Integer.parseInt(Integer.java:615)
at java.util.Optional.map(Optional.java:215)

You are trying to parse a number from an empty String. That throws the exception. It has nothing to do with Optional.
Maybe you thought that an empty string would be 'nullish' - like an empty String being falsy in javascript.
To get rid of the exception, assign null or a number to cityStr.

You could write it as :
String cityStr = null;
if (Optional.ofNullable(cityStr)
.map(Integer::parseInt)
.filter(city -> city > 0)
.isPresent()) {
System.out.println("the city is exist");
}
If you are expecting non numeric string you've to handle that yourself in the map method.

As suggested by #fastcodejava I made minor changes to the program, please take a look below:
public static void main(String[] args) throws NoSuchAlgorithmException {
String cityStr = "1";
Optional<String> cityOptional = Optional.ofNullable(cityStr)
.map(MainClass::parseInt)
.filter(integer -> integer > 0)
.map(integer -> "city exists");
String cityString = cityOptional.orElse("city does not exists");
System.out.println(cityString);
}
public static int parseInt(String str) {
try {
return Integer.parseInt(str);
} catch (NumberFormatException e) {
// Eating e for unknown reason
return -1;
}
}
Where MainClass is the class for main method MainClass.java

Related

String data still remains? (Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string)

I am trying out to code a simple arithmetic game in Java but I faced an error like: Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string. This happens when I clicked on number buttons and cleared them to enter a new number but it seems that the string still contains the previous number I clicked. (For example, I clicked 5 and deleted it so I could enter 9 instead and now the string seems to register it as 59 instead of just 9.) I used .setText('') to clear the text area.
This is my code for when the buttons are pressed:
public void actionPerformed(ActionEvent e)
{
if(e.getActionCommand().equals("one"))
{
answerText.append("1");
userAnswer = userAnswer + "1";
}
// same code for two, three, four... to nine.
if(e.getActionCommand().equals("enter"))
{
int userValue = new Integer(userAnswer);
if (userValue == rightAnswer)
{
score++;
userAnswer = "";
generateRandomProblem();
}
else
{
JOptionPane.showMessageDialog(this,"Wrong answer! Please try again.");
}
}
}
The answer variable and delete button is :
answerText = new JTextArea();
answerText.setEditable(false);
clearbtn = new JButton("Clear");
clearbtn.setActionCommand("clear");
clearAnswer.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
answerText.setText("");
}
});
How do I make sure that my answerText is completely clear?
Your error message:
java.lang.NumberFormatException: For input string
This means that you are trying to parse a string into a number, but the string contains something that cannot be parsed into a number. Java prints the content of the string after the text For input string. In this case there's nothing after that text, because the string that you are trying to parse is the empty string - that you set in the text box by calling answerText.setText("");
Solution: Check if the string you are trying to parse is empty before you try to parse it into a number. For example:
if (e.getActionCommand().equals("enter"))
{
if (!"".equals(userAnswer)) // Check if userAnswer is not empty
{
int userValue = new Integer(userAnswer);
if (userValue == rightAnswer)
{
score++;
userAnswer = "";
generateRandomProblem();
}
else
{
JOptionPane.showMessageDialog(this,"Wrong answer! Please try again.");
}
}
else
{
JOptionPane.showMessageDialog(this, "Please enter a number before pressing Enter.");
}
}
The variable userAnswer doesn't get cleared when answerText is cleared. This might cause issues.
The exception you are having is probably being cause because int userValue = new Integer(userAnswer); is called at a point where userAnswer is empty (because it can't make a number out of nothing).

Creating a Search Button (Double cannot converted to String)

private void searchProduct()
{
try {
Product p = new Product();
//Read data
p.setId(Double.parseDouble(textID.getText()));
//Display data
textDescription.setText(String.valueOf(p.getDescription()));
textPrice.setText(String.valueOf(p.getUnitPrice()));
textUOM.setText(String.valueOf(p.getUnitOfMeasurement()));
}
catch(NumberFormatException e)
{
JOptionPane.showMessageDialog(this.frame, "ID must be number", "Error",JOptionPane.ERROR_MESSAGE);
}
}
Hello recently I tried to put a button "Search" to find a product than equals to ID, but I don't know how to parse the ID than comes from the product class, I have a error.
Does the textID.getText() actually is a parseable double string? For instance "10.1" do but "10.1 " no.
Always I did this kind of conversion I use trim() to remove this extra white spaces as follow:
String stringValue = textID.getText();
if(stringValue != null) {
stringValue = stringValue.trim();
}
double doubleValue = Double.parseDouble(stringValue);
Se here http://docs.oracle.com/javase/8/docs/api/java/lang/Double.html#valueOf-java.lang.String- how to avoid NumberFormatException using a regular expression to text you string before try to convert it to double.

How to get the row index of a csv file in java

My program is to validate if the input code number is empty or not. The condition is if there is a code number entered(thru csv file) proceed and if code number is empty an error message show. "The code number is empty in line :__".
My problem is how can I suppose to print the index of a line on which the code number was empty.
Here's my sample data(csv):
CRITERIA CODE NAME AGE ADDRESS
ADD 0001 JOHN 21 USA
ADD MICH 16 EUR
ADD ALI 11 PHL
Error Message should be :
"The code number is empty in line 2."
"The code number is empty in line 3."
Here's my current program :
private static String[] sNextLine2;
public static Map<String,Employee> getChanges
( String sFileName, Map<String, Employee> mEmployeeList )
throws IOException {
//Read_File
setReader2(new CSVReader(new FileReader(sFileName)));
while ((sNextLine2 = reader2.readNext()) != null) {
switch(sNextLine2[0]) {
case "ADD":
if(sNextLine2[1].isEmpty()) {
System.out.println("The code number is empty in line" + lineNumber); //how to get that line number
} else if (mEmployeeList.containsKey(sNextLine2[1]))
{
System.out.println("Data already exist");
}
else
{
mEmployeeList.put(sNextLine2[1],new Employee(sNextLine2[1],
sNextLine2[2], sNextLine2[3], sNextLine2[4], sNextLine2[5],
sNextLine2[6], sNextLine2[7], sNextLine2[8]));
}
break;
}
I hope someone will help me on this. Thank you!
you can add a counter, which is incremented every .readNext() and let it print if there is an error
int counter=0;
while ((sNextLine2 = reader2.readNext()) != null) {
counter++;
switch(sNextLine2[0]) {
case "ADD":
if(sNextLine2[1].isEmpty()) {
System.out.println("The code number is empty in line" + counter); //how to get that line number
} else if (mEmployeeList.containsKey(sNextLine2[1]))
{
System.out.println("Data already exist");
}
else
{
mEmployeeList.put(sNextLine2[1],new Employee(sNextLine2[1],
sNextLine2[2], sNextLine2[3], sNextLine2[4], sNextLine2[5],
sNextLine2[6], sNextLine2[7], sNextLine2[8]));
}
break;
}

How to get a specific value from a string name via config

The green is the lore
and the yellow is the displayname
http://puu.sh/k2iI7/62619f9536.jpg
I'm trying to seperate them in there rightful places for some odd reason there both appearing in both of the places.
items.java
public ItemStack applyLore(ItemStack stack, String name, String lore1){
ItemMeta meta = stack.getItemMeta();
meta.setDisplayName(name.replaceAll("&([0-9a-f])", "\u00A7$1"));
ArrayList<String> lore = new ArrayList<String>();
lore.add(lore1.replaceAll("&([0-9a-f])", "\u00A7$1"));
meta.setLore(lore);
stack.setItemMeta(meta);
return stack;
}
// p.getInventory().addItem(new ItemStack(Integer.parseInt(s), 1));
public void giveItemfromConfig(Player p)
{
String name ="name:";
String lore ="lore:";
for ( String s : plugin.file.getFile().getStringList(plugin.file.path) ) {
try {
s.split(" ");
if ( s.contains(name) || s.contains(lore) )
{
String namelength = s.substring(name.length());
String lorelength = s.substring(lore.length());
p.getInventory().addItem(applyLore(new ItemStack(Integer.parseInt(s.split(" ")[0])),
namelength.replace("_", " ").replace("ame:", "").replace("e:", "").replace("lor", "").replace("ore", ""),
lorelength.replace("_", " ").replace("lor:", "").replace("e:", "").replace("am", "").replace("lor", "").replace("ore", "")));
p.sendMessage("debug");
} else {
///nope.exe
p.getInventory().addItem(new ItemStack(Integer.parseInt(s)));
}
} catch(Exception e)
{
e.printStackTrace();
Bukkit.getConsoleSender().sendMessage(ChatColor.AQUA + "Error in Config, Your id must be a integer ERROR:" + e);
}
}
}
config.yml
ChestPopulater:
items:
- 276 name:cookie
First thing is the problem is because of "Integer.parseInt(s)".
I dont know why you added this one as we dont have full source code or idea what you are trying to do with String "s" so that you will get result.
If you are doing it to get "276" , I will suggest you to do following :
String s2 = s.replaceAll("[A-Za-z]","").replace(":","").trim();
Integer i = Integer.parseInt(s2);

junit testing - assertEquals for exception

How can I use assertEquals to see if the exception message is correct?
The test passes but I don't know if it hits the correct error or not.
The test I am running.
#Test
public void testTC3()
{
try {
assertEquals("Legal Values: Package Type must be P or R", Shipping.shippingCost('P', -5));
}
catch (Exception e) {
}
}
The method being tested.
public static int shippingCost(char packageType, int weight) throws Exception
{
String e1 = "Legal Values: Package Type must be P or R";
String e2 = "Legal Values: Weight < 0";
int cost = 0;
if((packageType != 'P')&&(packageType != 'R'))
{
throw new Exception(e1);
}
if(weight < 0)
{
throw new Exception(e2);
}
if(packageType == 'P')
{
cost += 10;
}
if(weight <= 25)
{
cost += 10;
}
else
{
cost += 25;
}
return cost;
}
}
Thanks for the help.
try {
assertEquals("Legal Values: Package Type must be P or R", Shipping.shippingCost('P', -5));
Assert.fail( "Should have thrown an exception" );
}
catch (Exception e) {
String expectedMessage = "this is the message I expect to get";
Assert.assertEquals( "Exception message must be correct", expectedMessage, e.getMessage() );
}
The assertEquals in your example would be comparing the return value of the method call to the expected value, which isn't what you want, and of course there isn't going to be a return value if the expected exception occurs. Move the assertEquals to the catch block:
#Test
public void testTC3()
{
try {
Shipping.shippingCost('P', -5);
fail(); // if we got here, no exception was thrown, which is bad
}
catch (Exception e) {
final String expected = "Legal Values: Package Type must be P or R";
assertEquals( expected, e.getMessage());
}
}
Works perfectly for me.
try{
assertEquals("text", driver.findElement(By.cssSelector("html element")).getText());
}catch(ComparisonFailure e){
System.err.println("assertequals fail");
}
if assertEquals fails ComparisonFailure will handle it
Java 8 solution
Here is a utility function that I wrote:
public final <T extends Throwable> T expectException( Class<T> exceptionClass, Runnable runnable )
{
try
{
runnable.run();
}
catch( Throwable throwable )
{
if( throwable instanceof AssertionError && throwable.getCause() != null )
throwable = throwable.getCause(); //allows "assert x != null : new IllegalArgumentException();"
assert exceptionClass.isInstance( throwable ) : throwable; //exception of the wrong kind was thrown.
assert throwable.getClass() == exceptionClass : throwable; //exception thrown was a subclass, but not the exact class, expected.
#SuppressWarnings( "unchecked" )
T result = (T)throwable;
return result;
}
assert false; //expected exception was not thrown.
return null; //to keep the compiler happy.
}
(taken from my blog)
Use it as follows:
#Test
public void testThrows()
{
RuntimeException e = expectException( RuntimeException.class, () ->
{
throw new RuntimeException( "fail!" );
} );
assert e.getMessage().equals( "fail!" );
}
Also, if you would like to read some reasons why you should not want to assertTrue that the message of your exception is equal to a particular value, see this: https://softwareengineering.stackexchange.com/a/278958/41811
This is nice library that allows asserting exceptions in a clean way.
Example:
// given: an empty list
List myList = new ArrayList();
// when: we try to get the first element of the list
when(myList).get(1);
// then: we expect an IndexOutOfBoundsException
then(caughtException())
.isInstanceOf(IndexOutOfBoundsException.class)
.hasMessage("Index: 1, Size: 0")
.hasNoCause();

Categories

Resources