examples for java programs from my clas works

23
Java programming from my class works- java pro 1 This for Modulus example // Demonstrate the % operator. class Modulus { public static void main( String args []) { int x = 42; double y = 42.3; System.out.println("x mod 10 =" + x % 10); System.out.println( "y mod 10 =" + y % 10); } } This is for OpEquals Example class OpEquals { // Demonstate several assignment operators. public static void main( String args []) { int a = 1, b = 2, c = 3; a+=5; b*=4; c+= a*b; c%=6; System.out.println("a =" + a); // a=1+5 = 6 System.out.println("b =" + b); // b=2*4=8

Upload: win

Post on 15-Nov-2014

111 views

Category:

Documents


0 download

DESCRIPTION

this file contains plenty of java programs examples and I hope it will help you for your school works....

TRANSCRIPT

Page 1: Examples for Java Programs from my clas works

Java programming from my class works- java pro 1

This for Modulus example

// Demonstrate the % operator.

class Modulus {

public static void main( String args []) {

int x = 42;

double y = 42.3;

System.out.println("x mod 10 =" + x % 10);

System.out.println( "y mod 10 =" + y % 10);

}

}

This is for OpEquals Example

class OpEquals { // Demonstate several assignment operators.

public static void main( String args []) {

int a = 1, b = 2, c = 3;

a+=5; b*=4; c+= a*b; c%=6;

System.out.println("a =" + a); // a=1+5 = 6

System.out.println("b =" + b); // b=2*4=8

System.out.println("c =" + c); // c = 3+ (6*8)=51=> c%6 = 51%6=3

}

}

Page 2: Examples for Java Programs from my clas works

This is class Room example

class room

{

public static void main(String[] args)

{

int length=15;

int width=25;

int area = 375;

System.out.println("The floor space is " + area + " square feet");

}

}

This interest Class example

class interest

{

public static void main(String[] args)

{

double invested = 1000;

double rate=0.05;

double time=1;

System.out.println("Future Amount" + invested * rate * time);

}

Page 3: Examples for Java Programs from my clas works

}

Changing Fahrenheit to Centigrade

class FahrenheitToCentigrade

{

public static void main(String[] args)

{

int hbt;

int result;

int temp;

temp = 0;

hbt = 100;

temp = hbt - 32;

result = temp*5/9;

System.out.println("Result = " + result);

}

}

class Circle

{

public static void main(String[] args)

{

int radius;

double PI;

double result;

Page 4: Examples for Java Programs from my clas works

radius = 3;

PI = 3.14;

circle area = 1/2 PI;

result = temp*5/9;

System.out.println("Result = " + result);

}

}

Class Time

class time

{

public static void main(String[] args)

{

int minutes= 197;

System.out.println("197 minutes becomes 3 hours and 17 minutes");

}

}

Class Try to parse string

public class TryToParseString {

public static void main(String[] args) {

int i;

String str = "a"; // change this to any string you want

try {

i = Integer.parseInt ( str ) ; // get the integer

Page 5: Examples for Java Programs from my clas works

System.out.println(i); // print out i

} catch ( NullPointerException npe ) {

System.out.println(str + " is not defined");

// if str is not defined

}

catch ( NumberFormatException nfe ) {

System.out.println(str + " is not a number");

// if str is not a number

}

}

}

Class BRReadLines

import java.io.*;// Read a string from console using a BufferedReader.

class BRReadLines{

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

String str;

BufferedReader br=new BufferedReader(

new InputStreamReader(System.in));

System.out.println("Enter lines of text.\n Enter 'stop' to quit.");

do {

str=br.readLine();

System.out.println(str);

Page 6: Examples for Java Programs from my clas works

} while (!str.equals("stop"));

} }

Testing class

import java.io.*;

public class test {

public static void main(String[] args) {

String str = "";

try {

BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

System.out.print( "> ");

str = in.readLine();

} catch (IOException e) {

} // finished reading console input

try {

BufferedWriter out = new BufferedWriter(new FileWriter("test.txt"));

out.write(str);

out.close();

} catch (IOException e) {

} // finished writing to a file

System.out.println("Reading the file and printing .... ");

Page 7: Examples for Java Programs from my clas works

try {

BufferedReader in = new BufferedReader(new FileReader("test.txt"));

String s;

while ((s = in.readLine()) != null) {

System.out.println(s);

}

in.close();

} catch (IOException e){

} // finished reading the file and printing to std out

}

}

Simple java programming examples

class Win

{

public static void main(String[] args)

{

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

{

System.out.println("Hello! HAHAHAHAHA! You can do it !! "+i);

}

}

}

Page 8: Examples for Java Programs from my clas works

class Win1

{

public static void main(String[] args)

{

int MyArray[]={10, 11, 34,45};

for (int i=0;i<4;i++)

{

System.out.println(MyArray[i]);

}

}

}

class Win2

