Sie sind auf Seite 1von 7

Subjective Portion

Name: Ehtisham Haider

Reg.No: Sp18-bse-026

Class: 2-B

COURSE TEACHER: Sir Azfar shakeel


Question 1:
Answer:
public class Question1{

static int charactersOnly(String str){


int count=0;
for(int i = 0; i < str.length(); i++) {
if(str.charAt(i) != ' ')
count++;
}
//System.out.println(count);
return count;

}
public static void main(String[] args) {
String str = "my name is ehtisham";
int n = charactersOnly(str);
System.out.println(n);
}
}

Question 2:
Answer:
import java.util.Scanner;
public class Question2 {
public static void main(String args[]){
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the number:");
int num = scanner.nextInt();
int num2 = scanner.nextInt();
int num3 = scanner.nextInt();
int factorial1 = fact(num);
int factorial2 = fact(num2);
int factorial3 = fact(num3);

System.out.println("Factorial of" +num+ " is: "+factorial1);


System.out.println("Factorial of" +num2+ " is: "+factorial2);
System.out.println("Factorial of" +num3+ " is: "+factorial3);
}
static int fact(int n)
{
int output;
if(n==1){
return 1;
}
output = fact(n-1)* n;
return output;
}
}

Question 3:
Answer:
public class Ques3 {

public static void main(String[] args) {

int[][] m = {{1,2,3},{4,5,6},{7,8,9}};

sumDiagonals(m);
}

public static int[] sumDiagonals(int[][] m){

int[] D = new int[3];

int N = m.length;
int s1=0, s2=0, s3=0;

//Major Diagonal Sum


for(int i=0; i<N; i++){
s1+= m[i][i];
}
D[0] = s1;

//Antidiagonal Sum
for(int i=0, j=N-1; i<N || j>0; i++, j--){

s2 += m[i][j];
}
D[1] = s2;
//Middle Column sum
for(int i=0, j=N/2; i<N; i++){

s3 += m[i][j];
}
D[2] = s3;

return D;
}
}

Question 4:
Answer:
public class Ques4 {

public static Scanner input = new Scanner(System.in);


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

System.out.print("Enter Number of students to be added: ");


int n = input.nextInt();

PrintWriter pw = new PrintWriter(new FileWriter("file.txt", true));

String name;
int score;
for(int i=0; i<n; i++){
System.out.print("Enter Student "+(i+1)+" name: ");
name = input.next();

System.out.print("Enter Student "+(i+1)+" score: ");


score = input.nextInt();

pw.write(name);
pw.write(score);
}

// Read from file


try {
File file = new File("file.txt");
Scanner read = new Scanner(file);

//loop will be continue till file have next value

int i=0;
while (read.hasNextLine()) {

while (read.hasNext()) {

System.out.println("Name of students "+i+" " + read.next());


System.out.println("Score of students "+i+" " + read.next());

}
i++;
}
System.out.println("Total Students: "+i);

} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}

Das könnte Ihnen auch gefallen