In: Computer Science
Java
Q1: Create a class named Triangle, the class must contain:
Q2: Write a Java program that creates a two-dimensional array of type integer of size x by y (x and y must be entered by the user). The program must fill the array with random numbers from 1 to 100. The program must prompt the user to enter a search key between 1 and 100. Then, the program must check whether the search key is available in the array and print its location.
Here is a sample run:
Enter the number of rows: 5
Enter the number of columns: 5
Enter a search key between 1-100: 27
The key you entered is available at row 3, column 2.
Here is another sample run:
Enter the number of rows: 5
Enter the number of columns: 5
Enter a search key between 1-100: 33
The key you entered is not available in the array.
Q1:
import java.util.*;
public class Triangle {
private double base,height;
public void setBase(double b) {
base = b;
}
public void setHeight(double h) {
height = h;
}
public double getBase() {
return(base);
}
public double getHeight() {
return(height);
}
public Triangle(double b,double h) {
base = b;
height = h;
}
public void toMyString() {
System.out.println("Base of the triangle:
"+base+"\nHeight of the triangle: "+height);
}
public void area() {
System.out.println("area of the triangle:
"+0.5*base*height);
}
}
public class TriangleMain {
public static void main(String args[]) {
Triangle t1 = new Triangle(7,8);
t1.toMyString();
t1.area();
}
}
Output
Q2:
import java.util.*;
public class Array {
public static int[] searchArray(int[][] a,int x,int
y,int n) {
for(int i=0;i<x;i++) {
for(int j=0;j<y;j++) {
if(a[i][j] ==
n)
return new int[] {i,j};
}
}
return null;
}
public static void main(String args[]) {
int x,y,search;
Scanner s = new Scanner(System.in);
Random r = new Random();
System.out.print("Enter the number of rows: ");
x = s.nextInt();
System.out.print("Enter the number of columns:
");
y = s.nextInt();
int [][]array = new int[x][y];
for(int i=0;i<x;i++) {
for(int j=0;j<y;j++) {
array[i][j] =
r.nextInt(100-1)+1;
}
}
/* To print the array
for(int i=0;i<x;i++) {
for(int j=0;j<y;j++) {
System.out.print(array[i][j]+" ");
}
System.out.println();
}
*/
System.out.print("Enter a search key between 1-100:
");
search = s.nextInt();
int[] values = new int[2];
values = searchArray(array,x,y,search);
if (values != null)
System.out.println("The key you
entered is available at row "+(values[0]+1)+",column
"+(values[1]+1));
else
System.out.println("The key you
entered is not available in the array");
}
}