a java programm with try and catch mechanism

a java programm with try and catch mechanism

na kuiweka try and catch block (exception handling) to CTO , htuc
Check comments na uzifanyie kazi
nimejaribu kuweka maoni haya kukusaidia kufikia lengo

Code:
/*
 * Some Comments on your source code by CTO
 * Grades is the class name it should begin with capital to fit conventions (camel case assumed)
 * Put spaces between code blocks like for loops and related code groups
 * grade = grade/10; is more readble than grade /= 10; its better in terms of self documentation
 * 
 * ===Try and catch==
 * Unaweka simba (code) inayotarajia kurusha 'exceptions' katika try block na baada
 * tu ya simba unayotaka inaswe inapotokea tatizo weka catch block!
 * i.e
 * try{....} catch(Exception e){..do something with e}
 * 
 * ==Commandline argument==
 * These are received and added to array in order added to exe i.e
 * java yourProgram p1 p2 p3
 * will give args array of
 * args[0]==>p1
 * args[1]==>p2
 * args[3]==>p3
 * Check example before in first code block of main
 * Use them as you want
 * See this link for details: http://www.codeproject.com/Tips/419749/Working-with-command-line-arguments-in-Java
 */

import java.util.Scanner;

public class Grades {

    public static void main(String[] args) {
       
        try{ //in case anything happened in code tell us why!
           //parse commandline args
           for (int i = 0; i < args.length; i++) {
                System.out.println(args[i]);
            }
           
           //rest of your code
            int grade = 0;

            for (int i = 0; i < 10; i++) {
                grade += validInt("Enter mark " + (i + 1) + "[0-100]: ", 0, 100);
            }

            grade = grade/10;

            System.out.print("You earned a " + grade + " ");
            if (grade >= 70 && grade <= 100) {
                System.out.println("A");
            }         
            else if (grade >= 60 && grade <= 69) {
                System.out.println("B+");
            } 
            else if (grade >= 50 && grade <= 59) {
                System.out.println("B");
            } 
            else if (grade >= 40 && grade <= 49) {
                System.out.println("C");
            } 
            else if (grade >= 30 && grade <= 39) {
                System.out.println("D");
            } 
            else {
                System.out.println("E");
            }
       }
       catch(Exception e)
       {
           System.out.println(e.getMessage());// tells you what went wrong
       }
    }

    public static int validInt(String prompt, int min, int max) {
        Integer result = null;
        
        while (true) {
            System.out.print(prompt);
            Scanner in = new Scanner(System.in);
            
            if (in.hasNextInt()) {
                result = in.nextInt();
            }
            
            if (result != null && result >= min && result <= max) {
                return result;
            } 
            else {
                System.out.println("Invalid Number!...enter again");
            }
        }
    }
}
 
Last edited by a moderator:
sio kwamba nimeshindwa kabisa kodi hii hapo chini na inaru kabisa bro.
Hii code ihamishie ktk post yako ya kwanza na next time hakikisha ktk post yako ya kwanza unaweka details za kuonyesha ulichofanya na uliposhindwa.

BH,
CTO
 
nimejaribu hilo swali kipengere cha kwanza ndio utata (command line )kodi nimeifanya na ina run.

Here is the key to command line data entry...

Consider the signature of the main method
public static void main (String [ ] args)
{
}

Specifically note the input parameter to the main method - an array of strings.

Now, suppose my class with main is called Test, and if the program compiles and runs without any problem, i could call the program with command line data input as follows:
Java Test 1 2 3 4 5

What will happen is that the nos 1 2 3 4 and 5 will be put in an array and passed to main, but in String format, so if you are to use them as nos you have to convert them first

Int x = Integer.parseInt(args[0]);

I.e here am converting the first string in array args into an integer. Note that class Integer has static methods therefore no object instantiation for the class is necessary before you use it - this may sound like chinese to some readers 🙂

To sum up my illustration I now connect all the dots into a class with main as follows

//do the necessary imports

