Thursday, 1 July 2021

Java Program to add new element, its atomic number and atomic weight, sort based on atomic number and search based on element name

 

A chemist needs to record data of elements in periodic table. Draw the class diagram and develop the classChemicalElement with name, atomicNum andatomicWeight as private attributes. Code the constructorand toString() method. The main() method inChemicalDemo class must store data of chemicals in acollection and is menu driven with the followingoptions: a) Add new element, b)sort based onatomicNum and c)search based on name.

Sol:

Class Diagram:                                                                                              

 

ChemicalElement

-name:String

-atomicNum:int

-atomicWeight:float

+ChemicalElement(name: String, atomicNum:int, atomicWeight:float)

+getName():String

+getAtomicNum():int

 

SortByAtomicNumber

 

+compare(c1: ChemicalElement, c2: ChemicalElement):int

 

 

Demo

~cel:ArrayList<ChemicalElement>

~sc:Scanner

+main(args:String[]):void

 

 

 

package key;

 

import java.util.ArrayList;

import java.util.Collections;

import java.util.Comparator;

import java.util.Scanner;

 

class ChemicalElement                                                                                    

{

            private String name;

            private int atomicNum;

            private float atomicWeight;

            public ChemicalElement(String name, int atomicNum, float atomicWeight)

            {

                        this.name = name;

                        this.atomicNum = atomicNum;

                        this.atomicWeight = atomicWeight;

            }

            public String getName() {

                        return name;

            }

            public int getAtomicNum() {

                        return atomicNum;

                       

            }

            public String toString() {

                        return "name=" + name + ", atomicNum=" + atomicNum + ", atomicWeight=" + atomicWeight;

            }         

}

class SortByAtomicNumber implements Comparator<ChemicalElement>                  

{

            public int compare(ChemicalElement c1, ChemicalElement c2)

            {

                        return (int)(c1.getAtomicNum()-c2.getAtomicNum());

            }

}

public class ChemicalDemo                                                                                        

{

            static ArrayList<ChemicalElement> cel= new ArrayList<ChemicalElement>();

            static Scanner sc = new Scanner(System.in);

            public static void main(String[] args)

            {

                        while(true)

                        {

                                    System.out.println("enter 1. Add new element 2. sort based on atomicNum 3. search based on name 4. exit");

                                    int choice=sc.nextInt();

                                    switch(choice)

                                    {

                                    case 1:

                                                System.out.println("enter name, atomic number and its atomic weight");

                                                cel.add(new ChemicalElement(sc.next(),sc.nextInt(),sc.nextFloat()));

                                                break;

                                    case 2:

                                                System.out.println("sorted names based on atomic number");

                                                Collections.sort(cel,new SortByAtomicNumber());

                                                for(ChemicalElement ob:cel)

                                                            System.out.println(ob);

                                                break;

                                    case 3:

                                                System.out.println("enter name to be searched");

                                                String key=sc.next();

                                                for(ChemicalElement ob:cel)

                                                            if(ob.getName().equals(key))

                                                            {

                                                                        System.out.println(ob);

                                                                        break;

                                                            }

                                                break;

                                    case 4:

                                                return;

                                    default:

                                                System.out.println("invalid choice");

                                               

                                    }

            }

 

}

}

 Output:

enter 1. Add new element 2. sort based on atomicNum 3. search based on name 4. exit

1

enter name, atomic number and its atomic weight

hydrogen

1

1.007

enter 1. Add new element 2. sort based on atomicNum 3. search based on name 4. exit

1

enter name, atomic number and its atomic weight

helium

2

4.002

enter 1. Add new element 2. sort based on atomicNum 3. search based on name 4. exit

2

sorted names based on atomic number

name=hydrogen, atomicNum=1, atomicWeight=1.007

name=helium, atomicNum=2, atomicWeight=4.002

enter 1. Add new element 2. sort based on atomicNum 3. search based on name 4. exit

3

enter name to be searched

helium

name=helium, atomicNum=2, atomicWeight=4.002

enter 1. Add new element 2. sort based on atomicNum 3. search based on name 4. exit

4


Java Program to add Football player details and sort them by number of players

 

A university records data of its Football players. Drawthe class diagram and develop the class FootballPlayerwith name, numberOfGoals and numberOfMatches.Code the constructor, toString() method. The main()method in Demo class must store data of footballplayers in a collection and is menu driven with thefollowing options: a) Add new player b)sort by numberof goals.

Class diagram                                                                                               

 

FootballPlayer

-name:String

-numberOfGoals:int

-numberOfMatches:int

+FootballPlayer(name: String, numberOfGoals:int, numberOfMatches:int)

+getNumberOfGoals():int

 

