Create a Java Project With Your name as “YourNameProjectQNo1”, add a class to this Project, Class name should be Your Name with Your Reg No as “YourNameYourRegNo”
a. Add a Method to Accept names and marks of n students from user, enter the value of n from User
b. Ensure that valid data is entered. If user enters an invalid data, then appropriate message should be displayed using Message Dialog Box e.g. ‘Name cannot be a number’ or ‘Marks must be an integer value’
c. Add another Method, to Display this data in descending order according to marks such that name of student.
import javax.swing.JOptionPane;
public class Q188617 {
/**
* The start point of the program
*
* @param args
*/
public static void main(String[] args) {
String names[];
int marks[];
String nStr = " ";
while (!isInteger(nStr)) {
nStr = JOptionPane.showInputDialog("Enter N: ");
if (!isInteger(nStr)) {
JOptionPane.showMessageDialog(null, "N must be an integer value");
}
}
int n = Integer.parseInt(nStr);
names = new String[n];
marks = new int[n];
AddStudents(names, marks);
DisplayDescendingOrder(names, marks);
}
/**
* a Method to Accept names and marks of n students from user, enter the value
* of n from User
*
* @param names
* @param marks
*/
private static void AddStudents(String names[], int marks[]) {
for (int i = 0; i < names.length; i++) {
String name = " ";
while (!isString(name)) {
name = JOptionPane.showInputDialog("Enter student name " + (i + 1) + ": ");
if (!isString(name)) {
JOptionPane.showMessageDialog(null, "Name cannot be a number.");
}
}
names[i] = name;
String markStr = " ";
while (!isInteger(markStr)) {
markStr = JOptionPane.showInputDialog("Enter student mark " + (i + 1) + ": ");
if (!isInteger(markStr)) {
JOptionPane.showMessageDialog(null, "Marks must be an integer value");
}
}
marks[i] = Integer.parseInt(markStr);
}
}
/***
* Method, to Display this data in descending order according to marks such that
* name of student.
*
* @param names
* @param marks
*/
private static void DisplayDescendingOrder(String names[], int marks[]) {
int n = marks.length;
int temp = 0;
for (int i = 0; i < n; i++) {
for (int j = 1; j < (n - i); j++) {
if (marks[j - 1] < marks[j]) {
// swap marks
temp = marks[j - 1];
marks[j - 1] = marks[j];
marks[j] = temp;
// swap names
String tempName = names[j - 1];
names[j - 1] = names[j];
names[j] = tempName;
}
}
}
String output= String.format("%-20s%-20s\n","Names","Marks");
for (int i = 0; i < n; i++) {
output+= String.format("%-25s%-20d\n",names[i],marks[i]);
}
JOptionPane.showMessageDialog(null, output);
}
private static boolean isString(String s) {
for (int i = 0; i < s.length(); i++) {
if (!Character.isAlphabetic(s.charAt(i))) {
return false;
}
}
return true;
}
private static boolean isInteger(String s) {
for (int i = 0; i < s.length(); i++) {
if (!Character.isDigit(s.charAt(i))) {
return false;
}
}
return true;
}
}
Comments
Leave a comment