Showing posts with label Example program. Show all posts

Factorial Program using Recursion

Sunday, 5 July 2015
Posted by Unknown

class Factorial 
{
     int fact(int n) 
     {
          int result;
          if(n==1) return 1;
          result = fact(n-1) * n;
          return result;
     }
}

class Recursion 
{
     public static void main(String args[]) 
     {
          Factorial f = new Factorial();
          System.out.println("Factorial of 4 is " + f.fact(4));
     }
}

Output:

Factorial of 4 is 24
class ContinueLabel 
{
     public static void main(String args[]) 
     {
         outer: for (int i=0; i<10; i++) 
         {
             for(int j=0; j<10; j++) 
             {
                  if(j > i) 
                  {
                       System.out.println();
                       continue outer;
                  }
                  System.out.print(" " + (i * j));
             }
         }
     System.out.println();
     }
}

Output:

class Continue 
{
     public static void main(String args[]) 
     {
          for(int i=0; i<10; i++) 
          {
                System.out.print(i + " ");
                if (i%2 == 0) continue;
                System.out.println("");
          }
     }
}

Output:

Simple Arithmetic Operators

Sunday, 28 June 2015
Posted by Unknown

class arithmetic
{
    public static void main(String args[])
    {
        short x = 8;
        int y = 2;
        float a = 10.5f;
        float b = 6f;
        System.out.println("Addition: "+(x+y));
        System.out.println("Subtraction: "+(x-y));
        System.out.println("Multiplication: "+(x*y));
        System.out.println("Division: "+(x/y));
        System.out.println("Modulus: "+(x%y));
        System.out.println("Floating point Division: "+(a/b));
    }
}

Output:

Addition: 10
Subtraction: 6
Multiplication: 16
Division: 4
Modulus: 0
Floating point Division: 1.75

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
class palindrome
{
    public static void main(String[] args)
    {
        try
   {
            System.out.print("Enter a number: ");
  BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            String num=br.readLine();
            int no=Integer.parseInt(num);
            int temp=no;
            int digit=0,ld;
            while(no!=0)
            {
                ld=no%10;
                digit=digit*10+ld;
                no=no/10;
            }
            if(temp==digit)
            {
                System.out.println("Palindrome number");
            }
            else
     {
                System.out.println("Not a palindrome number");
            }
        }
   catch (IOException | NumberFormatException ex)
   {
       }
    }
}

Output:

Enter a number: 123
Not a palindrome number

Enter a number: 12321
Palindrome number
 

import java.io.BufferedReader;
import java.io.InputStreamReader;
class Reverse
{
    public static void main(String[] args)
    {
        try
   {
            System.out.print("Enter string : ");
  BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
            String str=in.readLine();
            for(int i=str.length()-1;i>=0;i--)
            {
              System.out.print(str.charAt(i));
            }
       }
   catch (Exception ex)
   {
      }
    }
}

Output:

Enter string : VIJAY 
YAJIV
import java.util.Scanner;
class fibonacci
{
  public static void main(String[] args)
    {
        System.out.print("Enter the number to display fibonicci series:  ");
        Scanner in=new Scanner(System.in);
        int num=in.nextInt();
        int a=0,b=1,c=0,i=0;
        while(i!=num)
        {
            System.out.println(c);
            a=b;
            b=c;
            c=a+b;
            i++;         
        }
    }
}

Output:

Find Real Roots of 3 Numbers

Friday, 26 June 2015
Posted by Unknown


import java.util.Scanner;
class solutions 
{
         public static void main(String[] args) 
        { 
                int a,b,c; 
                double x,y; 
                Scanner s=new Scanner(System.in); 
                System.out.println("Enter the values of a, b, c:");                        
                a=s.nextInt(); 
                b=s.nextInt(); 
                c=s.nextInt(); 
                int k=(b*b)-4*a*c; 
                if(k<0) 
                { 
                        System.out.println("No real roots");                                
                } 
                else 
                { 
                        double l=Math.sqrt(k); 
                        x=(-b-l)/2*a; 
                        y=(-b+l)/2*a; 
                        System.out.println("Roots of given equation:"+x+" 
"+y);                                
                } 
        } 
}


Output:

Enter the values of a, b, c:
5
5
2
No real roots

Color Transparency

Friday, 19 June 2015
Posted by Unknown
import java.awt.*;
import javax.swing.*;
import javax.swing.event.*;
public class TransparencyDemo extends JPanel 
{
    public static void main(String[] args) 
    {
        JFrame window = new JFrame("TransparencyDemo");
        TransparencyDemo content = new TransparencyDemo();
        window.setContentPane(content);
        window.pack(); 
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        window.setLocation( (screenSize.width - window.getWidth())/2,
                (screenSize.height - window.getHeight())/2 );
        window.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
        window.setVisible(true);
    }
    private JSlider triangleTransparency;
    private JSlider ovalTransparency;
    private JSlider rectangleTransparency;
    private JSlider textTransparency;

