Search This Blog

Thursday, June 17, 2021

Motion Detector in Java (Using Sarxos.Webcam)

 Motion Detector in Java



This link can be used to download the library used to make this project:


import  javax.sound.sampled.*;
import java.io.File;
import java.io.IOException;

import com.github.sarxos.webcam.Webcam;
import com.github.sarxos.webcam.WebcamMotionDetector;
import com.github.sarxos.webcam.WebcamMotionEvent;
import com.github.sarxos.webcam.WebcamMotionListener;


public class DetectMotion implements WebcamMotionListener {

public DetectMotion() {

WebcamMotionDetector detector = new WebcamMotionDetector(Webcam.getDefault());
detector.setInterval(200); // one check per 500 ms
detector.addMotionListener(this);
detector.start();
}

@Override
public void motionDetected(WebcamMotionEvent wme) {
System.out.print("beep ");
}

public static void main(String[] args) {




//Detector
new DetectMotion();
System.in.read(); // keep program open
}
}


Every time a motion is detected by the webcam of your PC 'beep' will be printed.

Use the famous book 'Head First Java' to learn Java in the best way possible, Download the free e-book now.

You can also follow this tutorial by Genuine Coder Youtube channel to build basic programs using this library.


Friday, June 4, 2021

Basic Calculator Using 'GUI' in java

Calculator Using GUI



********************************

 package com.company;


import javax.swing.*;

import java.awt.*;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;


public class GUI_calculator implements ActionListener {

    float first=0;

    float second=0;

    float third=0;

   private JFrame frame;

   private JPanel panel;

    private JButton b;

   private JButton b1;

   private JButton b2;

   private JButton b3;

   private JButton b4;

    private JButton b5;

    private JButton b6;

    private JButton b7;

   private JLabel label;

    private JLabel label1;

    private JLabel label2;

    public GUI_calculator(){

        frame=new JFrame();

        label=new JLabel("0");

        b=new JButton("++");

        b1=new JButton("+");

        b2=new JButton("-");

        b3=new JButton("*");

        b4=new JButton("/");

        label1=new JLabel("0");

        b5=new JButton("++");

        b6=new JButton("=");

        b7=new JButton("C");

        label2=new JLabel("0");

        b1.addActionListener(this);

        b2.addActionListener(this);

        b3.addActionListener(this);

        b4.addActionListener(this);

        b.addActionListener(this);

        b5.addActionListener(this);

        b6.addActionListener(this);

        b7.addActionListener(this);


        //Panel Content

        panel=new JPanel();

        panel.setBorder(BorderFactory.createEmptyBorder(30,30,10,30));


        panel.add(label);

        panel.add(b);

        panel.add(label1);

        panel.add(b5);

        panel.add(b7);

        panel.add(b1);

        panel.add(b2);

        panel.add(b3);

        panel.add(b4);

        panel.add(b6);

        panel.add(label2);



        panel.setLayout(new GridLayout(0,1));

        frame.add(panel,BorderLayout.CENTER);

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        frame.setTitle("Calculator");

        frame.pack();

        frame.setVisible(true);

    }

    public static void main(String[] args) {

        new GUI_calculator();

    }


    @Override

    public void actionPerformed(ActionEvent e) {

if (e.getSource()==b){

    first++;

    label.setText(""+first);

}

else { }

if (e.getSource()==b5){

    second++;

    label1.setText(""+second);

}

else { }

if (e.getSource()==b1){

    third=first+second;

}

else if (e.getSource()==b2){

    third=first-second;

}

else if (e.getSource()==b3){

    third=first*second;

}

else if (e.getSource()==b4){

    third=first/second;

}

else if (e.getSource()==b7){

    first=0;

    second=0;

    label1.setText(""+second);

    label.setText(""+first);

}

if (e.getSource()==b6){

    label2.setText(""+third);

}

    }

}


Wednesday, June 2, 2021

Library Management System in Java

 Library Management System

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

