Reputation: 53
I have been tasked to check the format of a string, it must be a floating point number, semicolon then string. How would I ensure this? I am reading a file and adding each line to an arrayList, if it is of the correct format, if not it throws up an exception.
if (s.hasNextLine())
//if of specific format then ...
items.add(s.nextLine());
//throw ("file of wrong format")
Upvotes: 1
Views: 216
Reputation: 841
You can do something like this, make a method and pass each String line to this method and if this method returns true then add the line to your list.
public static boolean isMatched(String input) {
return input.matches("[+-]?[0-9]+(\\.[0-9]+)?([Ee][+-]?[0-9]+)?;.*");
}
Upvotes: 0
Reputation: 1010
We can have two solutions here. Either using Regex to check the format of the input string, Or parsing it and catching the exception if there is any.
Here are code examples showing both cases.
String correctInput = "123.0;HelloWorld";
String incorrectInput = "this is an incorrect format";
String regex = "[+-]?([0-9]*[.])?[0-9]+;([a-z]|[A-Z])*";
System.out.println(correctInput.matches(regex));
System.out.println(incorrectInput.matches(regex));
The output here will be :
true
false
The matches()
method returns a boolean, true if your regex matches, false if not.
PS : the regex above checks of the second part of the input has only letters on it.
try {
String[] inputString = "-123;helloWorld".split(";", 2);
if(inputString.length != 2) {
throw new IllegalArgumentException("the input contains more than two parts");
}
Float.parseFloat(inputString[0]);
String.valueOf(inputString[1]);
}catch(Exception e) {
//do your exception handling here.
e.printStackTrace();
}
Here the code checks if your input has two parts then checks the float and string format of each part.
Upvotes: 0
Reputation: 1579
First, I would try to split
the string by ';'. If that returns an array with a length greater than 1, you know that it has a semicolon in the center.
Then check if the first elment of the arary is a float (for example by checking if Float.parseFloat(...)
throws an exception). If that doesn't fail, you know the string is formatted properly.
This is what that would look like in code:
public static boolean check(String input) {
String[] split = input.split(";");
if (split.length == 1)
return false;
try {
Double.parseDouble(split[0]);
return true;
} catch (NumberFormatException e) {
return false;
}
}
To put that in your code snippet:
if (s.hasNextLine()) {
String next = s.nextLine();
if (check(next))
items.add(next);
else
throw new Exception("Input string(" + next + ") of wrong format.");
}
Upvotes: 1