Sunday, February 24, 2019

Java Example to check if Number is Odd or Even

Java Example to check if the entered number is Odd or Even. This example is for the beginners who just started learning programming.

import java.util.Scanner;

public class OddOrEven {

    public static void main(String[] args) {

        Scanner reader = new Scanner(System.in);

        System.out.print("Enter the number: ");
        int num = reader.nextInt();

        if(num % 2 == 0)
            System.out.println(num + " is even.");
        else
            System.out.println(num + " is odd.");
    }
}

Java Example to check if entered Number is Prime or not

This Java Example if for beginners to check if entered number is prime i.e. number which is divisible by only two numbers first 1 and second itself. If any number is divisible by 3 or more numbers, it is not a prime number.

import java.util.Scanner;
public class Prime {

    public static void main(String[] args) {
        
        
        Scanner keyboard = new Scanner(System.in);

        int number = keyboard.nextInt();
        boolean flag = false;
        for(int i = 2; i <= number/2; ++i)
        {
            // condition for nonprime number
            if(number % i == 0)
            {
                flag = true;
                break;
            }
        }

        if (!flag)
            System.out.println(number + " is a prime number.");
        else
            System.out.println(number + " is not a prime number.");
    }
}

Wednesday, August 30, 2017

Java example for generating a table of a number and for loop

This example is for Java beginners to let them learn two basic concepts of the language
1. for loop
2. Using Scanner class to get input from keyboard

 
import java.util.Scanner;

public class TableOfInteger {

     // start of main() function

        public static void main(String[] args) {

        Scanner keyboard = new Scanner(System.in);

        // get an object of Scanner class for getting input from keyboard

        System.out.println("enter an integer for generate table ");

        int table = keyboard.nextInt();

        // for loop

        for(int i=1;i<=10;i++)

                                System.out.println(table + "X" + i +"=" +table*i);

}

//end of main function()

}

Monday, August 28, 2017

If-else statement, read input from keyboard (by java.util.Scanner) and Find if a number is Even Or Odd example in Java

this example explains three important topics of Java
1. read input from keyboard
2. if-else statement
3. calculate if the number is even or odd

import java.util.Scanner;

public class FindEvenOrOddNumber {

        public static void main(String[] args) {

        // main() function

        Scanner keyboard = new Scanner(System.in);

        // Scanner object to read input from keyboard

        System.out.println("enter an integer");

        int even_odd = keyboard.nextInt();

         if(even_odd%2 == 0) //check if number is odd or even

                                System.out.println(even_odd + " is even number.");

                         else

                                System.out.println(even_odd + " is odd number.");

}

}

Sunday, August 27, 2017

Hello world example in Java

This Example is for the beginners to start programming in Java


public class Hello{

//main() function start

  public static void main(String args[]){

    System.out.println("Hello World !");

//command to print on the console 

  }

// main function finish

}

Saturday, November 15, 2014

Uploading Image in jsp, java, Netbeans

i had spent a lot of time for uploading an image in jsp page.so to help you guys i am writing this blog.
the way to upload the desired image is as below(neteans project)

1. Put the image file in web folder(where all the web pages are placed.)
2. Wright the code

 <%String s=request.getContextPath() + "/abc.JPG";%>

<img src="<%=s%>" width = "500" hight = "600" aligh = "center" />
3. Mention the extensions of image carefully i.e(.jpeg, jpg are not treated as same)

for any other query keep posting.
Good Luck!!!

Monday, November 10, 2014

Create and display dynamic Chart in JSP using Database inputs(jFreeChart Library)

 JSP code that generates chart of database(Time-Speed  which was my application requirement) and returns chart image whenever called

<%// required packages  %>

<%@ page import="java.awt.Image" %>

<%@ page import="java.awt.*"%>

<%@ page import="java.text.SimpleDateFormat"%>

<%@ page import="java.awt.BasicStroke"%>

<%@ page import ="org.jfree.ui.ApplicationFrame"%>

<%@ page import="java.io.*" %>

<%@ page import="java.io.File"%>

<%@ page import="org.jfree.chart.*" %>

<%@ page import="org.jfree.chart.axis.*" %>

<%@ page import="org.jfree.chart.entity.*" %>

<%@ page import="org.jfree.chart.labels.*" %>

<%@ page import="org.jfree.chart.plot.*" %>

<%@ page import="org.jfree.chart.renderer.category.*" %>

<%@ page import="org.jfree.chart.urls.*" %>

<%@ page import="org.jfree.data.category.*" %>

<%@ page import="org.jfree.data.general.*" %>

<%@ page import="org.jfree.data.time.Minute"%>

<%@ page import="org.jfree.data.time.Hour"%>

<%@ page import="org.jfree.data.time.TimeSeries"%>

<%@ page import="org.jfree.data.time.TimeSeriesCollection"%>

<%@ page import="org.jfree.data.xy.XYDataset"%>

<%@ page import="org.jfree.chart.plot.XYPlot"%>

<%@ page import="org.jfree.chart.renderer.xy.StandardXYItemRenderer"%>

<%@ page import="org.jfree.chart.renderer.xy.XYItemRenderer"%>

 <%@ page import=  "java.sql.Connection" %>

<%@ page import  ="java.sql.DriverManager" %>

