Uploaded by Nene Nagetey

JAVA Assingments

advertisement
Slid 6
Write a program that calculates and outputs the square of each integer a
user inputs from a GUI
import java.util.*;
public class squareroot {
public static void main(String[] args)
{
int num;
Scanner in = new Scanner(System.in);
System.out.print("Input a positive integer: ");
int n = in.nextInt();
System.out.printf("Square root of %d is: ",n);
System.out.println(sqrt(n));
}
private static int sqrt(int num) {
if (num == 0 || num == 1) {
return num;
}
int a = 0;
int b = num;
while (a <= b) {
int mid = (a + b) >> 1;
if (num / mid < mid) {
b = mid - 1;
} else {
if (num / (mid + 1) <= mid) {
return mid;
}
a = mid + 1;
}
}
return a;
}
}
Write a program that calculates and outputs the average of integers a user
inputs from a GUI.
import java.util.Scanner;
public class
{varageinteger
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Input first number: ");
int num1 = in.nextInt();
System.out.print("Input second number: ");
int num2 = in.nextInt();
System.out.print("Input third number: ");
int num3 = in.nextInt();
System.out.print("Input fourth number: ");
int num4 = in.nextInt();
System.out.print("Enter fifth number: ");
int num5 = in.nextInt();
System.out.println("Average of five numbers is: " +
(num1 + num2 + num3 + num4 + num5) / 5);
}
}
Write a Java program that calculates the sum, difference, product, quotient,
and modulus of two integers accepted from a GUI.
import javax.swing.JOptionPane;
public class mywork{
public static void main(String[] args) {
System.out.println ("Exercice 01");
System.out.println (" ");
System.out.println("Enter two integer");
String input1 = JOptionPane.showInputDialog(null,"Enter the first
number : ");
String input2 = JOptionPane.showInputDialog(null,"Enter the second
number : ");
int A = Integer.parseInt(input1);
int B = Integer.parseInt(input2);
JOptionPane.showMessageDialog(null, A + " + " + B +" = " + (A+B)+ "\n" +
A + " - " + B +" = " + (A-B)+ "\n" + A + " * " + B +" = " + (A*B)+ "\n“
+ A + " / " + B +" = " + (A/B)+ "\n" + A + " % " + B +" = " + (A%B)+
"\n");
}
}
Slid 7.
Write an applet that uses graphics to draw a picture of your own design. The objective of
this programming activity is for you to gain experience with the window coordinate system, the draw
and fill graphics methods, and using colors.
import javax.swing.JApplet;
import java.awt.Graphics;
import java.awt.Color;
public class BeninFlag extends JApplet{
public void paint(Graphics g){
super.paint(g);
Polygon triangle1 = new Polygon();
Polygon triangle2 = new Polygon();
int sX = 10, sY = 10;
g.setColor(Color.YELLOW);
g.fillRect(sX,sY,450,50);
g.setColor(Color.RED);
g.fillRect(sX,sY+50,450,50);
g.setColor(Color.GREEN);
g.fillRect(sX,sY+100,70,100);
}
Download