class Library{
    Scanner sc=new Scanner(System.in);
    List<String> Books=new ArrayList<String>();
    List<String> IssuedBooks=new ArrayList<String>();

    public void addBook(){
        System.out.print("Enter the name of the book to be added: ");
        Books.add(sc.nextLine());
    }
    
    public void showAvailableBooks(){
        if (Books.size()==0){
            System.out.println("No books in the library");
        }
        else {
            System.out.println("Here is a list of books available in our library: ");
            for (int a = 1; a <= Books.size(); a++) {
                System.out.println(a + " " + Books.get(a - 1));
            }
        }
    }

    public void issueBook(){
        System.out.print("Enter the serial no. of the book you want to issue: ");
        int b=sc.nextInt();
        IssuedBooks.add(Books.get(b-1));
        System.out.println("You have issued: "+Books.get(b-1));
        Books.remove(b-1);
    }

    public void showIssuedBooks(){
        if (IssuedBooks.size()==0){
            System.out.println("No books issued!");
        }
        else {
            System.out.println("Here is a list of books issued: ");
            for (int a=1;a<=IssuedBooks.size();a++){
                System.out.println(a+" "+IssuedBooks.get(a-1));
            }
        }

    }

    public void returnBook(){
        System.out.print("Enter the serial no. of the book to be returned from the issued books: ");
        int b= sc.nextInt();
        Books.add(IssuedBooks.get(b-1));
        System.out.println("You have returned: "+IssuedBooks.get(b-1));
        IssuedBooks.remove(b-1);
    }

}
public class online_library {
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        //Implement a library using java class library
        //Method: addBook, issueBook, returnBook, showAvailableBooks,showIssuedBooks,
        //Properties: Array to store the available books, Array to store the issued books
        Library jnrm=new Library();
        int a=0;
        System.out.println("Add book to library->add\nShow available books->showl\nIssue book->issue\nShow issued books->showi\nReturn book->return");
    while (a==0){

        String b= sc.next();
        if (b.equals("add")){
            jnrm.addBook();
        }
        else if (b.equals("showl")){
            jnrm.showAvailableBooks();
        }
        else if (b.equals("issue")){
            jnrm.issueBook();
        }
        else if (b.equals("showi")){
            jnrm.showIssuedBooks();
        }
        else if (b.equals("return")){
            jnrm.returnBook();
        }
        else {
            System.out.println("Something went wrong\nCheck the syntax!!!");
        }
    }
    }
}


Sunday, May 30, 2021

What is Java?

 What is Java?


Java is a programming language and computing platform first released by Sun Microsystems in 1995.







There are lots of applications and websites that will not work unless you have Java installed, and more are created every day. Java is fast, secure, and reliable. From laptops to datacenters, game consoles to scientific supercomputers, cell phones to the Internet, Java is everywhere!


Features of Java



Object Oriented


In Java, everything is an Object. Java can be easily extended since it is based on the Object model.



Platform Independent


Unlike many other programming languages including C and C++, when Java is compiled, it is not compiled into platform specific machine, rather into platform-independent byte code. This byte code is distributed over the web and interpreted by the Virtual Machine (JVM) on whichever platform it is being run on.



Simple


Java is designed to be easy to learn. If you understand the basic concept of OOP Java, it would be easy to master.



Secure


With Java's secure feature it enables to develop virus-free, tamper-free systems. Authentication techniques are based on public-key encryption.



Architecture-neutral


Java compiler generates an architecture-neutral object file format, which makes the compiled code executable on many processors, with the presence of Java runtime system.



Portable


Being architecture-neutral and having no implementation dependent aspects of the specification makes Java portable. The compiler in Java is written in ANSI C with a clean portability boundary, which is a POSIX subset.



Robust


Java makes an effort to eliminate error-prone situations by emphasizing mainly on compile time error checking and runtime checking.



Multithreaded


With Java's multithreaded feature it is possible to write programs that can perform many tasks simultaneously. This design feature allows the developers to construct interactive applications that can run smoothly.



