Sei sulla pagina 1di 14

Austria, Christian Dave S.

BSECE 5D EXERCISES Chapter 2

September 12, 2012

1. What is eclipse? Ans.: Eclipse is a platform that has been designed from the ground up for building integrated web and application development tooling. Eclipse provides a common user interface (UI) model for working with tools. Plugins can program to the Eclipse portable APIs and run unchanged on any of the supported operated systems. 2. Enumerate the steps needed to run a java program in eclipse. Ans.: Create a New Project Create a New Class Write the Program Save it Run the Program by Selecting Java Application 3. What is naming convention for the following? Class Name Ans.: Class names should always start with a capital letter as the first letter and should have no spaces. Use whole words avoid acronyms and abbreviations. Method Name Ans.: The first letter of the method should be in lower case and the first letters of subsequent words in uppercase. Variable Ans.: Local variables, instance variables, and class variables are also written in lower case. Variable names should not start with underscore (_) or dollar sign ($) characters, even though both are allowed. Program file Ans.: The name of the program file must be same as the class name. The letters of the class file and program file must be exactly same. 4. Create a program that writes the following in the console: <Your Full Name> <Year and Section> <Address and Contact Number>

a. b. c. d. e. a.

b.

c.

d.

Program:
public class MyInformation { //This program displays my full name, CYS, address, and contact number. public static void main(String[] args) { System.out.println("Christian Dave S. Austria"); System.out.println("BSECE 5D"); System.out.print("56 Red rose St. PZBG cmpd.,Diliman Quezon City 09351170242"); } }

Austria,Christian Dave S. BSECE 5B

September 12, 2012

EXERCISES Chapter 3: 1. Which data type would you use to represent the following values? a. Child age Ans.: Integer (int) b. Employee salary Ans.: Double (double) c. Whether somebody has children or not Ans.: Boolean (boolean) d. Apartment letter Ans.: Character (char) 1. Define a Java variable named NewLine storing the new line character. Print it. Ans.:
String NewLine = "new line"; System.out.print(NewLine);

2. Declare two float variables (x and y) and assign them values 2.5 and 5.4 (with separate declaration and initialization). Ans.: double x;
double y; x = 2.5; y = 5.4;

3. Declare two float variables (x and y) and assign them values 2.5 and 5.4 (declaration and initialization in the same sentence). Ans.: double x = 2.5;
double y = 5.4;

a. b. c. d. e. f.

4. Find the errors in the following Java sentences: int a, b, c a=0 Ans.: Syntax error, there is no semicolon (;) at the end of each sentences. System.out.println(ab); Ans.: A pair of quotation mark () should be used instead of an apostrophe (). System.out.println((3+2)-1); Ans.: Nothing is wrong. int a = 3.2; Ans.: Type mismatch. It must be double. float a = 2.1; int c = a; Ans.: Type mismatch: cannot convert float to int. It must be double. int i = 10; float b;

g.

h. i.

j.

i = b; Ans.: Type mismatch: cannot convert float to int. int x; { x = 10; } System.out.println(x); Ans.: Nothing is wrong, but it is not necessary to insert the initialization into a pair of curly bracket. boolean a, b; a = false, b = true; Ans.: Syntax error. You cannot use comma (,) in initialization. int x; x = 1; r = x + 1; Ans.: Variable r was not initialized. String s = This is a string; Ans.: Quotation marks should be used to initialize a string. 1. Find the value of the variable result after executing the following sentences: int a; int b; int result;

a.

b.

c.

d.

e.

a = 4; b = 12; result = a + b / 3; Ans.: 8 a = 3; a = a + 3; b = 2; result = a b; Ans.: 4 a = 2; b = a + 1; a = b +2; result = a + b + a; result = -result; Ans.: -13 a = 3; b = 11; result = (b % a) + 1; Ans.: 3 a = 3; b = a++;

result = 1; result += a b; Ans.: 2 1. Write a program to find the following: a. Prime number Program:
public class PrimeNumbers { //This program displays the prime numbers. public static void main(String[] args) { int i, j, s=0; int desiredNumber = 100; for (i=1; i<=desiredNumber; i++){ s=0; for (j=1; j<=i; j++){ if (i%j==0) s = s + 1; } if (s==2) System.out.println(i); }}}

b.

Sum of digits Program:


public class SumOfDigits { //This program displays the sum of digits. public static void main(String[] args) { int i= 11; int s; s=0; System.out.println(i); while (i>10){ s += i%10; i /= 10; } s += i; System.out.println ("The sum of the digits is: " + s); } }

1. Write a program to calculate the roots of Quadratic equations. Program:


public class RootsOfQE { //This program calculates the roots of quadratic equations. public static void main(String[] args) { int a=1, b=1, c=2; int x = b*b-4*a*c; double r1, r2; r1 = (-b+(Math.sqrt(x)))/2*a; r2 = (-b-(Math.sqrt(x)))/2*a; if (x<0){ System.out.println("There are no real roots."); }

else{ } }}

System.out.println("The roots are "+r1+" or "+r2);

2. Write a program to print the following triangle of binary digits. Program:


public class Triangle { //This program displays a triangle of binary digits. public static void main(String[] args) { int i=1, a=0; for(i=1; i<=25;i++){ if (i%2!=0){ a=a*2; } else { a=a*2+1; String b = Integer.toBinaryString(a); System.out.println(b); System.out.println("0"+b); }}}}

a.

3. Write a program for calculating Matrix Operations. Addition. Program:


public class MatrixAddition { // Matrix addition public static void main(String[] args) { int I, j, k; int a[][]={ {4,7,9,8,3},{2,4,7,8,1},{1,1,8,1,2},{0,0,1,0,4}}; int b[][]={ {1,2,8,4,3},{4,1,8,3,1},{2,1,0,0,5},{1,2,1,1,7}}; int c[][]; c = new int[4][5]; for(I=0;I<4;I++) for(j=0;j<5;j++) c[I][j]=a[I][j]+b[I][j]; for(I=0;I<4;I++) { System.out.println("\n"); for(j=0;j<5;j++) System.out.print(c[I][j]); }}}

b.

Multiplication Program:
public class MatrixMultiplication { //Matrix multiplication public static void main(String[] args) { int a[][]={ {0,1,4},{2,1,7} }; int b[][]={ { 1,7,2,3},{4,1,-2,3},{4,1,7,2} }; int c[][]; c = new int[2][4]; int I, j, k; for(I=0;I<2;I++) for(j=0;j<4;j++)

c[I][j]=0; for(k=0;k<3;k++) c[I][j]+=a[I][k]*b[k][j];

} for(I=0;I<2;I++) { System.out.println("\n"); for(j=0;j<4;j++) System.out.print("\b" + c[I][j]+" "); }}}

1. Write program that calculates the voltage gain in decibels. Program:


public class VoltageGain { //This program calculates for the voltage gain in decibels. public static void main(String[] args) { double Vout = 2; double Vin = 4; double GaindB; GaindB = 20*Math.log10(Vout/Vin); System.out.print("The voltage gain in decibels is " + (GaindB) + " dB"); }}

Austria, Christian Dave S. 2012 BSECE 5B

September 12

EXERCISES Chapter 4: 1. Whats a java class? What constitutes a class? Ans.: A Java class is a blue print from which individual objects are created. Classes are the fundamental building blocks of a Java program. A class is a technique of using one or a group of variables as a foundation for a more detailed variable. A class can contain any of the following variable types: local variables, instance variables, class variables. A class can have any number of methods to access the value of various kind of methods. 2. Whats the difference between a local variable and a member variable? Ans.: Local variables are variables defined inside a methods, constructors or blocks. The variable will be declared and initialized within the method and the variable will be destroyed when the method has completed. While member variables are variables within a class but outside any method. These variables are instantiated when the class is loaded. It can be accessed from inside any methods, constructors or blocks of that particular class. 3. Whats the difference between a static field and a non-static field? Ans.: Static variables or fields belong to the class, and not to any object of the class. A static variable is initialized when the class is loaded at runtime. Non-static fields are instance fields of an object. They can only be accessed or invoked through an object reference. The value of static variable remains constant throughout the class. The value of Non-static variables changes as the objects has their own copy of these variables. 4. Write a program to create a room class, the attributes of this class are room number, room type and room area. In this class the member functions are setdata and displaydata. Program:
public class Room { int roomNo; String roomType; float roomArea; void setData(int rno, String rt, float area){ roomNo = rno; roomType = rt; roomArea = area; } void displayData(){ System.out.println("The room number is " + roomNo); System.out.println ("The room type is " + roomType); System.out.println ("The room area is " + roomArea); } public static void main(String[] args) { Room room1 = new Room ( ); room1. setData (101, "Deluxe", 240.0f);

} }

room1.displayData ( );

5. Create a class Rectangle. The class has attributes length and width, each of which is default to 1. It has methods that calculate the perimeter and the area of the rectangle. It has set and get methods for both length and width. The set method should verify that length and width are each floating-point numbers larger than 0.0 and less than 20.0. Program:
package classesObjects; public class Rectangle { float length=1; float width=1; public float getLength() { return length; } private float setLength(float length) { if ((length>0.0)&&(length<20.0)) { return length; } else { System.out.printf("Invalid length (%.2f) set to 1.\n",length); return 1; } } public float getWidth() { return width; } private float setWidth(float width) { if ((width>0.0)&&(width<20.0)) { return width; } else { System.out.printf("Invalid width (%.2f) set to 1.\n",width); return 1; } } public float calcPerimeter(float length, float width) { float perimeter=2 * (length + width); return perimeter; } public float calcArea(float length, float width) { float area= length * width; return area; } public static void main(String[] args) { Rectangle r=new Rectangle(); System.out.println("*** Test 1 - Valid length and width ***");

float l=r.setLength(5); float w=r.setWidth(2); float a=r.calcArea(l, w); float p=r.calcPerimeter(l, w); System.out.println("Area: "+a+"\nPerimeter: "+p); System.out.println(); System.out.println("*** Test 2 - Invalid length and width ***"); float l2=r.setLength(21); float w2=r.setWidth(-2); float a2=r.calcArea(l2, w2); float p2=r.calcPerimeter(l2, w2); System.out.println("Area: "+a2+"\nPerimeter: "+p2); } }

Austria, Christian Dave S. 2012 BSECE 5B CHAPTER 5

September 12,

2. Write a program to create a class named shape. In this class we have three sub classes circle, triangle and square each class has two member function named draw () and erase (). Create these using polymorphism concepts. Program:
public class Shape { void draw(){ System.out.println(Shape draw()); } void erase() { System.out.println ( Shape erase()); } } class Circle extends Shape { void draw() { System.out.println (Circle draw()); } void erase() { System.out.println (Circle erase()); } } class Triangle extends Shape { void draw(){ System.out.println(Triangle erase()); } } class Square extends Shape { void draw() { System.out.println (Square draw()); } void erase() { System.out.println (Square erase()); } } public class Shapes { public static Shape randshape() { switch((int)(Math.random()*3)){ case 0: return new Circle(); case 1: return new Square(); case 2: return new Triangle(); default :System.out.println(default); return new Shape(); } } public static void main (String arg[]) { Shape s[] = new Shape[9];

for(int i = 0;i<s.length; i++) s[i] = randshape(); for(int i= 0;i <s.length; i++) s[i].draw(); } }

Austria, Christian Dave S. BSECE 5D Chapter 7


2.Write a temperature conversion application that converts from Fahrenheit to Celsius. The Fahrenheit temperature should be entered from the keyboard (via a JTextField). A JLabel should be used to display the converted temperature.

ANSWER: import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.text.*; /* <applet code="TempCon" width=400 height=100> </applet> */ public class TempCon extends JApplet implements ActionListener { JTextField txtInput; JLabel lblResult; JRadioButton rbCelcius, rbKelvin; public void init(){ Container conpane = getContentPane(); conpane.setLayout (new FlowLayout()); txtInput = new JTextField("",10); conpane.add(txtInput); rbCelcius= new JRadioButton ("to Celcius", true); conpane.add(rbCelcius); rbKelvin = new JRadioButton("to Kelvin", false); conpane.add(rbKelvin); ButtonGroup selection = new ButtonGroup(); selection.add(rbCelcius); selection.add(rbKelvin); JButton button1 = new JButton ("Show Result"); button1.addActionListener(this); conpane.add(button1); lblResult= new JLabel ("Enter Ferenheit, Choose an option to convert and Click Show Result"); conpane.add(lblResult); } public void actionPerformed(ActionEvent e) { DecimalFormat df = new DecimalFormat ("#.##"); double ferenheit = Double.parseDouble(txtInput.getText()); double answer = 0.0; answer = ((5.0/9.0)*(ferenheit - 32.0)); if (rbKelvin.isSelected()) answer += 273.15; lblResult.setText(String.valueOf(df.format(answer))); } }

Austria,Christian Dave S. BSECE 5D


Chapter 8 5.Write a program to create interface A in this interface we have two method meth1 and meth2. Implements this interface in another class named MyClass.
ANSWER: // One interface an extend another. interface A { void meth1(); void meth2(); } // B now includes meth1() and meth2()--it adds meth3(). interface B extends A { void meth3(); } // This class must implement all of A and B class MyClass implements B { public void meth1 ( ) { System.out.println(Implement meth1().); } public void meth2() { System.out.println (Implement meth2().); } public void meth3() { System.out.println (Implement meth(). ); } } class IFExtend { public static void main(String arg[]) { MyClass ob = new MyClass(); ob.meth1(); ob.meth2(); ob.meth3(); } }

Austria, Christian Dave S. BS ECE 5D Chapter 6 1. (A) (B) (C) (D) 2. (E) Invalid Valid Valid Invalid True
Each array has a constant (final) instance variable that has its length. You can find out how many elements an array can hold by writing the array name followed by .length. In the previous example, a.length would be 100. Remember that this is the number of elements in the array, one more than the maximum subscript.

3.
class Exercise1 { public static void main(String[] args) { int[] val = {0,1,2,3}; int sum; sum = 0; for (int i = 0; i < val.length; i++) { sum += val[i]; } System.out.println(Sum os all numbers = + sum); } }

4. class Exercise3 { public static void main(String[] args) { int[] valA = {13,-22,82,17}; int[] valB = {-12,24,-79,-13}; int[] sum = {0,0,0,0}; sum[0] sum[1] sum[2] sum[3] = = = = valA[0] valA[1] valA[2] valA[3] + + + + valB[0]; valB[1]; valB[2]; valB[3];

System.out.println(sum: + sum[0] + "" + sum[1] + "" + sum[2] + "" + sum[3])

Potrebbero piacerti anche