Wednesday, 14 April 2021

Write a java program to sort books in ascending order based on their title using Comparator

 import java.util.*;

class Book

{

int id;

String title;

Book(int id, String title)

{

this.id=id;

this.title=title;

}

public String toString()

{

return id+" "+title;

}

}

public class BookDemo

{

public static void main(String args[])

{

List<Book> ar= new ArrayList<Book>();

        ar.add(new Book(1,"java"));

ar.add(new Book(2,"C"));

Comparator<Book> com = new Comparator<Book>()

{

public int compare(Book ob1, Book ob2)

{

if(ob1.title.compareTo(ob2.title)>0)

return 1;

else

return -1;

}

};

Collections.sort(ar,com);

for(Book b:ar)

System.out.println(b);

}

}

==========================================================
import java.util.*;
class Book implements Comparable<Book>
{
int id;
String title;
Book(int id, String title)
{
this.id=id;
this.title=title;
}
public String toString()
{
return id+" "+title;
}
public int compareTo(Book ob2)
{
if(this.title.compareTo(ob2.title)>0)
return 1;
else
return -1;
}
}
public class BookDemo
{
public static void main(String args[])
{
List<Book> ar= new ArrayList<Book>();
        ar.add(new Book(1,"java"));
ar.add(new Book(2,"C"));
Collections.sort(ar);
for(Book b:ar)
System.out.println(b);
}
}

Sunday, 4 April 2021

Password Validation using regular expressions and matches() in Java

 Some websites impose certain rules for passwords. Suppose the password rules are as

follows: ¦ A password must have at least eight characters. ¦ A password consists of only letters and digits. Write main () method that prompts the user to enter a password and a static method isValidPassword() that expects a string argument and returns boolean type after validating the password.


Solution:

package p1;


import java.util.Scanner;

class Password

{

String pass;


static boolean isValidPassword(String p)

{

if((p.length()>=8) &&p.matches("[a-zA-Z0-9]*"))

{

return true;

}   

else

{ return false; }

}

}

public class Passwordrule

{

public static void main(String[] args) 

{

String pas;

      Scanner s=new Scanner(System.in);

System.out.println("Enter the password");

pas=s.nextLine();

System.out.println("value in pas is"+pas);

boolean res=Password.isValidPassword(pas);

if(res==true)  

{

System.out.println("password is valid");

}

else

{

System.out.println("password is invalid");

}    

}

}

For >=8 charcters length password to have atleast one digit, atleast one alphabet and no spaces, the regular expression inside matches would be
if((p.length()>=8) &&p.matches(".*[a-zA-Z].*") &&p.matches(".*[0-9].*")&&(!(p.matches(".*\\s.*"))))