Interpreted


Java byte code is translated on the fly to native machine instructions and is not stored anywhere. The development process is more rapid and analytical since the linking is an incremental and light-weight process.



High Performance


With the use of Just-In-Time compilers, Java enables high performance.



Distributed


Java is designed for the distributed environment of the internet.



Dynamic

Java is considered to be more dynamic than C or C++ since it is designed to adapt to an evolving environment. Java programs can carry an extensive amount of run-time information that can be used to verify and resolve accesses to objects at run-time.


Java vs JavaScript: What’s the Difference?






You might have heard of another language known as JavaScript, and the first thing that comes to our mind is that they must be the same thing. But they are not.

Java is an Object-Oriented Programming language that is platform-independent because it gets executed in the Java Virtual Machine (JVM).

On the other hand, JavaScript is  an object-oriented scripting language that helps to create dynamic HTML pages. Java vs JavaScript has become a hot topic of discussion these days.

Permutation And Combination in Java

Permutation And Combination

The Java code below takes input from the user to return permutation and combination.

 import java.util.Scanner;


public class Math_programme {

    static int factorial(int a){

        if (a==0){

            return 1;

        }

        else if (a==1){

            return 1;

        }

        return a*factorial(a-1);

    }

    static int permutation(int a,int b){

        return factorial(a)/(factorial(a-b));

    }

    static int combination(int a,int b){

        return factorial(a)/(factorial(b)*factorial(a-b));

    }

    public static void main(String[] args) {

        Scanner sc=new Scanner(System.in);

        int a=sc.nextInt();

        String d=sc.next();

        int b=sc.nextInt();

        int c;

        int minus=a-b;

        if (d.equals("p") && minus>=0){

            c=permutation(a,b);

            System.out.println(c);

        }

        else if (d.equals("c") && minus>=0){

            c=combination(a,b);

            System.out.println(c);

        }

        else {

            System.out.println("Wrong format");

        }

    }

}



Friday, May 28, 2021

Head First Java 2nd Edition PDF


 


Book description

Learning a complex new language is no easy task especially when it s an object-oriented computer programming language like Java. You might think the problem is your brain. It seems to have a mind of its own, a mind that doesn't always want to take in the dry, technical stuff you're forced to study.

The fact is your brain craves novelty. It's constantly searching, scanning, waiting for something unusual to happen. After all, that's the way it was built to help you stay alive. It takes all the routine, ordinary, dull stuff and filters it to the background so it won't interfere with your brain's real work--recording things that matter. How does your brain know what matters? It's like the creators of the Head First approach say, suppose you're out for a hike and a tiger jumps in front of you, what happens in your brain? Neurons fire. Emotions crank up. Chemicals surge.

That's how your brain knows.

And that's how your brain will learn Java. Head First Java combines puzzles, strong visuals, mysteries, and soul-searching interviews with famous Java objects to engage you in many different ways. It's fast, it's fun, and it's effective. And, despite its playful appearance, Head First Java is serious stuff: a complete introduction to object-oriented programming and Java. You'll learn everything from the fundamentals to advanced topics, including threads, network sockets, and distributed programming with RMI. And the new. second edition focuses on Java 5.0, the latest version of the Java language and development platform. Because Java 5.0 is a major update to the platform, with deep, code-level changes, even more careful study and implementation is required. So learning the Head First way is more important than ever.

If you've read a Head First book, you know what to expect--a visually rich format designed for the way your brain works. If you haven't, you're in for a treat. You'll see why people say it's unlike any other Java book you've ever read.

By exploiting how your brain works, Head First Java compresses the time it takes to learn and retain--complex information. Its unique approach not only shows you what you need to know about Java syntax, it teaches you to think like a Java programmer. If you want to be bored, buy some other book. But if you want to understand Java, this book's for you.






Calculator source code (java)

 Calculator


import java.util.Scanner;


