Finding Correct exception to catch - java

Which exception can i use to check if the input has the right number of "/"
The input should be like DD/MM/YYYY
try{
String str = text.getText();
StringTokenizer st = new StringTokenizer(str);
String DD = st.nextToken("/");
String MM = st.nextToken("/");
String YYYY = st.nextToken();
}
catch( ???){
}

You will find it in the javadoc of nextToken.
It says it will throw a NoSuchElementException when there is no more token.
That said you should better not use the try/catch but test it using the hasMoreTokens method.

You can use Custom Exception for this but for that you need to declare method which validate your date (No of slashes).
Try Like this
public class Demo
{
public static void main (String[] args) {
try {
new MyClass().metToValidate("01/12/2014");
} catch (A e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class A extends Exception{}
class MyClass{
public void metToValidate(String dateText) throws A{
if( dateText.charAt(2) == '/'&& dateText.charAt(5) == '/' )
System.out.println("DATE IS OK");
else
throw new A();
}
}

The exception throws by nextToken is NoSuchElementException.

String str = "12/21223";
int counter = 0;
for( int i=0; i<str.length(); i++ ) {
if( str.charAt(i) == '/' ) {
counter++;
}
}
if(counter == 3){
StringTokenizer st = new StringTokenizer(str);
String DD = st.nextToken("/");
String MM = st.nextToken("/");
String YYYY = st.nextToken();
System.out.println(str);
}else{
System.out.println("Exception");
}

Related

Java error not a statement

When I try to compile my code I get the message
Main.java:31: error: not a statement
String bed = f.split(" ")
and also
error: ';' expected
String bed = f.split(" ");
I don't understand what's going on. I need to assign part of a file to a string.
Here's the code :
import java.util.Scanner;
import java.io.*;
public class Main{
public static void main(String[] args){
if ( args[0] == null){
System.out.println("File not Found");
return;
}
try {
File driver = new File (args[0]);
Scanner j = new Scanner( driver );
int i = 0;
while( j.hasNextLine()) {
String f = j.nextLine();
if (f.isEmpty() || f.startsWith("/")){ //If the String f is empty or has / it will continue reading the nextline after the / or space
continue;
if (f.startsWith("d")) {
String d = f.split(" ");
}
if (f.startsWith("b")) {
String b = f.split(" ");
}
if (f.startsWith("bed"))
String bed = f.split(" ");
}
System.out.println(f);
}
}
catch(FileNotFoundException e) {
System.out.println(e.getMessage());
}
catch (Exception ex) {
System.out.println(ex.getMessage);
}
}
}
.split() method returns an array so you should store it in an array, not in a string. Your code should be string b[]=f.split(" ") rather than storing it in string b
The split method returns splits the string based on the regex and returns an String array.
What you have here is String d = f.split(" ");, here you are trying to assign a string array to a string, and that is wrong.
It should instead say String[] d = f.split(" ");
I had this error.
I found a solution like below.
Error code
String a = "I goto the school";
String [] b = a.split("\\\s"); // error not a statement
Run code
try
{
String a = "I goto the school";
String [] b = a.split("\\\s");
}
catch(exception e)
{
}

print out from switch statement java

here is a piece of code:
class Main {
public static void main(String[] args) {
try {
CLI.parse (args, new String[0]);
InputStream inputStream = args.length == 0 ?
System.in : new java.io.FileInputStream(CLI.infile);
ANTLRInputStream antlrIOS = new ANTLRInputStream(inputStream);
if (CLI.target == CLI.SCAN || CLI.target == CLI.DEFAULT)
{
DecafScanner lexer = new DecafScanner(antlrIOS);
Token token;
boolean done = false;
while (!done)
{
try
{
for (token=lexer.nextToken();
token.getType()!=Token.EOF; token=lexer.nextToken())
{
String type = "";
String text = token.getText();
switch (token.getType())
{
case DecafScanner.ID:
type = " CHARLITERAL";
break;
}
System.out.println (token.getLine() + type + " " + text);
}
done = true;
} catch(Exception e) {
// print the error:
System.out.println(CLI.infile+" "+e);
}
}
}
else if (CLI.target == CLI.PARSE)
{
DecafScanner lexer = new DecafScanner(antlrIOS);
CommonTokenStream tokens = new CommonTokenStream(lexer);
DecafParser parser = new DecafParser (tokens);
parser.program();
}
} catch(Exception e) {
// print the error:
System.out.println(CLI.infile+" "+e);
}
}
}
It prints out as it is but somehow it does not print the type out only the default value of it which is an empty string. How can I make it to print out from the switch statement?
Thanks!
Try debugging.
Try printing the value from within the switch section, to see if you ever get into it.
Try replacing the switch with a simple "==" to see if you ever get "token.getType() == DecafScanner.ID"
General suggestion - move the definition of "type" and "next" outside the loop to avoid recreating them again and again.

Convert String to a String having a date format

I want to write a java method that takes a string in input and outputs another string following this rule:
input output
"123456" "12:34:56"
"23456" "02:34:56"
"3456" "00:34:56"
"456" "00:04:56"
"6" "00:00:06"
Any help would be appreciated. Thanks.
I would advice to use DateFormat as below. This will take care of all the burdens of conversion.
DateFormat formatFrom = new SimpleDateFormat("HHmmss");
DateFormat formatTo = new SimpleDateFormat("HH:mm:ss");
String origTimeString = "456";
String newDateString = null;
try {
String formattedString =
String.format("%06d", Integer.parseInt(origTimeString));
Date date = formatFrom.parse(formattedString);
newDateString = formatTo.format(date);
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println("Updated string : " + newDateString);
Copy this method and use it.
1) If string length is more than 6, it's going to return "ERROR".
2) First fixes the String with '0'
3) Second fixes the String with ':'
4) StringBuilder is used for concat. Avoid using '+' operator for concat.
5) Method 'getDate' is static because of 'main' method is static, too.
public static String getDate(String variable){
StringBuilder aux= new StringBuilder();
StringBuilder string= new StringBuilder();
int length = variable.length();
if(length>6 || length<=0){
return "ERROR";
}else{
//first to fill blanks with 0
for(int i=0;i<6-length;i++){
aux.append("0");
}
variable = aux.append(variable).toString();
//second to put :
for(int i=0;i<6;i++){
if(i%2==0 && i!=0){
string.append(":");
}
string.append(variable.charAt(i));
}
return string.toString();
}
}
public static void main(String[] args) {
System.out.print(getDate("464"));
}

