skip to main | skip to sidebar

Java Programs and Examples with Output

Pages

  • Home
 
  • RSS
  • Twitter
Showing posts with label Basic Java Programs. Show all posts
Showing posts with label Basic Java Programs. Show all posts
Tuesday, January 24, 2012

Java Program to tells whether the Temperature is Hot or not

Posted by Admin at 10:09 PM – 0 comments
 
Here is a Java Program to tells whether the Temperature is Hot or not
import java.util.*;

class weather{
 public static void main (String arg[]) {
  Scanner in=new Scanner (System.in);
  int a;

  System.out.print ("\n\t Enter the temprature in Celcious = ");
  a=in.nextInt();

  if (a<=20)
   System.out.print ("\n\t Whether is Cool ");
  else if (a<=30 && a>=21)
   System.out.println ("\n\t Whether is Fine ");
  else if (a<=40 && a>=31)
   System.out.println ("\n\t Whether is Hot ");
  else 
   System.out.println ("\n\t Whether is very Hot ");
 }
}

Output of Above Java Program
     Enter the temprature in Celcious = 31

     Whether is Hot 
[ Read More ]
Read more...
Monday, January 16, 2012

Use a Formatter object to format 20 random values of type double between –50 and +50

Posted by Admin at 9:13 AM – 0 comments
 
Use a Formatter object to format 20 random values of type double between –50 and +50 and output the entire set of 20 in a single call of System.out.print() or System.out.println().

import java.util.Formatter;
import static java.lang.Math.random;

public class FormatToString {
  public static void main(String[] args) {
    double[] data = new double[20];

    for (int i = 0 ; i < data.length ; ++i) {
      data[i] = 100.0*random() - 50.0;
    }

    StringBuilder buf = new StringBuilder();          // Buffer to hold output
    Formatter formatter = new Formatter(buf);         // Formatter to format data into buf
    int i = 0;
    for(double x : data) {
      formatter.format("%4d)%+7.2f", ++i, x);
      if(i%5 == 0) {
        formatter.format("%n");
      }
    }
    System.out.println(buf);                          // Output all the values in one go
  }
}


Output of Above Java Program


   1) +46.53   2)  -5.14   3)  -3.81   4) -45.54   5) +32.27
   6) -23.71   7) +47.19   8) +44.52   9) -19.52  10) -35.47
  11)  -9.32  12) -28.05  13) +44.03  14) -46.65  15)  -5.68
  16) +46.42  17)  -8.72  18) -13.47  19) -44.96  20) +46.57

[ Read More ]
Read more...

Write a program to generate 20 random values of type double between -50 and +50

Posted by Admin at 9:11 AM – 0 comments
 
Write a program to generate 20 random values of type double between -50 and +50 and use the printf() method for System.out to display them with two decimal places in the following form:

   1) +35.93   2) -46.94   3) +42.27   4) +32.09   5) +29.21
   6) +13.87   7) -47.87   8) +30.67   9) -25.20  10) +29.67
  11) +48.62  12)  +6.70  13) +28.97  14) -41.64  15) +16.67
  16) +17.01  17)  +9.62  18) -15.21  19)  +7.46  20)  +4.09
 
import static java.lang.Math.random;

public class FormatDoubleData {
  public static void main(String[] args) {
    double[] data = new double[20];

    for (int i = 0 ; i < data.length ; ++i) {
      data[i] = 100.0*random() - 50.0;
    }
    int i = 0;
    for(double x : data) {
      System.out.printf("%4d)%+7.2f", ++i, x);
      if(i%5 == 0) {
        System.out.println();
      }
    }
  }
}


Output of Above Java Program


   1) +20.79   2) +34.37   3) -49.38   4) +15.51   5) -23.63
   6) +41.13   7)  -3.22   8) +48.90   9)  +1.98  10)  -9.97
  11)  -0.05  12) +27.93  13) +22.23  14) -15.53  15) -11.51
  16) -32.27  17) +34.89  18) +49.76  19) +31.99  20) -25.20
[ Read More ]
Read more...

Program to Create a Rectangle objects defined by Two Points

Posted by Admin at 6:05 AM – 0 comments
 
Define a class for rectangle objects defined by two points, the top-left and bottom-right corners of the rectangle. Include a constructor to copy a rectangle, a method to return a rectangle object that encloses the current object and the rectangle passed as an argument, and a method to display the defining points of a rectangle. Test the class by creating four rectangles and combining these cumulatively to end up with a rectangle enclosing them all. Output the defining points of all the rectangles you create.

This is the Point class definition. It is used by the Rectangle class


public class Point {
  // Create a Point object from a coordinate pair
  public Point(double x, double y) {
    this.x = x;
    this.y = y;
  }

  // Create a Point object from another Point
  public Point(Point p) {
    x = p.x;
    y = p.y;
  }

  // Get the value of the x coordinate
  double getX() {
    return x;
  }

  // Get the value of the y coordinate
  double getY() {
    return y;
  }

  public String toString(){
    return x +","+y;
  }

  // Fields store the point coordinates
  private double x;
  private double y;
}

This is the Rectangle class definition. It makes use of the Point class definition that is in the same directory as this file.

public class Rectangle {
  private Point topLeft;
  private Point bottomRight;

  // Constructors
  public Rectangle(double x1, double y1, double x2, double y2) {
    // Ensure topleft uses the smaller of x1,x2 and y1,y2
    // and topright uses the larger of x1,x2 and y1,y2
    topLeft = new Point(Math.min(x1,x2),Math.min(y1,y2));
    bottomRight = new Point(Math.max(x1,x2),Math.max(y1,y2));
  }

  public Rectangle(Point tl, Point br) {
    this(tl.getX(), tl.getY(), br.getX(), br.getY());
  }