public class Calculator {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        int a1 = 1;

        while (a1 == 1){

        System.out.print("Enter 1st no: ");

        float input1 = sc.nextFloat();

        System.out.print("Enter the operation: ");

        String input = sc.next();

        System.out.print("Enter 2nd no: ");

        float input2 = sc.nextFloat();

        String a = new String("+");

        String b = new String("-");

        String c = new String("*");

        String d = new String("/");

        System.out.print("Result is: ");

        if (input.equals(a)){

            System.out.println(input1+input2);

        }

        else if (input.equals(b)){

            System.out.println(input1-input2);

        }

        else if (input.equals(d)){

            System.out.println(input1/input2);

        }

        else if (input.equals(c)){

            System.out.println(input1*input2);

        }

else {

            System.out.println("Invalid operation");

        }

           System.out.println("");

        }

    }

}


The above Java code can be used in a GUI to make it look good and user friendly.

Find Leap Year source code (java)

 Find Leap Year


import java.util.Scanner;

public class LeapYear {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = 1;
        while (n==1){

        System.out.println("Enter the year: ");
        int y = sc.nextInt();

        if (y%4==0){
            System.out.println("Yes, it's a leap year");
        }
        else {
            System.out.println("No, it's not a leap year");
        }
        }
    }
}

The Bear Song source code (java)

 The Bear Song


public class beer_song {
    public static void main(String[] args) {
        int beerNum = 10;
        String word =new String("bottles") ;
        while (beerNum > 0) {
            if (beerNum == 1) {
                word = "bottle"; // singular, as in ONE bottle.
            }
            System.out.println(beerNum + " " + word + " of beer on the wall");
            System.out.println(beerNum + " " + word + " of beer.");
            System.out.println("Take one down.");
            System.out.println("Pass it around.");
            System.out.println("\n");
            beerNum = beerNum - 1;
            } if (beerNum==0){
                System.out.println("No more bottles of beer on the wall");

            } // end else
        } // end while loop
    }



Making a Fibonacci series source code(java) (two approaches)

 Making a Fibonacci series using 'for loop'


***********************************************

import java.util.Scanner;

public class fibonacci_series {
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        int times=0;
        while (times<10){
        int a=0;
        int b=1;
        int d;

            int upto= sc.nextInt();
            System.out.print(a+" "+b);

            for (int c=1;c<=upto-2;c++){
                d=a+b;
                System.out.print(" " +d+" ");
                a=b;
                b=d;

            }
            times++;
        }

    }
}


*****************************************


Making a Fibonacci series using Recursion


************************************

public class fibonacci_series_recursion {
    static int a=0,b=1,c=0;
    static void fib(int upto){
        if (upto>0){
            c=a+b;
            System.out.print(" "+c);
            a=b;
            b=c;
            fib(upto-1);
        }

    }

    public static void main(String[] args) {
        System.out.print(a+" "+b);
        int a=10;
        fib(a);
    }
}


**************************************

Career Guidance AI source code(java)

Career Guidance AI 


import java.sql.Time;

import java.util.Random;

import java.util.Scanner;

import java.util.concurrent.TimeUnit;


public class career {

    static void loading(){

        System.out.print("Loading");

        for (int a =1;a<3;a++){

            System.out.print("...");

            try {

                TimeUnit.SECONDS.sleep(2);

            } catch (InterruptedException e) {

                e.printStackTrace();

            }

        }

        System.out.println(" ");

    }

    static void hold(int y){

        try {

            TimeUnit.SECONDS.sleep(y);

        } catch (InterruptedException e) {

            e.printStackTrace();

        }

    }