{

public static void main(String[] args)

{

int ArrayA[][]={{10, 11}, {34,45}};

int ArrayB[][]={{10, 11}, {34,45}};

int ArrayC[][];

//perform addition

for (int i=0;i<2;i++)

{

Page 9: Examples for Java Programs from my clas works

for (int j=0;j<2;j++)

{

ArrayC[i][j] = ArrayA[i][j]+ArrayB[i][j];

}

}

//display result

for (int i=0;i<2;i++)

{

for (int j=0;j<2;j++)

{

System.out.print(MyArray[i][j]+" ");

}

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

}

}

}

Java programming from my class work- java pro 2import java.awt.*;

import javax.swing.*;

public class Printer extends JFrame {

public Printer(){

super("Printer");

setLayout(new BorderLayout());

//Label Printer: MyPrinter

Page 10: Examples for Java Programs from my clas works

JLabel labelMyPrinter = new JLabel("Printer: MyPrinter");

add(labelMyPrinter, BorderLayout.PAGE_START);

//Checkboxes

JCheckBox checkImage = new JCheckBox("Image");

JCheckBox checkText = new JCheckBox("Text");

CheckBox checkCode = new JCheckBox("Code");

JPanel panelCheck = new JPanel(new GridLayout(0, 1));

panelCheck.add(checkImage);

panelCheck.add(checkText);

panelCheck.add(checkCode);

//Radio buttons

JRadioButton radioSelection = new JRadioButton("Selection");

JRadioButton radioAll = new JRadioButton("All");

JRadioButton radioApplet = new JRadioButton("Applet");

JPanel panelRadio = new JPanel(new GridLayout(0, 1));

panelRadio.add(radioSelection);

panelRadio.add(radioAll);

panelRadio.add(radioApplet);

//Buttons

JButton buttonOk = new JButton("OK");

JButton buttonCancel = new JButton("Cancel");

JButton buttonSetup = new JButton("Setup...");

JButton buttonHelp = new JButton("Help");

JPanel panelButton = new JPanel(new GridLayout(0, 1));

panelButton.add(buttonOk);

panelButton.add(buttonCancel);

panelButton.add(buttonSetup);

Page 11: Examples for Java Programs from my clas works

panelButton.add(buttonHelp);

//Add Checkbox, radio button and button panel to middle panel

JPanel panelMiddle = new JPanel();

panelMiddle.add(panelCheck);

panelMiddle.add(panelRadio);

panelMiddle.add(panelButton);

add(panelMiddle, BorderLayout.CENTER);

//Print quality and print to file

JLabel labelQuality = new JLabel("Print Quality:");

String[] qualityOptions = {"High","Medium","Low"};

JComboBox comboQuality = new JComboBox(qualityOptions);

JCheckBox checkFile = new JCheckBox("Print to File:");

JPanel panelPrintFile = new JPanel();

panelPrintFile.add(labelQuality);

panelPrintFile.add(comboQuality);

panelPrintFile.add(checkFile);

add(panelPrintFile, BorderLayout.PAGE_END);

}}

Testing printer

import javax.swing.JFrame;

public class PrinterTest {

public static void main(String[] args){

Printer printer = new Printer();

printer.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE);

printer.setSize(500,300);

printer.setVisible(true);

}}

Page 12: Examples for Java Programs from my clas works

Second

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

public class TempConv extends JFrame implements ActionListener{

double fahrenheit, celsius;

JTextField textFahrenheit = new JTextField(10);

JButton buttonConvert = new JButton("Convert");

JLabel labelResult = new JLabel("Result:");

public TempConv(){

super("Fahrenheit to Celsius");

setLayout(new BorderLayout());

//Explanation

JLabel labelExplanation = new JLabel();

labelExplanation.setText("<html>Please enter the value in Fahrenheit and press the Convert button to display the degrees</html>");

add(labelExplanation, BorderLayout.PAGE_START);

//Textarea and button

buttonConvert.addActionListener(this);

JPanel panelInput = new JPanel(new FlowLayout());

panelInput.add(textFahrenheit);

panelInput.add(buttonConvert);

add(panelInput, BorderLayout.CENTER);

//Result label

add(labelResult, BorderLayout.PAGE_END);

}

//Conversion

Page 13: Examples for Java Programs from my clas works

public void actionPerformed(ActionEvent e) {

double celsius;

double fahrenheit = Double.parseDouble(textFahrenheit.getText());

celsius=(fahrenheit-32)*5/9;

labelResult.setText("Result: "+celsius+" degree celsius");

}}

Testing temp

import javax.swing.JFrame;

public class TempConvTest {

public static void main(String[] args){

TempConv tempConv = new TempConv();

tempConv.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE);

tempConv.setSize(320,130);

tempConv.setVisible(true);

}}

Grid class

import java.awt.Graphics;

import javax.swing.JPanel;

public class Grid extends JPanel

{public void paint(Graphics g)

{super.paint(g);

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

{g.drawRect(20,20*i,380,20*i);

g.drawRect(20*i,20,20*i,380);

} } }

Testing grid

import javax.swing.JFrame;

Page 14: Examples for Java Programs from my clas works

public class TestGrid

{public static void main (String args[])

{JFrame frame = new JFrame ("Grid");

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

Grid RectJPanel = new Grid();

frame.add(RectJPanel);

frame.setSize(400,400);

frame.setVisible(true);

} }