  public Rectangle(Rectangle rect) {
    topLeft = new Point(rect.topLeft);
    bottomRight = new Point(rect.bottomRight);
  }

  // Methods to create a rectangle enclosing the current rectangle and the argument
  public Rectangle encloses(Rectangle rect) {
    // Return a new rectangle defined by the minimum x,y for to left and the and maximum x,y for bottom right
    return new Rectangle(Math.min(topLeft.getX(), rect.topLeft.getX()),
                         Math.min(topLeft.getY(), rect.topLeft.getY()),
                         Math.max(bottomRight.getX(), rect.bottomRight.getX()),
                         Math.max(bottomRight.getY(), rect.bottomRight.getY()));

  }

  public String toString()  {
    return "Rectangle: " + topLeft + " : " + bottomRight;
  }
}

This is the main Class to Test the Rectangle Class.

public class TestRectangle {
  public static void main(String args[]) {
    Rectangle[] rects = new Rectangle[4];
    Rectangle enclosing;

    // Initialize the rectangles as arbitrary sizes and at arbitrary positions:
    for(int i = 0 ; i < rects.length ; ++i) {
      rects[i] = new Rectangle(Math.random()*100, Math.random()*100, Math.random()*100, Math.random()*100);
      System.out.print("Coords of rectangle " + i + " are: ");
      System.out.println(rects[i]);
    }

    // Initialize the enclosing rectangle to be first rectangle
    enclosing = rects[0];

    // Combine it with each the other rectangles in turn.
    // This will result in the rectangle that encloses them all.
    for(Rectangle rect : rects)  {
      enclosing = enclosing.encloses(rect);
    }

    System.out.println("\nCoords of Enclosing rectangle are ");
    System.out.println(enclosing);
  }
}


Output of Above Java Program
Coords of rectangle 0 are: Rectangle: 0.1903728640358593,58.04643476457927 : 0.2032621709617044,85.8337274416007
Coords of rectangle 1 are: Rectangle: 6.239529478079319,44.58944044246343 : 66.47238823570548,57.983153189860396
Coords of rectangle 2 are: Rectangle: 10.500877688164522,59.35612909169482 : 80.53072142287722,99.35041648038772
Coords of rectangle 3 are: Rectangle: 28.73052501676693,2.2641735796500972 : 44.35555027080914,11.239350082208022

Coords of Enclosing rectangle are
Rectangle: 0.1903728640358593,2.2641735796500972 : 80.53072142287722,99.35041648038772


[ Read More ]
Read more...

To Reverse the Sequence of Letters in Each word of your Chosen Paragraph | Java Example

Posted by Admin at 5:27 AM – 0 comments
 
 Write a program that reverses the sequence of letters in each word of your chosen paragraph.
For instance, "To be or not to be." becomes "oT eb ro ton ot eb."

public class ReverseText {
  public static void main(String args[]) {
    // The String that is to be processed with a few newlines to make the
    // output a little more readable
    String text = "Into the face of the young man who sat on the terrace " +
                  "\nof the Hotel Magnifique at Cannes crept a look of furtive " +
                  "\nshame, the shifty, hangdog look which announces that " +
                  "\nan Englishman is about to talk French." ;

    boolean isWord = false;                                            // Indicates start of a word found
    int start = 0;                                                     // Index of word start
    StringBuffer reversedText = new StringBuffer();
    StringBuffer word = new StringBuffer();
    for(int i = 0 ; i  <text.length() ; ++i) {
      if(!isWord) {                                                    // If we are not in a word...
        if(Character.isLetter(text.charAt(i))) {                       // look for first letter of a word.
          word.append(text.charAt(i));                                 // and append it to word
          isWord = true;                                               // Flag that we are in a word
        } else {
          reversedText.append(text.charAt(i));
        }
      } else {                                                         // We are in a word
        if(Character.isLetter(text.charAt(i)) || text.charAt(i) == '\'') {
          word.append(text.charAt(i));                                 // Append to word
          continue;
        }
        else {                                                         // It is the end of the word
          reversedText.append(word.reverse());                         // so append the reversed word
          reversedText.append(text.charAt(i));                         // Don't forget the current character
          word.delete(0,word.length());                                // Delete the contents of word
          isWord = false;                                              // and reset word indicator
        }
      }
    }
    if(word.length() > 0)                                              // Is there a last word?
      reversedText.append(word.reverse());                             // If so append it - reversed of course.



    // Display the Reversed text
    System.out.println(reversedText);
  }
}


Output of Above Java Program
otnI eht ecaf fo eht gnuoy nam ohw tas no eht ecarret
fo eht letoH euqifingaM ta sennaC tperc a kool fo evitruf
emahs, eht ytfihs, godgnah kool hcihw secnuonna taht
na namhsilgnE si tuoba ot klat hcnerF.

[ Read More ]
Read more...

To Print dates in Formatted Way | Java Example

Posted by Admin at 5:18 AM – 0 comments
 
Define an array of ten String elements each containing an arbitrary string of the form "month/day/year";
for example,"10/29/99" or "12/5/01".
Analyze each element in the array and output the date represented in the form 29th October 1999