    public static void main(String[] args){

        Random ra=new Random();

        Scanner sc=new Scanner(System.in);

        hold(2);

        System.out.print("Hey!");

        hold(1);

        System.out.print(" I am ARTEMIS. ");

        hold(2);

        System.out.println("Your personal AI");

        hold(2);

        System.out.print("And I am here to tell you");

        hold(1);

        System.out.println(" what job suits you the best");

        System.out.println(" ");

        hold(3);

        System.out.println("Do you wish to continue?( y/n )");

        String start = sc.next();

        System.out.println(" ");

        hold(1);

        if (start.equals("n")){

            System.out.println("Oh! I guess you are not interested");

            System.out.println("loss is all yours");

            System.exit(0);

        }

        else if (start.equals("y")){

            System.out.println("Very well ;) Lets begin");

        }

        else {

            System.out.println("I guess you are not a very smart person");

            System.out.println("I thought you will get that you have to answer in 'y' or 'n'");

            System.exit(0);

        }

        hold(2);


        // STRINGS

        String[] names={"That is a beautiful name","That is not a very good name",

                "That seems to be a pretty common name","wow! What a unique name"};

        //0-Bio

        //1-Economics

        //2-Physics

        //3-computer

        //4-arts

        //5-Teaching

        String[][] car={

                {"Psychologist"," Physician assistant"," Physician/Surgeon","Agricultural Food Scientist","Pharmacist","Animal Breeder","Conservation Scientist","Environmental Engineer and Technician","Environmental Scientist","Farmer or Rancher","Fish and Game Warden or Conservation Officer","Fish Hatchery Manager","Fisher","Forester","Geophysicist",""},

                {"Management analyst","Financial analyst","Chief executive","Accountant or Auditor","Administrative Assistant or Secretary ","Budget Analyst","Customer Service Representative","Employment and Placement Specialist","File Clerk","Proofreader","Statistician"},

                {"Civil engineer","Physical scientist","Engineer","Electrician"},

                {"Computer programmer","Software developer","Computer and information systems manager"},

                {"Lawyer","Actor","Art Director","Audio or Video Equipment Technician","Broadcast News Anchor","Dancer/Choreographer","Fashion Designer","Graphic Designer","Makeup Artist","Musician or Singer"},

                {"Education Administrator","Elementary School Teacher","Fitness Trainer","Post-Secondary Teacher","School Counselor/Social Worker/Psychologist","Training Specialist or Manager"}};



        //Personal Info

        System.out.println(" ");

        System.out.println("Are you male? (y/n)");

        String gender = sc.next();

        System.out.println(" ");

        hold(1);

        System.out.println("What is your name?");

        String name = sc.next();

        System.out.println(" ");

        hold(1);

            System.out.println(name+", "+names[ra.nextInt(3)]);

        System.out.println(" ");

        hold(1);

        System.out.println("what field are you in? (science,economics,arts)");

        String field=sc.next();

        System.out.println(" ");

        hold(1);

        System.out.println("How good are you in dealing with children? Rate yourself on the scale of 0 to 10");

        float childrate = sc.nextFloat();

        System.out.println(" ");

        hold(1);

        if (childrate<5){

            System.out.println("That's pretty bad");

        }

        else if(childrate>=5 && childrate<=7){

            System.out.println("You are not bad but can be improved");

        }

        else if (childrate>7 && childrate<=10){

            System.out.println("That's amazing !!");

        }

        else {

            System.out.println("I guess you don't know how to rate yourself");

        }

        hold(1);

        System.out.println(" ");

        System.out.println("Did you have Biology as a subject?(y/n)");

        String bio= sc.next();

        System.out.println(" ");

        hold(1);

        System.out.println("Did you have computer as a subject?(y/n)");

        String comp=sc.next();

        System.out.println(" ");

        hold(1);

        float biorate=0;

        if (bio.equals("y")){

            System.out.println("If you have Biology, how much do you rate yourself out of 10");

            biorate=sc.nextFloat();

            System.out.println(" ");

        }


        float comrate=0;

        if (comp.equals("y")){

            System.out.println("If you have computer, how much do you rate yourself out of 10");

            comrate=sc.nextFloat();

            System.out.println(" ");

        }

        float phyrate=0;

        if (field.equals("science")){

            System.out.println("If you have physics, how much do you rate yourself out of 10");

            phyrate=sc.nextFloat();

            System.out.println(" ");

        }


        float ecorate=0;

        if (field.equals("economics")){

            System.out.println("If you have economics, how much do you rate yourself out of 10");

            ecorate=sc.nextFloat();

            System.out.println(" ");

        }

        System.out.println(" ");

        hold(1);

        System.out.println("OK, NOW LET'S SEE WHAT SUITS YOU THE BEST");

        System.out.println(" ");

        String career=new String();

        loading();

        if (field.equals("science") && bio.equals("y") && biorate>6 && phyrate<8){

            career=car[0][ra.nextInt(car[0].length)];

        }

        else if (field.equals("science") && comp.equals("y") && comrate>6 && phyrate<8){

            career=car[3][ra.nextInt(car[3].length)];

        }

        else if (field.equals("science") && phyrate>=8) {

            career = car[2][ra.nextInt(car[2].length)];

        }

        else if (field.equals("economics") && ecorate>6){

            career=car[1][ra.nextInt(car[1].length)];

        }

        else if (field.equals("arts")){

            career=car[4][ra.nextInt(car[4].length)];

        }

        else if (childrate>5){

            career=car[5][ra.nextInt(car[5].length)];

        }

        else {

            career="Nothing";

        }


        loading();

        System.out.println(" ");

        System.out.println("What You can be in future is :");

        System.out.println(" ");

        System.out.println(" ");

        hold(3);

        System.out.println("********");

        System.out.println(" ");

        System.out.println(career);

        System.out.println(" ");

        System.out.println("********");






    }

}


