vegapunk
vegapunk

Reputation: 23

Shorten code to 1 line

Ok so I had a problem asking to rewrite this code within 1 line of code within the main method:

public static void main(String[] args)
String s;
    boolean b;
    JOptionPane jop;

    jop = new JOptionPane();

    s = jop.showInputDialog("Enter your email address");
    b = s.matches(".*@.*\\..*");
    if (b)
    {
        System.out.println("Address Appears Valid");
    }
    else
    {
        System.out.println("Address is Invalid");
    }
}

And here is what I have done so far

public static void main( String[] args )
{

   String s = JOptionPane.showInputDialog("Enter your email address");

   System.out.println(s.matches(".*@.*\\..*") ? "Address Appears Valid" : "Address is Invalid" );
}

How can I shorten this code even further?? THanks

Upvotes: 0

Views: 233

Answers (4)

Kirill Gamazkov
Kirill Gamazkov

Reputation: 3397

Just remove all CR/LF characters from your source :)

Upvotes: 0

iluvthee07
iluvthee07

Reputation: 501

public static void main( String[] args )
{
   System.out.println(JOptionPane.showInputDialog("Enter your email address").matches(".*@.*\\..*") ? "Address Appears Valid" : "Address is Invalid" ));
}

Important point to note is that the input dialog box returns a string that you are only using once. So no need to store it instead use it just as it is returned.

Upvotes: 0

AndreaTaroni86
AndreaTaroni86

Reputation: 559

Don't create s, pur joption in the println instead

Upvotes: 0

Blue Ice
Blue Ice

Reputation: 7922

Make this:

String s = JOptionPane.showInputDialog("Enter your email address");

   System.out.println(s.matches(".*@.*\\..*") ? "Address Appears Valid" : "Address is Invalid" );

Into this:

System.out.println(JOptionPane.showInputDialog("Enter your email address").matches(".*@.*\\..*") ? "Address Appears Valid" : "Address is Invalid" );

After all, why store the value if you are just going to use it in the next line?

Upvotes: 3

Related Questions