public class Dates {
  public static void main(String args[]) {
    String[] dates = new String[10];
    String[] monthNames = {
    "January", "February", "March", "April",
    "May", "June", "July", "August", "September",
    "October", "November", "December"
    };

    int[] daysInMonth = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
    String ending = "th";
    String dayStr = null;
    String monthStr = null;
    String yearStr = null;
    char separator = '/';
    int day = 0;
    int month = 0;
    int year = 0;
    int daysIncrement = 0;

    // Generate a set of arbitrary dates:
    for(int i = 0 ; i < dates.length ; ++i) {
      year = (int)(100.0*Math.random());                               // Random year value 00 to 99
      month = (int)(12.0*Math.random()) + 1;                           // Random month value 1 to 12

      // February in a leap year has 29 days in the month so we need to allow for an extra day.
      // Leap years are messy ...
      // A leap year is a year that is divisible by 4 and not by 100, or
      // a leap year is a century and the number of centuries is divisible by 4
      daysIncrement = (((year % 4 == 0) && !(year % 100 == 0)) || (year % 400 == 0)) && (month == 2) ? 1 : 0 ;

      day = (int)(Math.random()*(daysInMonth[month-1] + daysIncrement)) + 1;
      dates[i] = "" + day + separator + month + separator + (year<10 ? "0" :"") + year;
      System.out.println("Day is " + dates[i]);
    }

    // Now the set of dates has been generated, we can interpret and output it.
    int start = 0;                                                     // Word start index
    int end = 0;                                                       // Word end index

    System.out.println();
    for(String date : dates) {
      // Extract the day, month and year strings using the familiar method.
      start = 0;
      end = date.indexOf(separator,start);
      dayStr = date.substring(start, end);
      start = end + 1;
      end = date.indexOf(separator,start);
      monthStr = date.substring(start, end);
      start = end + 1;
      yearStr = date.substring(start);

      // Figure out whether "st", "nd", "rd", or "th", should be appended to the day.
      //  Single digit day is "st", "rd", "nd", for "1", "2", "3", and "th" otherwise.
      // Days "11" to "19" are all "th".
      // The remainder are "st", "rd", "nd", for last digit "1", "2", "3",
      // and "th" otherwise.
      if(dayStr.length() == 1)
        switch(dayStr.charAt(0)) {
          case '1':
            ending = "st";
            break;
          case '2':
            ending = "nd";
            break;
          case '3':
            ending = "rd";
            break;
          default:
            ending = "th";
        }
      else if(dayStr.charAt(0) == '1')
        ending = "th";
      else
        switch(dayStr.charAt(1)) {
          case '1':
            ending = "st";
            break;
          case '2':
            ending = "nd";
            break;
          case '3':
            ending = "rd";
            break;
          default:
            ending = "th";
        }

      // We can now output the date in the required format.
      // To output the month name string we must use monthStr to get an index to the monthNames array.
      System.out.println(dayStr + ending + " " +
           monthNames[monthStr.length() == 1 ? monthStr.charAt(0) - '1': 9 + monthStr.charAt(1) - '0'] +
           " " + "19" + yearStr);

      // The preceding would be easier using Integer class methods to convert
      // the day and month strings to integers.
      // We could index the monthNames array with the expression monthNames[Integer.parseInt(monthStr)]
      // The parseInt() method converts the String argument to an int value.
    }
  }
}


Output of Above Java Program
Day is 6/6/87
Day is 30/6/79
Day is 30/4/99
Day is 8/8/68
Day is 30/6/96
Day is 27/5/97
Day is 5/3/76
Day is 4/4/27
Day is 20/11/39
Day is 26/2/23

6th June 1987
30th June 1979
30th April 1999
8th August 1968
30th June 1996
27th May 1997
5th March 1976
4th April 1927
20th November 1939
26th February 1923
[ Read More ]
Read more...

To Extract the words from the Text and Sort them into Alphabetical Order

Posted by Admin at 5:05 AM – 0 comments
 
Write a program that sets up a String variable containing a paragraph of text of your choice.
Extract the words from the text and sort them into alphabetical order. Display the sorted list of words.
You could use a simple sorting method called the bubble sort. To sort an array into ascending order the process is as follows:
  •   Starting with the first element in the array, compare successive elements (0 and 1, 1 and 2, 2 and 3, and so on).
  •   If the first element of any pair is greater than the second, interchange the two elements.
  •   Repeat the process for the whole array until no interchanges are necessary. The array elements are now in ascending order.
This solution scans the string character by character to extract words. You cannot conveniently use a StringTokenizer object or the indexOf() method in the String class because a word can end with a space or a punctuation character such as a period or a comma. For simplicity, I have assumed that a single quote is always part of a word.

public class Sort {
  public static void main(String args[]) {
    // Declare the String that is to be sorted:
    String text = "Into the face of the young man who sat on the terrace " +
                  "of the Hotel Magnifique at Cannes crept a look of furtive " +
                  "shame, the shifty, hangdog look which announces that " +
                  "an Englishman is about to talk French." ;


    // Determine how many words there are.
    // A word is a sequence of letters that may include a single quote character.
    // Anything else is punctuation or spaces.
    int count = 0;                                                    // Counts number of words
    boolean isWord = false;                                            // Indicates start of a word found
    for (int i = 0 ; i < text.length() ; ++i) {
      if(isWord) {                                                     // If we have found a word...
        if(Character.isLetter(text.charAt(i)) || text.charAt(i) == '\'')
          continue;                                                    // ...pass over letters or single quote
        else                                                           // It is not a letter or single quote...
          isWord = false;                                              // so we have come to the end of the word
      }
      else if(Character.isLetter(text.charAt(i))) {
                                                                       // We have the first letter of a new word
          count++;                                                     // so increment word count
          isWord = true;                                               // and record we have found a word
      }
    }

    // Create the array of strings to contain all the words:
    String[] words = new String[count];

    // Now extract the words from the text
    int start = 0;                                                     // Position of first letter of a word
    int wordIndex = 0;                                                 // Current vacant words array element
    isWord = false;                                                    // Indicates when a word start is found
    for (int i = 0 ; i < text.length() ; ++i) {
      if(!isWord) {                                                    // If we are not in a word...
        if(Character.isLetter(text.charAt(i))) {                       // look for first letter of a word.
          start = i;                                                   // Record word start index
          isWord = true;                                               // We have a word
        }
      }
      else {                                                           // We are in a word
        if(Character.isLetter(text.charAt(i)) || text.charAt(i) == '\'')
          continue;                                                    // Still the same word so continue
        else {                                                         // It is the end of the word
          isWord = false;                                              // so reset word indicator
          words[wordIndex++] = text.substring(start,i);                // and extract the word
        }
      }
    }
    // If the text ends with a letter, we will not have stored the last word
    if(wordIndex < words.length)
      words[wordIndex] = text.substring(start);

    // Sort the array of words
    String temp = null;                                                // Stores a word reference
    boolean exchange = true;                                           // Indicate we exchanged a pair of words
    while(exchange) {
      exchange = false;                                                // No exchange so far
      for(int i = 1 ; i < words.length ; ++i) {                        // For each word starting with the second
        if(words[i-1].compareTo(words[i]) > 0) {                       // If the previous word is greater
          temp = words[i];                                             // exchange them
          words[i] = words[i-1];
          words[i-1] = temp;
          exchange = true;                                             // and record that exchange occurred
        }
      }
    }

    // Display the sorted array of words:
    for(String word : words) {
      System.out.println(word);
    }
  }
}