Rock Paper Scissor game source code (java)

Rock Paper Scissor game


 import java.util.Scanner;

import java.util.Random;


public class rock {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        Random ra = new Random();

        int j = 1;

        while (j == 1){

            System.out.println("Rock->0 , Paper->1 , Scissor->2");

            int ci = ra.nextInt( 3 );

        System.out.print("Enter your no: ");

        int my = sc.nextInt();

        if (ci == my){

            System.out.println("Draw");

        }

        else if (my == ci+1 || my == ci-2){

            System.out.println("You win !!");

        }

        else {

            System.out.println("You lose !!");

        }

        if (ci == 0){

            System.out.println("Computer chose Rock");

        }

        else if (ci == 1){

            System.out.println("Computer chose Paper");

        }

        else{

            System.out.println("Computer chose Scissor");

        }

        System.out.println("Let's play again !!");

        }


    }


}


Encrypt and Decrypt secret messages source code (java)

Encrypt and Decrypt



 import java.util.Locale;

import java.util.Scanner;

import java.util.concurrent.TimeUnit;



public class ED {

    static void sleep(int a) throws InterruptedException {

        TimeUnit.SECONDS.sleep(a);

    }

   static String encrypt(String a) throws InterruptedException {

       System.out.println("Encrypting....");

        sleep(3);


       String b=a.replace("a","05");

       String b1=b.replace("b","06");

       String b2=b1.replace("c","0a");

       String b3=b2.replace("d","0b");

       String b4=b3.replace("e","01");

       String b5=b4.replace("f","02");

       String b6=b5.replace("g","03");

       String b7=b6.replace("h","04");

       String b8=b7.replace("i","0c");

       String b9=b8.replace("j","0d");

       String b10=b9.replace("k","0e");

       String b11=b10.replace("l","0f");

       String b12=b11.replace("m","0g");

       String b13=b12.replace("n","0h");

       String b14=b13.replace("o","0i");

       String b15=b14.replace("p","0j");

       String b16=b15.replace("q","0k");

       String b17=b16.replace("r","0l");

       String b18=b17.replace("s","0m");

       String b19=b18.replace("t","0n");

       String b20=b19.replace("u","0o");

       String b21=b20.replace("v","0p");

       String b22=b21.replace("w","0q");

       String b23=b22.replace("x","0r");

       String b24=b23.replace("y","0s");

       String b25=b24.replace("z","0t");

       String b26=b25.replace(" ","#m");

       return b26;

    }