Showing color// Fig. 12.6: ShowColors.java

// Demonstrating Colors.

import javax.swing.JFrame;

public class ShowColors

{

// execute application

public static void main( String args[] )

{

// create frame for ColorJPanel

JFrame frame = new JFrame( "Using colors" );

frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );

ColorJPanel colorJPanel = new ColorJPanel(); // create ColorJPanel

frame.add( colorJPanel ); // add colorJPanel to frame

frame.setSize( 400, 180 ); // set frame size

frame.setVisible( true ); // displayt frame

Page 15: Examples for Java Programs from my clas works

} // end main

} // end class ShowColors

Draw Arcs

// Fig. 12.25: DrawArcs.java

// Drawing arcs.

import javax.swing.JFrame;

public class DrawArcs

{

// execute application

public static void main( String args[] )

{

// create frame for ArcsJPanel

JFrame frame = new JFrame( "Drawing Arcs" );

frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );

ArcsJPanel arcsJPanel = new ArcsJPanel(); // create ArcsJPanel

frame.add( arcsJPanel ); // add arcsJPanel to frame

frame.setSize( 300, 210 ); // set frame size

frame.setVisible( true ); // display frame

} // end main

} // end class DrawArcs

Draw polygons

// Fig. 12.28: DrawPolygons.java

// Drawing polygons.

import javax.swing.JFrame;

Page 16: Examples for Java Programs from my clas works

public class DrawPolygons

{

// execute application

public static void main( String args[] )

{

// create frame for PolygonsJPanel

JFrame frame = new JFrame( "Drawing Polygons" );

frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );

PolygonsJPanel polygonsJPanel = new PolygonsJPanel();

frame.add( polygonsJPanel ); // add polygonsJPanel to frame

frame.setSize( 280, 270 ); // set frame size

frame.setVisible( true ); // display frame

} // end main

} // end class DrawPolygons

File demonstration

// Fig. 14.4: FileDemonstration.java

// Demonstrating the File class.

import java.io.File;

public class FileDemonstration {

// display information about file user specifies

public void analyzePath( String path ) {

// create File object based on user input

File name = new File( path );

Page 17: Examples for Java Programs from my clas works

if ( name.exists() ) // if name exists, output information about it

{

// display file (or directory) information

System.out.printf(

"%s%s\n%s\n%s\n%s\n%s%s\n%s%s\n%s%s\n%s%s\n%s%s",

name.getName(), " exists",

( name.isFile() ? "is a file" : "is not a file" ),

( name.isDirectory() ? "is a directory" :

"is not a directory" ),

( name.isAbsolute() ? "is absolute path" :

"is not absolute path" ), "Last modified: ",

name.lastModified(), "Length: ", name.length(),

"Path: ", name.getPath(), "Absolute path: ",

name.getAbsolutePath(), "Parent: ", name.getParent() );

if ( name.isDirectory() ) // output directory listing

{

String directory[] = name.list();

System.out.println( "\n\nDirectory contents:\n" );

for ( String directoryName : directory )

System.out.printf( "%s\n", directoryName );

} // end else

} // end outer if

else // not file or directory, output error message

{

Page 18: Examples for Java Programs from my clas works

System.out.printf( "%s %s", path, "does not exist." );

} // end else

} // end method analyzePath

} // end class FileDemonstration

File demonstration test

// Fig. 14.5: FileDemonstrationTest.java

// Testing the FileDemonstration class.

import java.util.Scanner;

public class FileDemonstrationTest

{

public static void main( String args[] )

{

Scanner input = new Scanner( System.in );

FileDemonstration application = new FileDemonstration();

System.out.print( "Enter file or directory name here: " );

application.analyzePath( input.nextLine() );

} // end main

} // end class FileDemonstrationTest

Account record

// Fig. 14.6: AccountRecord.java

// A class that represents one record of information.

public class AccountRecord

{

private int account;

Page 19: Examples for Java Programs from my clas works

private String firstName;

private String lastName;

private double balance;

// no-argument constructor calls other constructor with default values

public AccountRecord()

{

this ( 0, "", "", 0.0 ); // call four-argument constructor

} // end no-argument AccountRecord constructor

// initialize a record

public AccountRecord( int acct, String first, String last, double bal )

{

setAccount( acct );

setFirstName( first );

setLastName( last );

setBalance( bal );

} // end four-argument AccountRecord constructor

// set account number

public void setAccount( int acct )

{

account = acct;

} // end method setAccount

// get account number

public int getAccount()

Page 20: Examples for Java Programs from my clas works

{

return account;

} // end method getAccount

// set first name

public void setFirstName( String first )

{

firstName = first;

} // end method setFirstName

// get first name

public String getFirstName()

{

return firstName;

} // end method getFirstName

// set last name

public void setLastName( String last )

{

lastName = last;

} // end method setLastName

// get last name

public String getLastName()

{

return lastName;

} // end method getLastName

Page 21: Examples for Java Programs from my clas works

// set balance

public void setBalance( double bal )

{

balance = bal;

} // end method setBalance

// get balance

public double getBalance()

{

return balance;

} // end method getBalance

} // end class AccountRecord