Output of Above Java Program
Cannes
Englishman
French
Hotel
Into
Magnifique
a
about
an
announces
at
crept
face
furtive
hangdog
is
look
look
man
of
of
of
on
sat
shame
shifty
talk
terrace
that
the
the
the
the
the
to
which
who
young

[ Read More ]
Read more...

To create a Rectangular Array containing a Multiplication Table | Java Example

Posted by Admin at 4:17 AM – 0 comments
 
Write a program to create a rectangular array containing a multiplication table from 1 x 1 up to 12 x 12.
Output the table as 13 columns with the numeric values right-aligned in the columns.
(The first line of output is the column headings, the first column with no heading, then the numbers 1 to 12 for the remaining columns. The first item in each of the succeeding lines is the row heading, which ranges from 1 to 12.)

public class Tables {
  public static void main(String[]args) {
    final int TABLE_SIZE = 12;
    // Declare the rectangular array to store the multiplication table:
    int[][] table = new int[TABLE_SIZE][TABLE_SIZE];

    // Fill in the array with the multiplication table:
    for(int i = 0 ; i < table.length ; ++i) {
      for(int j = 0 ; j < table[i].length ; ++j) {
        table[i][j] = (i+1)*(j+1);
      }
    }

    // Output the table heading
    System.out.print("      :");             // Row name column heading
    for(int j = 1 ; j <= table[0].length ; ++j) {
      System.out.print((j<10 ? "   ": "  ") + j);
    }
    System.out.println("\n-------------------------------------------------------");

    // Output the table contents
    // Each entry in the table should be four characters wide so we output
    // three spaces preceding values less than 10, two spaces preceding values
    // from 10 to 99 and one space for values exceeding 100.
    for(int i = 0 ; i < table.length ; ++i) {
      System.out.print("Row" + (i<9 ? "  ":" ") + (i+1) + ":");

      for(int j = 0; j < table[i].length; ++j) {
        System.out.print((table[i][j] < 10 ? "   " : table[i][j] < 100 ? "  " : " ") + table[i][j]);
      }
      System.out.println();
    }
  }
}


Output of Above Java Program
      :   1   2   3   4   5   6   7   8   9  10  11  12
-------------------------------------------------------
Row  1:   1   2   3   4   5   6   7   8   9  10  11  12
Row  2:   2   4   6   8  10  12  14  16  18  20  22  24
Row  3:   3   6   9  12  15  18  21  24  27  30  33  36
Row  4:   4   8  12  16  20  24  28  32  36  40  44  48
Row  5:   5  10  15  20  25  30  35  40  45  50  55  60
Row  6:   6  12  18  24  30  36  42  48  54  60  66  72
Row  7:   7  14  21  28  35  42  49  56  63  70  77  84
Row  8:   8  16  24  32  40  48  56  64  72  80  88  96
Row  9:   9  18  27  36  45  54  63  72  81  90  99 108
Row 10:  10  20  30  40  50  60  70  80  90 100 110 120
Row 11:  11  22  33  44  55  66  77  88  99 110 121 132
Row 12:  12  24  36  48  60  72  84  96 108 120 132 144
[ Read More ]
Read more...

To Create Annual Sheet using Array | Java Example

Posted by Admin at 4:10 AM – 0 comments
 
Create an array of String variables and initialize the array with the names of the months from January to December. Create an array containing 12 random decimal values between 0.0 and 100.0. Display the names of each month along with the corresponding decimal value. Calculate and display the average of the 12 decimal values.

public class Months {
  public static void main(String args[]) {
    // Initialize the months' array with names of the months of the year:
    String[] monthNames = {
                           "January"  , "February", "March"   , "April",
                           "May"      , "June"    , "July"    , "August",
                           "September","October"  , "November", "December"
                         };

    double average = 0.0;           // A variable used to find the average.

    // Declare an array which can contain the 12 random numbers:
    double[] numbers = new double[12];

    // Fill in the numbers' array with 12 numbers between 0.0 and 100.0, and print it out,
    // alongside each month. Also keep track of the sum of those numbers elements.

    for(int i = 0 ; i  < numbers.length ; ++i) {
      numbers[i] = 100.0*Math.random();
      System.out.println("In Month " + monthNames[i] + " number is " + numbers[i]);
      average += numbers[i];
    }
    average /= numbers.length;

    System.out.println("\nAverage of values in numbers is " + average);
  }
}



