Java Exception Handling Without Try Catch

Asked 2 years ago, Updated 2 years ago, 21 views

public class Student { public int studentNumber; // school number public int kor; // Korean // English public int math; // mathematics public double avg; public int total; public Student(int studentNumber) { // Student class constructor this.studentNumber = studentNumber; } Public void pointInsert(Scannersc) { // Method of receiving student grades System.out.println(studentNumber+) You are the first student."); System.out.print ("Korean: "); kor = Integer.parseInt(sc.nextLine()); System.out.print ("English: "); eng = Integer.parseInt(sc.nextLine()); System.out.print ("Mathematics: "); math = Integer.parseInt(sc.nextLine()); } public void printsumAvr() { // Find the total score and mean and output the total result total = (kor + eng + math); avg = (total * 100 / 3 / 100.0); System.out.print(studentNumber + "\t" + kor + "\t" + eng + "\t" + math + "\t"); System.out.print(total + "\t" + avg); System.out.println(); } }

---‐‐------------- public class Main { public static void main(String[] args) { String[] subject = { "School year", "Korean", "English", "Mathematics", "Total", "Average"; Scanner sc = new Scanner(System.in); System.out.print ("Please enter the number of students: "); int number = Integer.parseInt(sc.nextLine()); // Enter the number of students to manage. Student[] student = new Student[number]; // Create an array of Student objects with the student name as many as the number of students entered for (inti = 0; i < number; i++) { // numbering student[i] = new Student(i + 1); } System.out.println(); System.out.println ("Start to enter your score"."); System.out.println(); for (inti = 0; i < student.length; i++) { // Enter score student[i].pointInsert(sc); System.out.println(); } System.out.print ("Number" + "\t" + "Korean" + "\t" + "English" + "\t" + "Mathematics" + "\t" + "Total" + "\t" + "Mean" + "\t" + "\n"); for (inti = 0; i < student.length; i++) { // Enter score student[i].printsumAvr(); } } } }

How should I write down if I use 100 exception handling when coding like this?

java

2022-09-20 20:46

1 Answers

Create a method to try and condition repeatedly, which is good for reuse.

public void pointInsert(Scannersc) { // Method of receiving student grades 
    System.out.println(studentNumber+) You are the first student."); 
    System.out.print ("Korean: "); 
    kor = tryValue(sc);  
    System.out.print ("English: "); 
    eng = tryValue(sc);  
    System.out.print ("Mathematics: "); 
    math = tryValue(sc); 
}
public int tryValue(Scanner sc){
    while(true){
        int temp = Integer.parseInt(sc.nextLine());
        if (temp<1 || temp>100){
            System.out.println ("Invalid value). Please enter a value between 1 and 100.");
        }else{
            return temp;
        }
    }
}


2022-09-20 20:46

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.