This is Java programming assignment to test your control flow and object-oriented concepts in Java.
Write a program in java called Marks (Marks.java) which prompts the user for the number of marks, reads it from the keyboard, and saves it in an integer variable called numOfMarks. It then prompts the user for the marks and saves them in an integer array called marks.
The program you code shall check that value of marks entered are in the range 0 to 100 and the number of marks entered between 0 to 30. The program should display the number of marks that are more than 50.
An example of the output is shown below:
Enter the number of marks: 2 Enter marks 1 : 145 Invalid marks.. try again ! Enter marks 1: 45 Enter marks 2 : 56 Number of marks more than 50 is: 1
package Marks; import java.util.Scanner; public class Marks { int numOfMarks; int[] marks; int count = 0; Scanner input; /* * function that checks if input is valid or not * and also prints the number * of marks > 50 */ private void checkMarks(int numOfMarks) { int i = 0; int score = 0; //to check if number of marks are in //between 0 and 30 if (numOfMarks <= 0 || numOfMarks >= 30) { System.out.println("Invalid Input !"); return; } marks = new int[numOfMarks]; while (i < numOfMarks) { System.out.printf("Enter marks %d:", i + 1); score = input.nextInt(); // to check if value of marks is in between 0 to 100 if (score >= 0 && score <= 100) { marks[i] = score; // assigning value of score variable to marks array i++; continue; } System.out.println("Invalid marks.. Try again !!"); } // loop the marks entered to check // if marks obtained are greater than 50 for (int j = 0; j < marks.length; j++) { if (marks[j] >= 50) { count++; } } System.out.println("Number of marks greater than 50:" + count); } public static void main(String args[]) { Marks myMarks = new Marks(); myMarks.input = new Scanner(System.in); System.out.println("Enter the number of marks:"); myMarks.numOfMarks = myMarks.input.nextInt(); myMarks.checkMarks(myMarks.numOfMarks); } }
Now, let’s have a look at what’s actually happening in the program coded above.
Now, let’s have a look at the various possible outputs for the above program.
Case 1: If the user inputs a value less than 0 or greater than 30 for the variable numOfMarks
Enter the number of marks: 0 Invalid Input !
Case 2: If the user inputs mark greater than 100 and less than 0, we get-
Enter the number of marks: 2 Enter marks 1: 154 Invalid marks.. Try again ! Enter marks 1: 56 Enter marks 2: 47 Number of marks greater than 50: 1
Case 3: Expected Output
Enter the number of marks: 3 Enter marks 1: 56 Enter marks 2: 65 Enter marks 3: 47 Number of marks greater than 50: 2
There might be other ways to solve this Java Assignment for Control Flow and Class-Object. You can try them out and even share it with us.
If you like solving coding challenges, checkout out these coding questions asked in many of the interview rounds.
Keep Coding and Happy Learning!