Output of Above Java Program
In Month January number is 2.62329136050351
In Month February number is 95.49823339063055
In Month March number is 58.978051814545786
In Month April number is 99.2117855806428
In Month May number is 49.808337007547145
In Month June number is 79.15664466990732
In Month July number is 13.451240158382593
In Month August number is 46.94383635492937
In Month September number is 83.73174198408276
In Month October number is 88.0275024074453
In Month November number is 10.300025142868542
In Month December number is 91.70504925022092

Average of values in numbers is 59.95297826014221

[ Read More ]
Read more...
Sunday, January 15, 2012

Java Program to generate a random sequence of capital letters that does not include vowels.

Posted by Admin at 9:47 AM – 0 comments
 
Write a program to generate a random sequence of capital letters that does not include vowels.

public class Capitals {
  public static void main(String args[])   {
    int counter = 0;                                                   // Counter for number of capitals generated.
    int numberToGenerate = 20;                                         // Number of capitals to generate.
    char symbol = 0;                                                   // Variable to store a random character.

    // While there are still letters to generate:
    while( counter < numberToGenerate ) {
      // Generate a random symbol between A and Z:
      // This relies on the fact that the codes for the letters are in a
      // contiguous sequence from 'A' to 'Z'. If we add 1 to 'A' we get the
      // code for 'B', if we add 2 we get 'C', and so on. Thus to create a
      // random capital letter from 'A' to 'Z' we can add a random integer
      // between 0 and 25 to 'A'.
      symbol = (char)(26*Math.random() + 'A');
      switch(symbol) {
        //Vowels ignored:
        case 'A':
        case 'E':
        case 'I':
        case 'O':
        case 'U':
          break;
        default:
          //Consonant displayed:
          System.out.print(symbol + " ");
          counter++;
          break;
      }
    }
  }
}



Output of Above Java Program
Q Y S K F N X T D X F F W R B V N J J V
[ Read More ]
Read more...

Java Program to Generate the Lottery Number between 1 to 49

Posted by Admin at 9:36 AM – 0 comments
 
 A lottery requires that you select six different numbers from the integers 1 to 49. Write a program to do this for you and generate five sets of entries.

public class Lottery {
  public static void main(String[]args) {
    int setCount = 5;                                                  // Number of sets of lucky numbers.
    int setSize = 6;                                                   // Number of lucky numbers in the set.
    int range = 49;                                                    // Assume selecting integers between 1 and range.
    int lucky;                                                         // Holds a lucky number candidate.
    int luckyCount;                                                    // Holds count of lucky numbers in a set.

    for(int i = 0 ; i < setCount ; ++i) {
      int lucky1 = 0;                                                  // Lucky numbers for the set of 6.
      int lucky2 = 0;
      int lucky3 = 0;
      int lucky4 = 0;
      int lucky5 = 0;
      int lucky6 = 0;

      luckyCount = 0;                                                  // Count of numbers found in the current set
      while(luckyCount < setSize) {
       // Generate a lucky number between 0 and 48 and add 1:
       lucky = (int)(range*Math.random()) + 1;
        switch(luckyCount) {
          case 0:                                                      // It is the first one
            lucky1 = lucky;                                            // so just store it
            luckyCount++;                                              // and increment the count
            break;
          case 1:                                                      // For the second we must
            if(lucky != lucky1) {                                      // check that it is different from the first
              lucky2 = lucky;                                          // It is, so store it
              luckyCount++;                                            // and increment the count
            }
            break;
          case 2:                                                      // For the third we check aginst the previous two
            if(lucky != lucky1 && lucky != lucky2) {
              lucky3 = lucky;
              luckyCount++;
            }
            break;
           case 3:                                                     // Check against the previous three...
            if(lucky != lucky1 && lucky != lucky2 && lucky != lucky3) {
              lucky4 = lucky;
              luckyCount++;
            }
            break;
           case 4:                                                     // Check against the previous four...
            if(lucky != lucky1 && lucky != lucky2 && lucky != lucky3 && lucky != lucky4) {
              lucky5 = lucky;
              luckyCount++;
            }
            break;
           case 5:                                                     // Check against the previous five...
            if(lucky != lucky1 && lucky != lucky2 && lucky != lucky3 && lucky != lucky4 && lucky != lucky5) {
              lucky6 = lucky;
              luckyCount++;
            }
            break;
        }
      }

      System.out.print("\nSet " + (i + 1) + ":");                      // Identify the set

      System.out.print(" " + lucky1 + " " + lucky2  + " " + lucky3  +  // and output the numbers
                       " " + lucky4  + " " + lucky5  + " " + lucky6);

    }
  }
}


Output of Above Java Program
Set 1: 32 45 6 46 11 5
Set 2: 21 24 3 18 45 33
Set 3: 13 25 37 2 31 46
Set 4: 19 10 12 32 7 29
Set 5: 47 48 2 15 40 20


If you want to be sure the numbers line up in columns you could use a  rather more complicated statement here instead of the above:
 System.out.print((lucky1>9 ? " " :"  ") + lucky1 +
                       (lucky2>9 ? " " :"  ") + lucky2 +
                       (lucky3>9 ? " " :"  ") + lucky3 +
                       (lucky4>9 ? " " :"  ") + lucky4 +
                       (lucky5>9 ? " " :"  ") + lucky5 +
                      (lucky6>9 ? " " :"  ") + lucky6);
  This makes use of the conditional operator to output an extra space when a lucky number is a single digit.
[ Read More ]
Read more...

Program to Calculate the Prime numbers until it reaches to Given Number