Split, trim and assign array elements in Java

I am splitting the XML elements using String.split() method. The format of the XML elements are mentioned below:
start:23 | stop:43 | name:abc def
After splitting the strings, I'm trying to trim and assign like the following:
String[] parts = oneLine.split("\\s*\\|\\s*"); // splits into 3 strings
for (int x = 0; x < parts.length; x++) {
String tmp = parts[0];
if (tmp.startsWith("start:")) {
tmp = tmp.substring("start:".length());
try {
this.begin = Integer.parseInt(tmp);
}
catch (NumberFormatException nfe) {
nfe.printStackTrace();
}
}
else {
System.err.println("Wrong format");
}
String tmp1 = parts[1];
if ( tmp1.startsWith("stop:")) {
tmp1 = tmp1.substring("stop:".length());
try {
this.end = Integer.parseInt(tmp1);
}
catch ( NumberFormatException nfe ) {
nfe.printStackTrace();
}
}
else {
System.err.println("Wrong format"+tmp1);
}
Strint tmp2 = parts[2];
if ( tmp2.startsWith("name:")) {
tmp2 = tmp2.substring("name:".length());
try {
this.name = tmp2;
}
catch ( NumberFormatException nfe ) {
nfe.printStackTrace();
}
}
else {
System.err.println("Wrong format"+tmp2);
}
This returns an error Wrong format. Is this the problem with assignments String tmp1 = parts[0]?
Answer to my question.
String[] parts= oneLine.split("\\s*\\|\\s*");
//System.out.println(parts[0]);
String tmp=parts[0].substring("start:".length());
this.begin=Integer.parseInt(tmp);
String tmp1=parts[1].substring("stop:".length());
this.end=Integer.parseInt(tmp1);
String tmp2=parts[2].substring("name:".length());
this.uri=tmp2;
Above code snippet solves my problem

How do I validate a timestamp?

my application takes in a string like this "2002-10-15 10:55:01.000000". I need to validate that the string is a valid for a db2 timestamp.
How can I do this?
EDIT: This mostly works
public static boolean isTimeStampValid(String inputString) {
SimpleDateFormat format = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSS");
try {
format.parse(inputString);
return true;
} catch (ParseException e) {
return false;
}
}
The problem is that if I pass it a bad format for milliseconds like "2011-05-02 10:10:01.0av" this will pass validation. I am assuming that since the first millisecond character is valid then it just truncates the rest of the string.
I'm not exactly sure about the format but you you can play around it and can try something like this
public static bool isTimeStampValid(String inputString)
{
SimpleDateFormat format = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSS");
try{
format.parse(inputString);
return true;
}
catch(ParseException e)
{
return false;
}
}
EDIT: if you want to validate for numbers after successful parsing, you could do
format.parse(inputString);
Pattern p = Pattern.compile("^\\d{4}[-]?\\d{1,2}[-]?\\d{1,2} \\d{1,2}:\\d{1,2}:\\d{1,2}[.]?\\d{1,6}$");
return p.matcher(inputString).matches();
instead of
format.parse(inputString);
return true;
http://download.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html
I believe the format would be "yyyy-MM-dd HH:mm:ss.SSSSSS"
Call parse(String) and catch ParseException indicating it is invalid.
/**
* This method validates the given time stamp in String format
* #param timestamp
* #return
*/
public static boolean isTimeStampValid(String timestamp) {
//(Considering that formal will be yyyy-MM-dd HH:mm:ss.SSSSSS )
//Tokenize string and separate date and time
boolean time = false;
try {
//Tokenize string and separate date and time
StringTokenizer st = new StringTokenizer(timestamp, " ");
if (st.countTokens() != 2) {
return false;
}
String[] dateAndTime = new String[2];
int i = 0;
while (st.hasMoreTokens()) {
dateAndTime[i] = st.nextToken();
i++;
}
String timeToken = dateAndTime[1];
StringTokenizer timeTokens = new StringTokenizer(timeToken, ":");
if (timeTokens.countTokens() != 3) {
return false;
}
String[] timeAt = new String[4];
int j = 0;
while (timeTokens.hasMoreTokens()) {
timeAt[j] = timeTokens.nextToken();
j++;
}
try {
int HH = Integer.valueOf(timeAt[0].toString());
int mm = Integer.valueOf(timeAt[1].toString());
float ss = Float.valueOf(timeAt[2].toString());
if (HH < 60 && HH >= 0 && mm < 60 && mm >= 0 && ss < 60 && ss >= 0) {
time = true;
} else {
}
} catch (Exception e) {
e.printStackTrace();
}
//Got Date
String dateToken = dateAndTime[0];//st.nextToken();
//Tokenize separated date and separate year-month-day
StringTokenizer dateTokens = new StringTokenizer(dateToken, "-");
if (dateTokens.countTokens() != 3) {
return false;
}
String[] tokenAt = new String[3];
//This will give token string array with year month and day value.
int k = 0;
while (dateTokens.hasMoreTokens()) {
tokenAt[k] = dateTokens.nextToken();
k++;
}
//Now try to create new date with got value of date
int dayInt = Integer.parseInt(tokenAt[2]);
int monthInt = Integer.parseInt(tokenAt[1]);
int yearInt = Integer.parseInt(tokenAt[0]);
Calendar cal = new GregorianCalendar();
cal.setLenient(false);
cal.set(yearInt, monthInt - 1, dayInt);
cal.getTime();//If not able to create date it will throw error
} catch (Exception e) {
e.printStackTrace();
return false;
}
//Here we ll check for correct format is provided else it ll return false
try {
Pattern p = Pattern.compile("^\\d{4}[-]?\\d{1,2}[-]?\\d{1,2} \\d{1,2}:\\d{1,2}:\\d{1,2}[.]?\\d{1,6}$");
if (p.matcher(timestamp).matches()) {
} else {
return false;
}
} catch (Exception e) {
e.printStackTrace();
return false;
}
//Cross checking with simple date format to get correct time stamp only
SimpleDateFormat format = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSS");
try {
format.parse(timestamp);
//return true;
if (time) {
return true;
} else {
return false;
}
} catch (ParseException e) {
e.printStackTrace();
return false;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
If you're already connected to the database, you can execute a query that attempts to cast the input string as a timestamp, and check for a failure message (in this case, SQLSTATE 22007).
VALUES CAST( ? AS TIMESTAMP )
The above query will fully validate the input string while consuming hardly any resources on the database server. If the string is invalid for any reason, your database client will encounter an exception.

Categories