    static String decrypt(String a) throws InterruptedException {

        System.out.println("Decrypting....");

        sleep(3);

        String b=a.replace("05","a");

        String b1=b.replace("06","b");

        String b2=b1.replace("0a","c");

        String b3=b2.replace("0b","d");

        String b4=b3.replace("01","e");

        String b5=b4.replace("02","f");

        String b6=b5.replace("03","g");

        String b7=b6.replace("04","h");

        String b8=b7.replace("0c","i");

        String b9=b8.replace("0d","j");

        String b10=b9.replace("0e","k");

        String b11=b10.replace("0f","l");

        String b12=b11.replace("0g","m");

        String b13=b12.replace("0h","n");

        String b14=b13.replace("0i","o");

        String b15=b14.replace("0j","p");

        String b16=b15.replace("0k","q");

        String b17=b16.replace("0l","r");

        String b18=b17.replace("0m","s");

        String b19=b18.replace("0n","t");

        String b20=b19.replace("0o","u");

        String b21=b20.replace("0p","v");

        String b22=b21.replace("0q","w");

        String b23=b22.replace("0r","x");

        String b24=b23.replace("0s","y");

        String b25=b24.replace("0t","z");

        String b26=b25.replace("#m"," ");

        return b26;

    }

    public static void main(String[] args) throws InterruptedException {

        Scanner sc=new Scanner(System.in);

        String k=sc.nextLine();

        String j=sc.next();


        String i=k.toLowerCase(Locale.ROOT);

        if (j.equals("encrypt")){

            System.out.println(encrypt(i));

        }

        else if (j.equals("decrypt")){

            System.out.println(decrypt(i));

        }

        else {

            System.out.println("Operation not possible\nPlease enter a valid");

        }

    }

}


'Guess the number game' source code(java)

import java.util.Random;
import java.util.Scanner;


class game{
Random ra=new Random();
Scanner sc=new Scanner(System.in);
int theNum= ra.nextInt(100);

public void cond(int l){

for (int i=1;i<=l;i++){
System.out.println(" "+i);
System.out.print("Enter your number: ");
int a=sc.nextInt();

if (theNum>a){
System.out.println("Greater than "+a);
}

else if (theNum<a){
System.out.println("Less than "+a);
}

else {
System.out.println("Congrats !!!"+theNum+" is the correct guess");

if (i<=6)
System.out.println("It took you only "+i+" tries to guess the number");

else {
System.out.println("But it took you "+i+" tries");
}
break;
}
System.out.println(" ");
if (i==l){
System.out.println("Loser!!!");
System.out.println("The number is "+theNum);
}
}

}
}


public class Guess_the_number_game {

public static void main(String[] args) {

Scanner sc=new Scanner(System.in);
// Create a class game which allows the user to play " Guess the number" game once
game guess=new game();
System.out.println("Choose your difficulty level (1-Easy,2-Medium,3-Hard):");
int k=sc.nextInt();
System.out.println("Guess the number");
System.out.println("The number is between 0 and 100");
if (k==1){
System.out.println("You will be given 10 chances to guess the number");
guess.cond(10);
}
else if (k==2){
System.out.println("You will be given 7 chances to guess the number");
guess.cond(7);
}
else if (k==3){
System.out.println("You will be given 5 chances to guess the number");
guess.cond(5);
}

}
}



Thursday, May 27, 2021

How to extract the last n characters from a string using Java?

 Example:

public class ExtractingCharactersFromStrings {
   public static void main(String args[]) {
   
      String str = "Hi welcome to tutorialspoint";
      int n = 5;
      int initial = str.length()-5;
      for(int i=initial; i<str.length(); i++) {
         System.out.println(str.charAt(i));
      }
   }
}

Output:

p
o
i
n
t

Trending Articles