Posted by Admin at 9:30 AM – 1 comments
 
 When testing whether an integer is a prime, it is sufficient to try to divide by integers up to and including the square root of the number being tested.

public class Primes {
  public static void main(String args[]) {
    int maxValue = 50;                                                 // The maximum value to be checked.

    // Check all values from 2 to maxValue:
    OuterLoop:
    for(int i = 2 ; i <= maxValue ; ++i) {
      // Try dividing by all integers from 2 to square root of i:
      for(int j = 2 ; j <= Math.sqrt(i) ; ++j) {
        if(i%j == 0)                                                   // This is true if j divides exactly
          continue OuterLoop;                                          // so exit the loop.
      }
      // We only get here if we have a prime:
      System.out.println(i);                                           // so output the value.
    }
  }
}

Output of Above Java Program
2
3
5
7
11
13
17
19
23
29
31
37
41
43
47

[ Read More ]
Read more...

Java Program to display a random choice from a set of six choices for breakfast

Posted by Admin at 9:26 AM – 0 comments
 
Write a program to display a random choice from a set of six choices for breakfast
(you could use any set—for example, scrambled eggs, waffles, fruit, cereal, toast, or yogurt).

public class Choice {
  public static void main(String args[]) {
    // Use an integer to determine the choice:
    int myChoice = 0;

    // Select a random value for myChoice between 0 and 5:
    myChoice = (int)(6.0*Math.random());

    // The above line ensures each integer from 0 to 5 is equiprobable.
    // Multiplying the value produced by random() by 6.0 results in a value
    // from 0.0 to 5.99999
    // Values from 0 to 0.99999 becomes 0, from 1.00 to 1.99999 becomes 1,
    // and so on, with values from 5.0 to 5.99999 becoming 5.

    // Print the appropriate Breakfast Choice depending on value myChoice:
    switch(myChoice) {
      case 0:
        System.out.println("Breakfast choice is scrambled eggs");
        break;
      case 1:
        System.out.println("Breakfast choice is waffles");
        break;
      case 2:
        System.out.println("Breakfast choice is fruit");
        break;
      case 3:
        System.out.println("Breakfast choice is cereal");
        break;
      case 4:
        System.out.println("Breakfast choice is toast");
        break;
      case 5:
        System.out.println("Breakfast choice is yogurt");
        break;
    }
  }
}


Output of Above Java Program
Breakfast choice is yogurt
[ Read More ]
Read more...

Java Program to Calculate and output the amount of tax to pay in dollars and cents

Posted by Admin at 9:21 AM – 0 comments
 
Write a program that defines a floating-point variable initialized with a dollar value for your income and a second floating-point variable initialized with a value corresponding to a tax rate of 35 percent. Calculate and output the amount of tax you must pay with the dollars and cents stored as separate integer values (use two variables of type int to hold the tax, perhaps taxDollars and taxCents).

public class TaxCalc {
  public static void main(String args[]) {
    double income = 87562.34;
    double taxRate = 0.35;                                             // 35%  corresponds to 0.35
    double tax = income*taxRate;

    int taxDollars = (int)tax;
    int taxCents = (int)Math.round((tax - taxDollars)*Math.pow(10.0, 2.0));

    // Output the results:
    System.out.println("Gross income is $" + (int)income +"." + (int)Math.round((income - (int)income)*Math.pow(10.0, 2.0)));
    System.out.println("Tax to pay is " + taxDollars + " dollars and " + taxCents + " cents.");

 /*
    The output statements above show how you can put arithmetic expressions as part of the argument
    to the println() method. The compiler takes care of converting the values that result from the
    arithmetic expressions to a string.
 */
  }
}

Output of Above Java  Program
Gross income is $87562.34
Tax to pay is 30646 dollars and 82 cents.
[ Read More ]
Read more...

Java Program to successively Multiply a Number by 2 and Display it

Posted by Admin at 5:03 AM – 0 comments
 
Write a console program to define and initialize a variable of type byte to 1,and then successively multiply it by 2 and display its value 8 times.Explain the reason for the last result.

public class ByteTest {     // Ensure classes/variables have distinctive names.
  public static void main(String args[]) {
    // Initialize variable data of type byte to 1:
    byte data = 1;

    data *= 2; // Multiply by 2: 1st time
    System.out.println("data = " + data);
    data *= 2; // Multiply by 2: 2nd time
    System.out.println("data = " + data);
    data *= 2; // Multiply by 2: 3rd time
    System.out.println("data = " + data);
    data *= 2; // Multiply by 2: 4th time
    System.out.println("data = " + data);
    data *= 2; // Multiply by 2: 5th time
    System.out.println("data = " + data);
    data *= 2; // Multiply by 2: 6th time
    System.out.println("data = " + data);
    data *= 2; // Multiply by 2: 7th time
    System.out.println("data = " + data);

    // Value of data is now out of the byte range, which is -128 to +127
    // At this point we have stored 128 in data - in binary 1000 0000
    // which corresponds to -128 as a value of type byte.

    data *= 2; // Multiply by 2: 8th time
    System.out.println("data = " + data);

    // Don't forget that these integer calculations will be done
    // with 32 bits precision. The result is then stored in data taking the
    // low-order 8 bits of the result as the value to be stored.
    // Since we multiply the -128 value by 2, the result is -256. In binary the
    // low-order 8 bits for this value are zero.

    // This calculation would normally be done in a loop ( a subject covered in chapter 3).
  }
}

[ Read More ]
Read more...

Java Program to find that given number is Palindrome or not

Posted by Admin at 2:44 AM – 0 comments
 
Here is program to find that given number is Palindrome or not.
A palindrome number, is the number that can be read the same way in either direction.
import java.io.*;