Class Test
{

public static void main( String [ ] args )
{
int n = args.length ; // note args is like a loca variable in main()
int nums [ ] = new int[n ]; //array to hold n numbers where n is size of args array

if ( n=0)
{
// no input data, i.e the input string is empty

// read data from the keyboard by promting the user
}
else {
Int i;

for i=0, i < n, i++
{
nums = Integer.parseInt(args[ i ] );
}

}//end else


}//end main
}//end Test


So, all the nos entered will be stored in integer array nums ....
 
Now for the try catch block consider the given line....

Int x = Integer.parseInt(args[0]);

The method parseInt can throw an exception if the parameter passed in not a number, go to the API Documentation for more details on kinds of exceptions that ca be thrown by this method.

To make your code more stable you must handle the exceptions as follows:


try. // this block is executed if everything is ok
{
x = Integer.parseInt(args[0]);
}
//this block is executed only when an exception occurs
Catch(NotANumberException e)
{
System.out.print(" the input is not a number");
}

catch(Exception e)
{
//put a friendly msg here
}

Note that the try- catch block works like an if-else statement, only one of the blocks is executed not both

You must heavily use JAVADOC or ApiS to discover potential exceptions

The catch block csn have as many catch phrases as possible but more general ones (high in the inheritance hierarchy) should be at the bottom
 
I think hiki ndicho unachokitaka

class 1: for avaraging and grading

public class GetAvarageGrade_lkileha_gmail_com {
public int getAvarage(int sum){
int avarage=0;
avarage=sum/10;
return avarage;
}
public void getGrade(int grade){
if ((grade>=70) && (grade<=100)){
System.out.println("\t\t A");
}
else if ((grade>=60) && (grade<=69)){
System.out.println("\t\t B+");
}
else if ((grade>=50) && (grade<=59)){
System.out.println("\t\t B");
}
else if ((grade>=40) && (grade<=49)){
System.out.println("\t\t C");
}
else if ((grade>=35) && (grade<=39)){
System.out.println("\t\t D");
}
else if ((grade>=0) && (grade<=34)){
System.out.println("\t\t E");
}
}

}


class 2 : core class

import java.util.*;
public class GetUserInput_lkileha_gmail_com {

public static void main(String[] args) {
GetAvarageGrade_lkileha_gmail_com avrg=new GetAvarageGrade_lkileha_gmail_com();
Scanner input = new Scanner(System.in);
int marks[]=new int[10];
int total=0;
int i;
//check if the parameter passed are 10
if(args.length==10){
for(i=0;i<args.length;i++){
try{
marks = Integer.parseInt(args);
} catch (Exception e){
System.out.println(e.getMessage());
}
while ((marks < 0 || marks > 100)) {
System.out.println("Invalid entry,only 0-100 is allowed...");
System.out.print("please re-enter score "+(i+1)+" :");
try{
marks = input.nextInt();
} catch (InputMismatchException e){
System.out.println(e.getMessage());
}
System.out.println("Invalid entry,only 0-100 is allowed...");
}
total=total+marks;
}
avrg.getAvarage(total);
System.out.println("\n************ RESULTS ****************\n");
System.out.println("\tAVARAGE \t GRADE");
System.out.print("\t "+avrg.getAvarage(total));
avrg.getGrade(avrg.getAvarage(total));
System.out.println("*************************************");
}
//if are greater than 10
else if((args.length>10)){
System.out.println("You have exceeded the limit,Only ten Integers are allowed not greater than that!!Try Again");
}
//less than 10
else if((args.length<10) &&(args.length!=0)){
System.out.println("Your inputs are below the limit,ten Integers are allowed not less than that!!Try Again");
}
//if there is no parameter passed
else if(args.length==0)
{

for (i = 0; i < marks.length; i++) {

System.out.print("Please enter score " + (1+i)+" :");
while (!input.hasNextInt()) {
System.out.println("That's not an Integer!");
System.out.print("Please re-enter score " + (1+i)+" :");
input.next();
}
marks = input.nextInt();

while ((marks < 0 || marks > 100)) {
System.out.println("Invalid entry,only 0-100 is allowed...");
System.out.print("please re-enter score "+(i+1)+" :");
while (!input.hasNextInt()) {
System.out.println("That's not an Integer!");
System.out.print("Please re-enter score " + (1+i)+" :");
input.next();
}
marks = input.nextInt();
}
total=total+marks;
}
avrg.getAvarage(total);
System.out.println("\n************ RESULTS ****************\n");
System.out.println("\tAVARAGE \t GRADE");
System.out.print("\t "+avrg.getAvarage(total));
avrg.getGrade(avrg.getAvarage(total));
System.out.println("*************************************");
}
}}