SortByNumberOfGoals

 

+compare(f1:FootballPlayer, f2: FootballPlayer):int

 

 

Demo

 

+main(args:String[]):void

 

 

 

FootballPlayer.java                                                                                        

package key;

 

public class FootballPlayer

{

            private String name;

            private int numberOfGoals,numberOfMatches;

           

            public int getNumberOfGoals() {

                        return numberOfGoals;

            }

 

            public void setNumberOfGoals(int numberOfGoals) {

                        this.numberOfGoals = numberOfGoals;

            }

 

            public FootballPlayer(String name, int numberOfGoals, int numberOfMatches)

            {

                        this.name = name;

                        this.numberOfGoals = numberOfGoals;

                        this.numberOfMatches = numberOfMatches;

            }

           

            public String toString()

            {

                        return "name=" + name + ", numberOfGoals=" + numberOfGoals + ", numberOfMatches="

                                                + numberOfMatches;

            }

           

           

}

 

Demo.java

package key;

 

import java.util.*;

class SortByNumberOfGoals implements Comparator<FootballPlayer>                    

{

            public int compare(FootballPlayer f1,FootballPlayer f2 )

            {

                        return (int)(f1.getNumberOfGoals() -f2.getNumberOfGoals());

            }

}

public class Demo                                                                                          

{

            public static void main(String[] args)

            {

                        List<FootballPlayer> fp = new ArrayList<FootballPlayer>();

                        Scanner sc= new Scanner(System.in);

                       

                        while(true)

                        {

                                    System.out.println("enter 1. Add new player 2.sort by numberof goals 3. exit");

                                    int choice=sc.nextInt();

                                    switch(choice)

                                    {

                                    case 1:

                                                System.out.println("enter player name, number of goals, numbe of matches");

                                                fp.add(new FootballPlayer(sc.next(),sc.nextInt(),sc.nextInt()));

                                                break;

                                    case 2:

                                                System.out.println("sorted players list based on number of goals");

                                                Collections.sort(fp,new SortByNumberOfGoals());

                                                for(FootballPlayer ob:fp)

                                                            System.out.println(ob);

                                                break;

                                    case 3:

                                                return;

                                    default:

                                                System.out.println("invalid choice");

                                               

                                    }

                        }

                       

            }

 

}

 

Output:

enter 1. Add new player 2.sort by numberof goals 3. exit

1

enter player name, number of goals, numbe of matches

sarvani

34

20

enter 1. Add new player 2.sort by numberof goals 3. exit

1

enter player name, number of goals, numbe of matches

lakshmi

12

40

enter 1. Add new player 2.sort by numberof goals 3. exit

2

sorted players list based on number of goals

name=lakshmi, numberOfGoals=12, numberOfMatches=40

name=sarvani, numberOfGoals=34, numberOfMatches=20

enter 1. Add new player 2.sort by numberof goals 3. exit

3

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.*"))))

Wednesday, 24 March 2021

1D and 2D arrays in java

1D arrays in java

  1. Syntax to declare an integer array in java
    int []a;  or int a[];   or int[] a;
  2. Allocating memory to store 3 integers (instantiation)
    a=new int[3];
    you can declare and instantiate in same line by writing int a[]=new int[3];
  3.  Initialization or giving values
    a[0]=2;
    a[1]=12;
    a[2]=5;
    (or) take array values from user
    for(int i=0; i< a.length;i++)
                a[i]=sc.nextInt();
    here sc is an object of Scanner class
  4. you can declare, instantiate and initialize in same line as int a[]={1,2,3,4};
  5. Displaying all elements of array using for each loop
    for(int ele: a)
            System.out.println(ele);
  6.  Displaying elements using for loop
    for(int i=0; i< a.length;i++)
                System.out.println(a[i]);
    here length is a property of arrays that will return the size of array
  7. Linear Search function in java that returns index if search element found otherwise returns -1
    public static int linearSearch(int a[],int key)
    {
           for(int i=0;i<a.length;i++)
           {
                     if(a[i] == key)
                            return i;
            }
            return -1;
    }

2D arrays in java

Declaration:
int[][] a;  or int[][] a;   or int [][]a;

Instantiation:
a = new int[3][3];
We can do declaration and instantiation in same line by writing int a[][] = new int[3][3];

Initialization and giving values
for(int i=0;i<a.length;i++)
{
           for(int j=0;j<a[i].length;j++)
                     a[i][j]=sc.nextInt();
}
here  a.length will give number of rows and a[i].length gives number of columns in each row.
and sc is object of Scanner class

Initialization, instantiation and initialization in single line
int a[][]={{1,2,3},{4,5,6},{7,8,9}};