    private Font textFont = new Font("Serif",Font.BOLD,42);

    private JPanel display = new JPanel() {
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            Color triangleColor = new Color(255,0,0,triangleTransparency.getValue());
            Color ovalColor = new Color(0,255,0,ovalTransparency.getValue());
            Color rectangleColor = new Color(0,0,255,rectangleTransparency.getValue());
            Color textColor = new Color(0,0,0,textTransparency.getValue());
            g.setColor(triangleColor);
            g.fillPolygon(new int[] { scaleX(0.25), scaleX(0.7), scaleX(0.1) },
                    new int[] { scaleY(0.1), scaleY(0.7), scaleY(0.7) },
                    3);
            g.setColor(ovalColor);
            g.fillOval(scaleX(0.3),scaleY(0.45),getWidth()/2,getHeight()/2);
            g.setColor(rectangleColor);
            g.fillRect(scaleX(0.4),scaleY(0.15),getWidth()/2,getHeight()/2);
            FontMetrics metrics = g.getFontMetrics(textFont);
            int lineWidth1 = metrics.stringWidth("Transparency");
            int lineWidth2 = metrics.stringWidth("Demo");
            int textHeight = metrics.getHeight() + metrics.getAscent();
            int topSkip = (getHeight() - textHeight) / 2;
            int leftSkip1 = (getWidth() - lineWidth1) / 2;
            int leftSkip2 = (getWidth() - lineWidth2) / 2;
            g.setColor(textColor);
            g.setFont(textFont);
            g.drawString("Transparency", leftSkip1, topSkip + metrics.getAscent());
            g.drawString("Demo", leftSkip2, topSkip + metrics.getAscent() + metrics.getHeight());
        }
        private int scaleX(double x) {
            return (int)(x * getWidth());
        }
        private int scaleY(double y) {
            return (int)(y * getHeight());
        }
    };
   
    private ChangeListener listener = new ChangeListener() {
        public void stateChanged(ChangeEvent arg0) {
            display.repaint();
        }
    };

    public TransparencyDemo() {
        setLayout(new BorderLayout(3,3));
        setBorder(BorderFactory.createLineBorder(Color.GRAY,2));
        setBackground(Color.GRAY);
        display.setBackground(Color.WHITE);
        display.setPreferredSize(new Dimension(400,300));
        add(display,BorderLayout.CENTER);
        JPanel bottom = new JPanel();
        bottom.setLayout(new GridLayout(4,2,3,3));
        add(bottom,BorderLayout.SOUTH);
        bottom.add( new JLabel("  Triangle Transparency:") );
        triangleTransparency = new JSlider(0,255);
        triangleTransparency.addChangeListener(listener);
        bottom.add( triangleTransparency );
        bottom.add( new JLabel("  Oval Transparency:") );
        ovalTransparency = new JSlider(0,255);
        ovalTransparency.addChangeListener(listener);
        bottom.add( ovalTransparency );
        bottom.add( new JLabel("  Rectangle Transparency:") );
        rectangleTransparency = new JSlider(0,255);
        rectangleTransparency.addChangeListener(listener);
        bottom.add( rectangleTransparency );
        bottom.add( new JLabel("  Text Transparency:") );
        textTransparency = new JSlider(0,255);
        textTransparency.addChangeListener(listener);
        bottom.add( textTransparency );
    }
}

Output:

Stroke Program