it works fine just compile and run it.
Note:
passing arguments will be like

java GetUserInput_lkileha_gmail_com 34 56 67 89 98 76 56 43 66 77

if there will be no parameter passed it will opt for the prompt method
ie. java GetUserInput_lkileha_gmail_com
Enjoy programming
 
TRY THIS.....

import java.io.*;
import java.util.*;
class Argument
{
public static int n, i=0;

public static double average, sum=0;
public static int p;
double[] x = new double[10];

//main function;
public static void main(String[] arg)
{
int count = 0;
Scanner input = new Scanner(System.in);
double[] x = new double[arg.length];
Argument g = new Argument();
if(arg.length!=0)
{
for(count=0; count<arg.length; count++)
{
try
{
x[count] = Double.parseDouble(arg[count]);
if(x[count]<0)
{
System.out.println("Invalid number(s) "+x[count]);
System.exit(1);
}
else if (x[count]>100)
{
System.out.println("Invalid number(s) "+x[count]);
System.exit(1);
}
else if(arg.length<10)
{
System.out.println("Only ten valid values required" );
break;
}
else if(arg.length>10)
{
System.out.println("Only ten valid values required" );
break;
}

sum+=x[count];
}catch(Exception e)
{
System.out.println(e.getMessage());
}

}
if(sum!=0)
{
average=sum/10;

if(average >= 0 && average <= 34)
{
System.out.println("The average is "+average);
System.out.println("The grade is E");
}
else if(average >= 35 && average <= 39)
{
System.out.println("The average is "+average);
System.out.println("The grade is D");
}
else if(average >= 40 && average <= 49)
{
System.out.println("The average is "+average);
System.out.println("The grade is C");
}
else if(average >= 50 && average <= 59)
{
System.out.println("The average is "+average);
System.out.println("The grade is B");
}
else if(average >= 60 && average <= 69)
{
System.out.println("The average is "+average);
System.out.println("The grade is B+");
}
else if(average >= 70 && average <= 100)
{
System.out.println("The average is "+average);
System.out.println("The grade is A");
}
}
}else
{
g.UsingScanner();
}
}//end main function
public void UsingScanner()
{
Scanner input = new Scanner(System.in);

System.out.println("Enter ten values");
do{
try{
ValidateData(x);
} catch(Exception e)
{
System.out.println(e.getMessage());
}
i++;
}while(i<10);
if(sum!=0)


average=sum/10;

if(average >= 0 && average <= 34)
{
System.out.println("The average is "+average);
System.out.println("The grade is E");
}
else if(average >= 35 && average <= 39)
{
System.out.println("The average is "+average);
System.out.println("The grade is D");
}
else if(average >= 40 && average <= 49)
{
System.out.println("The average is "+average);
System.out.println("The grade is C");
}
else if(average >= 50 && average <= 59)
{
System.out.println("The average is "+average);
System.out.println("The grade is B");
}
else if(average >= 60 && average <= 69)
{
System.out.println("The average is "+average);
System.out.println("The grade is B+");
}
else if(average >= 70 && average <= 100)
{
System.out.println("The average is "+average);
System.out.println("The grade is A");
}
}

double ValidateData(double score)
{
while (true)
{
Scanner input = new Scanner(System.in);

if (input.hasNextDouble())
{
score = input.nextDouble();

}

if (score >= 0 && score <= 100)
{
sum+=score;
return score;
}
else
{
System.out.println("Invalid Number entered! Try again");
}
}

}
}
 
Back
Top Bottom