<%@ page import = "java.sql.SQLException" %>

<%@ page import = "java.sql.PreparedStatement" %>

<%@ page import = "java.sql.ResultSet" %>

<%@ page import = "java.sql.Statement" %>

 <%@ page import=  "javax.servlet.*" %>

<%@ page import  ="javax.servlet.http.*" %>



<%@ page import="java.awt.image.BufferedImage"%>

<%

 try

 {

 File image = File.createTempFile("image", "tmp");



 //chart class instance

Fms fm = new Fms("Graph");



JFreeChart chart = fm.createChart(fm.dataset);

 ChartUtilities.saveChartAsPNG(image, chart, 500, 400);

//get input stream

 FileInputStream fileInStream = new FileInputStream(image);

//output stream foe returning chart as image

 OutputStream outStream = response.getOutputStream(); 

 long fileLength;

 byte[] byteStream;

 fileLength = image.length();

 byteStream = new byte[(int)fileLength];

//read chart image

 fileInStream.read(byteStream, 0, (int)fileLength);

//returns chart image whenever called

 response.setContentType("image/png");

 response.setContentLength((int)fileLength);

 response.setHeader("Cache-Control","no-store,no-cache, must-revalidate, post-check=0, pre-check=0");

 response.setHeader("Pragma", "no-cache");

 fileInStream.close();

 outStream.write(byteStream);

 outStream.flush();

 outStream.close();

 }

 catch (IOException e)

 {

 System.err.println("Problem occurred creating chart.");

 }

%>

<%! public class Fms extends ApplicationFrame {   

//Main class

   XYDataset dataset= null;

   public Fms(final String title) {

        super(title);

      dataset= createDataset();

        final JFreeChart chart = createChart(dataset);

        final ChartPanel chartPanel = new ChartPanel(chart);

        chartPanel.setPreferredSize(new java.awt.Dimension(700, 570));

        chartPanel.setMouseZoomable(true, false);

        setContentPane(chartPanel);

    } 

//chart creation method

   JFreeChart createChart(final XYDataset dataset) {

        final JFreeChart chart = ChartFactory.createTimeSeriesChart(

            "Speed Chart",

            "Time",

            "Speed",

            dataset,

            true,

            true,

            false

        );

        chart.setBackgroundPaint(Color.white);

       final XYPlot plot = chart.getXYPlot();

        plot.setBackgroundPaint(Color.lightGray);

        plot.setDomainGridlinePaint(Color.white);

        plot.setRangeGridlinePaint(Color.white);

        plot.setDomainCrosshairVisible(true);

        plot.setRangeCrosshairVisible(false);

        final XYItemRenderer renderer = plot.getRenderer();

        if (renderer instanceof StandardXYItemRenderer) {

            final StandardXYItemRenderer rr = (StandardXYItemRenderer) renderer;

            rr.setShapesFilled(true);

            renderer.setSeriesStroke(0, new BasicStroke(1.0f));

            renderer.setSeriesStroke(1, new BasicStroke(1.0f));

           }       

        final DateAxis axis = (DateAxis) plot.getDomainAxis();

        axis.setDateFormatOverride(new SimpleDateFormat("dd:MM")); 

        try{

        final ChartRenderingInfo info = new ChartRenderingInfo

(new StandardEntityCollection());

final File file1 = new File("c:/Documents and Settings/accounts/WebApplication2/web/barchart.png");

ChartUtilities.saveChartAsPNG(file1, chart, 600, 400, info);

        }catch(Exception e){}

        return chart;

    }   

//data set generation method

    private XYDataset createDataset() {

        final TimeSeriesCollection dataset = new TimeSeriesCollection();

        dataset.setDomainIsPointsInTime(true);       

        final TimeSeries s1 = new TimeSeries("Series 1", Minute.class);

         int str = 0;

         int i =0,j= 0 ;

         String str1 = null;

        try{             

      Class.forName("sun.jdbc.odbc.JdbcOdbc"); 

      Connection con=DriverManager.getConnection("jdbc:odbc:FMSDB",null,null);

      PreparedStatement st;   

      Statement stmt = con.createStatement(); 

      String query = "Select * from Job_Status";

      stmt.executeQuery(query);

       ResultSet rs = stmt.executeQuery(query);       

           while( rs.next() )

        {                 

         str1= rs.getString("Time");

         String sa = str1.substring(11,13);

         String ha = str1.substring(14,16);

        str= rs.getInt("Speed"); 

        j=Integer.parseInt(sa);

        i=Integer.parseInt(ha);

        String date = rs.getString("Date");

        String y = date.substring(0,4);

         String m = date.substring(5,7);

          String d = date.substring(8,10);

         s1.add(new Minute(i, j, Integer.parseInt(d), Integer.parseInt(m), Integer.parseInt(y)), str);

          }

          }

          catch(Exception e)

          {             

          }

         System.out.println(str1.substring(11,13));

          System.out.println(str1.substring(14,16)+"\t"+str1);                 

        dataset.addSeries(s1);   

        return dataset;

    }

    }

%>
HTML Code for calling this JSP file
exp.jsp is the name of above jsp code file in my application
<html>

<body>

<img src="exp.jsp" alt="Progress chart" />

</body>

</html>
Note: To implement this code you will need jFreeChart Library from jFree Org.