Posted by Unknown
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class StrokeDemo extends JPanel 
{
    public static void main(String[] args) 
    {
        JFrame window = new JFrame("Click and Drag; Right-click for Rectangles");
        StrokeDemo content = new StrokeDemo();
        window.setContentPane(content);
        window.pack(); 
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        window.setLocation( (screenSize.width - window.getWidth())/2,
                (screenSize.height - window.getHeight())/2 );
        window.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
        window.setVisible(true);
    }

    private class Display extends JPanel 
    {
        Stroke stroke;  // The stroke used for drawing in this panel.
        boolean antialiased;   // Should antialiasing be used?
        boolean drawLine = true;   // Should a line be drawn, or a rectangle?
        int x1, y1, x2, y2;  // Endpoints of line or corners of rectangle.
        Display(Stroke s, boolean a) 
        {
            stroke = s;
            antialiased = a;
            x1 = y1 = 15;
            x2 = 80;
            y2 = 85;
            setPreferredSize(new Dimension(100,100));
            setBackground(Color.WHITE);
        }
        public void paintComponent(Graphics g) 
        {
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D)g;
            g2.setStroke(stroke);
            if (antialiased) 
            {
                g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                        RenderingHints.VALUE_ANTIALIAS_ON);
            }
            if (drawLine)
                g2.drawLine(x1,y1,x2,y2);
            else 
            {
                int a = Math.min(x1,x2);
                int b = Math.min(y1,y2);
                int w = Math.abs(x1 - x2);
                int h = Math.abs(y1 - y2);
                g2.drawRect(a,b,w,h);
            }
        }
    }
    private class MouseHandler implements MouseListener, MouseMotionListener
    {
        public void mousePressed(MouseEvent e) 
        {
            for (int i = 0; i < 5; i++)
                for (int j = 0; j < 3; j++) 
                {
                    displays[i][j].x1 = e.getX();
                    displays[i][j].x2 = e.getX();
                    displays[i][j].y1 = e.getY();
                    displays[i][j].y2 = e.getY();
                    displays[i][j].drawLine = ! e.isMetaDown();
                    displays[i][j].repaint();
                }
        }
        public void mouseDragged(MouseEvent e) 
        {
            for (int i = 0; i < 5; i++)
                for (int j = 0; j < 3; j++) 
                {
                    displays[i][j].x2 = e.getX();
                    displays[i][j].y2 = e.getY();
                    displays[i][j].repaint();
                }
        }
        public void mouseReleased(MouseEvent e) { }
        public void mouseMoved(MouseEvent e) { }
        public void mouseClicked(MouseEvent e) { }
        public void mouseEntered(MouseEvent e) { }
        public void mouseExited(MouseEvent e) { }
    }

    private Display[][] displays = new Display[5][3];
    public StrokeDemo() 
    {
        setLayout(new GridLayout(3,5,3,3));
        setBorder(BorderFactory.createLineBorder(Color.GRAY,3));
        setBackground(Color.GRAY);
        displays[0][0] = new Display(new BasicStroke(1), false);
        displays[1][0] = new Display(new BasicStroke(2), false);
        displays[2][0] = new Display(new BasicStroke(5), false);
        displays[3][0] = new Display(new BasicStroke(10), false);
        displays[4][0] = new Display(new BasicStroke(20), false);
        displays[0][1] = new Display(new BasicStroke(1,
                BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND), true);
        displays[1][1] = new Display(new BasicStroke(2,
                BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND), true);
        displays[2][1] = new Display(new BasicStroke(5,
                BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND), true);
        displays[3][1] = new Display(new BasicStroke(10,
                BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND), true);
        displays[4][1] = new Display(new BasicStroke(20,
                BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND), true);
        displays[0][2] = new Display(new BasicStroke(1, BasicStroke.CAP_BUTT,
                BasicStroke.JOIN_BEVEL, 10, new float[] {5,5}, 0), true);
        displays[1][2] = new Display(new BasicStroke(2, BasicStroke.CAP_BUTT,
                BasicStroke.JOIN_BEVEL, 10, new float[] {5,5}, 0), true);
        displays[2][2] = new Display(new BasicStroke(5, BasicStroke.CAP_BUTT,
                BasicStroke.JOIN_BEVEL, 10, new float[] {5,5}, 0), true);
        displays[3][2] = new Display(new BasicStroke(10, BasicStroke.CAP_BUTT,
                BasicStroke.JOIN_BEVEL, 10, new float[] {5,5}, 0), true);
        displays[4][2] = new Display(new BasicStroke(20, BasicStroke.CAP_BUTT,
                BasicStroke.JOIN_BEVEL, 10, new float[] {5,5}, 0), true);
        MouseHandler listener = new MouseHandler();
        for (int row = 0; row < 3; row++)
            for (int col = 0; col < 5; col++) 
            {
                add(displays[col][row]);
                displays[col][row].addMouseListener(listener);
                displays[col][row].addMouseMotionListener(listener);
            }
    }
}