class palindrome {
 public static void main(String [] args) throws IOException{
  try{
   BufferedReader obc=new BufferedReader (new InputStreamReader(System.in));
   int r,n1,n2;
   int rev=0;
   System.out.println("Enter the number: ");
   n1=Integer.parseInt(obc.readLine());
   n2=n1;
   
   while(n1>0) {
    r=n1%10;
    rev=rev*10+r;
    n1=n1/10;
   }
   
   if(rev==n2) {
    System.out.println("The number is Palindrome Number.");
   } else {
    System.out.println("The number is not a Palindrome Number.");
   }
  } catch(IOException e) {
   System.out.println("Wrong number entered.");
  }
 }
}


Output of Above Java Program
Enter the number:
12321
The number is Palindrome Number.


[ Read More ]
Read more...
Saturday, January 14, 2012

Java Program to Demonstrate the Use of Pre and Post Operator

Posted by Admin at 11:03 PM – 0 comments
 
Here is a Java Program to Demonstrate the Use of Pre and Post Operator.

   class prepost {
        public static void main(String args[]){
          int i=50;
          System.out.println("The value is "+i +".");
          System.out.println("The value of i++ is "+ i++ +".");
          System.out.println("The value of ++i is "+ ++i +".");
          System.out.println("The value of ++i is "+ ++i +".");
        }
    }


Output of Above Java Program:
The value is 50.
The value of i++ is 50.
The value of ++i is 52.
The value of ++i is 53.

[ Read More ]
Read more...

Java Program to Reverse the Given Number

Posted by Admin at 10:48 PM – 0 comments
 
Here is a Java Program to Reverse the Given Number

import java.io.*;

class reverse{
 public static void main(String [] args) {
  try {
   BufferedReader obc=new BufferedReader (new InputStreamReader(System.in));
   int n,r;
   int rev=0;
   System.out.println("Enter the number: ");
   n=Integer.parseInt(obc.readLine());
   
   while(n>0) {
    r=n%10;
    rev=rev*10+r;
    n=n/10;
   }

   System.out.println("The reverse number is "+rev+".");
  
  } catch(IOException e) {
    System.out.println("Wrong number entered.");
  }
 }
}

Output of Above Java Program
Enter the number:
12345
The reverse number is 54321.

[ Read More ]
Read more...

Java Program to Print Number in the Given Data Type

Posted by Admin at 10:26 PM – 0 comments
 
Here is Java Program to print number given in the data types

 public class second{
    public static void main(String[] args){
  int n;
        float fl;
        double d;

        n=50;
        fl=50.08f;
        d=12345.123;
        
 System.out.println("The given integer is = "+n);
        System.out.println("The given float is = "+fl);
        System.out.println("The given double is = "+d);
    }
 }


Output of above Java Programs
The given integer is = 50
The given float is = 50.08
The given double is = 12345.123
[ Read More ]
Read more...

Program to Demonstrate Skipping using Continue

Posted by Admin at 12:35 PM – 0 comments
 
Here is Program to Demonstrate Skipping using Continue Statement.
import java.io.*;

class skip {
  public static void main(String [] args) {
  int a=1;
  while(a<50) {
   if(a>20 && a<=35) {
    a++;
    continue;
   } 
  
   System.out.print("\t"+a);
   a++;
  }
 }
}  

Output of Above Java Program
  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 36 37 38 39 40 41 42 43 44 45 46 47 48 49
[ Read More ]
Read more...
Older Posts
Subscribe to: Posts ( Atom )

List of Java Programs

  • Java Program to check Greater between the Two Number
  • Java Program to find that given number is Palindrome or not
  • Java Program to Demonstrate the Use of Pre and Post Operator
  • Java Program to Reverse the Given Number
  • Java Program to Print Number in the Given Data Type
  • Program to Demonstrate Skipping using Continue
  • Program to find whether entered character is a vowel or Consonant
  • Java Program to Calculate the Sum of Digits of Given Number
  • How to swap two numbers using only two variables
  • Checking the Given Number is Armstrong or Not
  • Average an Array of Values
  • Display ASCII Code Instead of Character
  • Comparison of Two Variable using If
  • Printing Table In java using While Loop
  • Generate Random Number Using Math.Random Function
  • To Find roots of Quadratic Equation
  • Performing Arithmetic Opration on Two Variable
  • Concatenation of Two String in Java
  • Command Line Argument in JAVA
  • Java Hello World Program
  • Calculate Circle Perimeter | Java Program
  • Calculate the Area of Circle | Java Program
  • To Find Whether Given Year is a Leap Year or not
  • Popular
  • Recent
  • Archives

Total Pageviews

Sparkline

Followers

Popular Posts of This Week

Powered by Blogger.

Archives

  • ▼  2014 ( 4 )
    • ▼  August ( 4 )
      • Java program to create a Binary Heap and Perform v...
      • Create an Adjacency matrix Graph and perform Add a...
      • To Sort an Interger Array using Shell Sort
      • Sort an Integer array with Bucket Sort
  • ►  2013 ( 6 )
    • ►  August ( 1 )
    • ►  April ( 5 )
  • ►  2012 ( 673 )
    • ►  November ( 9 )
    • ►  October ( 223 )
    • ►  September ( 272 )
    • ►  August ( 2 )
    • ►  June ( 1 )
    • ►  February ( 67 )
    • ►  January ( 99 )
 

Our Blogs

  • Linux Tutorial
  • C Programming Tutorial