Output:

import java.awt.*;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
public class StatesAndCapitalsTableDemo extends JPanel 
{
    public static void main(String[] args) 
    {
        JFrame window = new JFrame("Trivial Table Demo");
        StatesAndCapitalsTableDemo content = new StatesAndCapitalsTableDemo();
        window.setContentPane(content);
        window.setSize( new Dimension(350,300) );
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        window.setLocation( (screenSize.width - window.getWidth())/2,
                (screenSize.height - window.getHeight())/2 );
        window.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
        window.setVisible(true);
    }

    public StatesAndCapitalsTableDemo() 
    {
        String[] columnHeads = new String[] { "State", "Capital City" };
        JTable table = new JTable(statesAndCapitals, columnHeads);
        setLayout(new BorderLayout());
        add( new JScrollPane(table), BorderLayout.CENTER );
    }

    private static String[][] statesAndCapitals = new String[][] 
    {
        { "Alabama", "Montgomery" },
        { "Alaska", "Juneau" },
        { "Arizona", "Phoenix" },
        { "Arkansas", "Little Rock" },
        { "California", "Sacramento" },
        { "Colorado", "Denver" },
        { "Connecticut", "Hartford" },
        { "Delaware", "Dover" },
        { "Florida", "Tallahassee" },
        { "Georgia", "Atlanta" },
        { "Hawaii", "Honolulu" },
        { "Idaho", "Boise" },
        { "Illinois", "Springfield" },
        { "Indiana", "Indianapolis" },
        { "Iowa", "Des Moines" },
        { "Kansas", "Topeka" },
        { "Kentucky", "Frankfort" },
        { "Louisiana", "Baton Rouge" },
        { "Maine", "Augusta" },
        { "Maryland", "Annapolis" },
        { "Massachusetts", "Boston" },
        { "Michigan", "Lansing" },
        { "Minnesota", "St. Paul" },
        { "Mississippi", "Jackson" },
        { "Missouri", "Jefferson City" },
        { "Montana", "Helena" },
        { "Nebraska", "Lincoln" },
        { "Nevada", "Carson City" },
        { "New Hampshire", "Concord" },
        { "New Jersey", "Trenton" },
        { "New Mexico", "Santa Fe" },
        { "New York", "Albany" },
        { "North Carolina", "Raleigh" },
        { "North Dakota", "Bismarck" },
        { "Ohio", "Columbus" },
        { "Oklahoma", "Oklahoma City" },
        { "Oregon", "Salem" },
        { "Pennsylvania", "Harrisburg" },
        { "Rhode Island", "Providence" },
        { "South Carolina", "Columbia" },
        { "South Dakota", "Pierre" },
        { "Tennessee", "Nashville" },
        { "Texas", "Austin" },
        { "Utah", "Salt Lake City" },
        { "Vermont", "Montpelier" },
        { "Virginia", "Richmond" },
        { "Washington", "Olympia" },
        { "West Virginia", "Charleston" },
        { "Wisconsin", "Madison" },
        { "Wyoming", "Cheyenne" }
    };
}

Output:

import javax.swing.*;
public class SimpleJLabelExample 
{
  public static void main(String[] args) 
  {
    JLabel label = new JLabel("A Very Simple Text Label");
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().add(label); // adds to CENTER
    frame.pack();
    frame.setVisible(true);
  }
}

Output:

import javax.swing.*;
import java.awt.*;
public class MnemonicLabels 
{
  public static void main(String[] args) 
  {
    JTextField firstField = new JTextField(10);
    JTextField middleField = new JTextField(10);
    JTextField lastField = new JTextField(10);

    // Create labels and mnemonics
    JLabel firstLabel = new JLabel("First Name", JLabel.RIGHT);
    firstLabel.setDisplayedMnemonic('F');
    firstLabel.setLabelFor(firstField);

    JLabel middleLabel = new JLabel("Middle Initial", JLabel.RIGHT);
    middleLabel.setDisplayedMnemonic('I');
    middleLabel.setDisplayedMnemonicIndex(7); // requires 1.4
    middleLabel.setLabelFor(middleField);

    JLabel lastLabel = new JLabel("Last Name", JLabel.RIGHT);
    lastLabel.setDisplayedMnemonic('L');
    lastLabel.setLabelFor(lastField);

    // Layout and Display
    JPanel p = new JPanel();
    p.setLayout(new GridLayout(3, 2, 5, 5));
    p.add(firstLabel);
    p.add(firstField);
    p.add(middleLabel);
    p.add(middleField);
    p.add(lastLabel);
    p.add(lastField);

    JFrame f = new JFrame("MnemonicLabels");
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setContentPane(p);
    f.pack();
    f.setVisible(true);
  }
}

Output:

import javax.swing.*;
public class HtmlLabel extends JPanel {
  public static final String markup = "<html>line 1<p><font color=blue size=+2>"
                                    + "big blue</font> line 2<p>line 3</html>";
  public static void main(String argv[]) {
    JPanel p = new JPanel(new java.awt.GridLayout(0, 1));
    p.add(new JLabel(markup));
    p.add(new java.awt.Label(markup));
    JFrame f = new JFrame("HtmlLabel");
    f.setContentPane(p);
    f.setSize(600, 200);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setVisible(true);
  } 
}

Output:

import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
public class DynamicIconExample {
public static void main(String[] args) {
final JSlider width = new JSlider(JSlider.HORIZONTAL, 1, 150, 75);
final JSlider height = new JSlider(JSlider.VERTICAL, 1, 150, 75);
class DynamicIcon implements Icon {
public int getIconWidth() { return width.getValue(); }
public int getIconHeight() { return height.getValue(); }
public void paintIcon(Component c, Graphics g, int x, int y) {
g.fill3DRect(x, y, getIconWidth(), getIconHeight(), true);
}
};
Icon icon = new DynamicIcon();
final JLabel dynamicLabel = new JLabel(icon);
class Updater implements ChangeListener {
public void stateChanged(ChangeEvent ev) {
dynamicLabel.repaint();
}
};
Updater updater = new Updater();
width.addChangeListener(updater);
height.addChangeListener(updater);
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container c = f.getContentPane();
c.setLayout(new BorderLayout());
c.add(width, BorderLayout.NORTH);
c.add(height, BorderLayout.WEST);
c.add(dynamicLabel, BorderLayout.CENTER);
f.setSize(210,210);
f.setVisible(true);
}
}

Output:

Text Alignment Example

Thursday, 18 June 2015
Posted by Unknown
import java.awt.*;
import javax.swing.*;
public class AlignmentExample 
{
  public static void main(String[] args) 
  {
    JLabel label1 = new JLabel("BottomRight", SwingConstants.RIGHT);
    JLabel label2 = new JLabel("CenterLeft", SwingConstants.LEFT);
    JLabel label3 = new JLabel("TopCenter", SwingConstants.CENTER);
    label1.setVerticalAlignment(SwingConstants.BOTTOM);
    label2.setVerticalAlignment(SwingConstants.CENTER);
    label3.setVerticalAlignment(SwingConstants.TOP);

    label1.setBorder(BorderFactory.createLineBorder(Color.black));
    label2.setBorder(BorderFactory.createLineBorder(Color.black));
    label3.setBorder(BorderFactory.createLineBorder(Color.black));


    JFrame frame = new JFrame("AlignmentExample");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JPanel p = new JPanel(new GridLayout(3, 1, 8, 8));
    p.add(label1);
    p.add(label2);
    p.add(label3);
    p.setBorder(BorderFactory.createEmptyBorder(8, 8, 8, 8));
    frame.setContentPane(p);
    frame.setSize(200,200);
    frame.setVisible(true);
  }
}

Output:

Reference:

Text Area Demo

Posted by Unknown
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.Insets;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class TextAreaDemo extends JPanel 
{
    public static void main(String[] args) 
    {
        JFrame window = new JFrame("Slider Demo");
        TextAreaDemo content = new TextAreaDemo();
        window.setContentPane(content);
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        window.setLocation(120,70);
        window.setSize(400,250);
        window.setVisible(true);
    }
    public TextAreaDemo() 
    {
       
        String text = "So, naturalists observe, a flea\n"
            + "Has smaller fleas that on him prey;\n"
            + "And these have smaller still to bite 'em;\n"
            + "And so proceed ad infinitum.\n\n"
            + "                              --Jonathan Swift";
       
        JTextArea textArea = new JTextArea();
        JScrollPane scrollPane = new JScrollPane(textArea);
       
        textArea.setText(text);
        textArea.setFont( new Font("Serif", Font.PLAIN, 24 ));
        textArea.setMargin( new Insets(7,7,7,7) );
       
        setLayout(new BorderLayout());
        setBorder(BorderFactory.createLineBorder(Color.BLACK, 2));
        add(scrollPane, BorderLayout.CENTER);       
    }
}

Output:


import java.util.Scanner;
public class ReverseInputNumbers 
{
   public static void main(String[] args) 
   {
   Scanner input = new Scanner( System.in );
     int[] numbers;
     int count,num;       
     numbers = new int[100];  
     count = 0;               
     System.out.println("Enter up to 100 positive integers (or) enter 0 to end.");
     while (true) 
     {  
        System.out.print("? ");
        num = input.nextInt();
        if (num <= 0) 
        {           
           break;
        }
        numbers[count] = num; 
        count++; 
     }   
     System.out.println("\nYour numbers in reverse order are:\n");    
     for (int i = count - 1; i >= 0; i--) 
     {
         System.out.println( numbers[i] );
     }    
   }
} 

Output:

Enter up to 100 positive integers (or) enter 0 to end. 
? 54
? 45 
? 451 
? 21 
? 32 
? 65465 
? 9779 
? 0

Your numbers in reverse order are:

9779 
65465 
32 
21
451 
45 
54

import java.util.Scanner;
class ComputeAverage 
{
    public static void main(String[] args) 
  {
        Scanner input = new Scanner( System.in );
        int inputNumber, sum=0, count=0;    
        double average;
        System.out.print("Enter your first positive integer: ");
        inputNumber = input.nextInt();
        while (inputNumber != 0) 
        {
            sum += inputNumber; 
            count++;            
            System.out.print("Enter your next positive integer, or 0 to Stop: ");
            inputNumber = input.nextInt();
        }
        if (count == 0)
        {
            System.out.println("You didn't enter any data!");
        }
        else 
        {
            average = ((double)sum) / count;
            System.out.println();
            System.out.println("You entered " + count + " positive integers.");
            System.out.printf("Their average is %1.3f.\n", average);
        }
    }
}

Output:

Enter your first positive integer: 12
Enter your next positive integer, or 0 to Stop: 45
Enter your next positive integer, or 0 to Stop: 87
Enter your next positive integer, or 0 to Stop: 0

You entered 3 positive integers.
Their average is 48.000.


import java.util.Scanner;
class CountDivisors 
{
    public static void main(String[] args) 
   {
        Scanner input = new Scanner( System.in );
        int N,testDivisor,divisorCount,numberTested;
        while (true) 
        {
            System.out.print("Enter a positive integer: ");
            N = input.nextInt();
            if (N > 0)
                break;
            System.out.println("That number is not positive.  Please try again.");
        }
        divisorCount = 0;
        numberTested = 0;
        for (testDivisor = 1; testDivisor <= N; testDivisor++) 
       {
            if ( N % testDivisor == 0 )
                divisorCount++;
            numberTested++;
            if (numberTested == 1000000) 
            {
                System.out.print('.');
                numberTested = 0;
            }
        }
        System.out.println();
        System.out.println("The number of divisors of " +N+ " is " + divisorCount);
    }
}

Output:

Enter a positive integer: 5

The number of divisors of 5 is 2

Welcome to My Blog

Translate

Popular Post

Total Pageviews

- Copyright © Learning Java Program - Powered by Blogger -