Labels

  • Agile Methodology ( 1 )
  • Algorithm ( 3 )
  • AntiSamy ( 1 )
  • Arithmetic Operation ( 1 )
  • Array Example ( 9 )
  • ArrayList Examples ( 11 )
  • Average an Array of Values ( 1 )
  • Barcode Example ( 1 )
  • Basic Java Programs ( 34 )
  • Bing API Example ( 2 )
  • BitSet Example ( 1 )
  • Boolean Example ( 1 )
  • Bouncy Castle API ( 1 )
  • Break Statement ( 2 )
  • BufferedReader Example ( 2 )
  • Calendar Example ( 1 )
  • Chart Generation Example ( 1 )
  • Command Line Argument ( 1 )
  • Comparator Example ( 1 )
  • Concatenation of String ( 1 )
  • Continue Statement ( 1 )
  • Control Structure ( 1 )
  • Copy File Example ( 1 )
  • CRC Example ( 1 )
  • CSV Example ( 6 )
  • Data Structure ( 5 )
  • Date Example ( 2 )
  • Directory Example ( 1 )
  • Do - While Loop Example ( 1 )
  • Domino Database ( 1 )
  • Email Example ( 8 )
  • Encryption Example ( 3 )
  • Excel Example ( 15 )
  • Factorial Example ( 1 )
  • File Upload Example ( 1 )
  • Find Roots of Quadratic Equation ( 1 )
  • FTP Example ( 2 )
  • Graph Examples ( 1 )
  • Greater between Two Numbers ( 1 )
  • GSON Library ( 1 )
  • HashMap Example ( 1 )
  • HashSet Example ( 1 )
  • Hello World Program ( 1 )
  • If Condition ( 2 )
  • Inner Class Example ( 1 )
  • iText Example ( 3 )
  • JAR File ( 1 )
  • JAVA Applet ( 1 )
  • Java Applications ( 1 )
  • Java AWT Example ( 9 )
  • Java Certification ( 1 )
  • Java Class Examples ( 15 )
  • Java Collection Example ( 1 )
  • Java Command Example ( 4 )
  • Java Constructor Examples ( 1 )
  • Java Currency Example ( 1 )
  • Java Database Example ( 3 )
  • Java Date and Time Example ( 3 )
  • Java DateFormat Example ( 3 )
  • Java Examples ( 2 )
  • Java Exception Example ( 5 )
  • Java File Example ( 22 )
  • Java GUI Example ( 1 )
  • Java Image Examle ( 3 )
  • Java Inheritance Example ( 3 )
  • Java Input Output Example ( 1 )
  • Java IO Example ( 3 )
  • Java Jar Example ( 1 )
  • Java JSON Example ( 3 )
  • Java Mail Examples ( 4 )
  • Java Map Example ( 5 )
  • Java MapReduce Example ( 2 )
  • Java MultiThreading Example ( 7 )
  • Java Network Example ( 9 )
  • Java Package ( 1 )
  • Java Programs ( 1 )
  • Java RMI ( 1 )
  • Java Robot Class Examples ( 2 )
  • Java Runtime Example ( 1 )
  • Java Swing Example ( 9 )
  • Java Util Example ( 1 )
  • Java Vector Example ( 4 )
  • Java Voice Example ( 1 )
  • Java Webservice Example ( 1 )
  • Java XML Example ( 3 )
  • Java Zip Class Examples ( 2 )
  • JDBC ( 9 )
  • JDK Version Comparison ( 1 )
  • JFrame Example ( 3 )
  • JOptionPane Dialog Example ( 1 )
  • JPanel Example ( 1 )
  • JSP Example ( 2 )
  • JSTL Example ( 1 )
  • jUnit Example ( 2 )
  • LinkedList Example ( 2 )
  • List Example ( 1 )
  • Long Variable ( 1 )
  • Lottery Nubmer ( 1 )
  • MD5 Hashing Example ( 3 )
  • Memory Management Example ( 1 )
  • Method Override ( 1 )
  • MIDI Sound ( 8 )
  • Module Operator Example ( 2 )
  • Multiplication Table ( 1 )
  • Observer Interface Example ( 1 )
  • Operator Example ( 5 )
  • Pagination ( 1 )
  • Palindrome Number ( 1 )
  • Pass By Reference Example ( 1 )
  • Pass By Value Example ( 1 )
  • PDF File Example ( 3 )
  • PDF Generation Example ( 4 )
  • Pre and Post Operator ( 2 )
  • Prime Number ( 3 )
  • Progress Bar Example ( 1 )
  • Property List Example ( 2 )
  • Random Function ( 7 )
  • Recursion Example ( 2 )
  • Regex Example ( 2 )
  • Remote Host Example ( 2 )
  • Robot Class ( 4 )
  • Searching Example ( 3 )
  • Slideshow ( 1 )
  • Sorting Example ( 7 )
  • SpringLayout Example ( 1 )
  • Stack Example ( 4 )
  • Static Variable ( 1 )
  • StreamTokenizer Example ( 2 )
  • String Example ( 19 )
  • Struts2 Example ( 1 )
  • Sum of Digits ( 1 )
  • Swap Two Numbers ( 1 )
  • Switch Case ( 3 )
  • Tapestry Components ( 1 )
  • Thumbnail Example ( 2 )
  • TimerTask Example ( 2 )
  • To Calculate Volume ( 1 )
  • To Check Armstrong Number ( 1 )
  • Tree Example ( 1 )
  • TreeMap Example ( 1 )
  • TreeSet Example ( 1 )
  • Two Dimensional Array Example ( 1 )
  • UUID ( 1 )
  • Validation Example ( 2 )
  • Variable Casting ( 1 )
  • While Loop ( 1 )
  • XML Parsing ( 7 )
  • XSS Attacks ( 1 )
  • Zip File ( 15 )

Popular Posts

 
 
© 2011 Java Programs and Examples with Output | Designs by Web2feel & Fab Themes

Bloggerized by DheTemplate.com - Main Blogger