int age=0,maleCount=0,totalNumberOfMembers=0,younger=1000;
double sum=0;
String gender,str;
FileReader fr=null;
PrintWriter pw = null;
How can I use if and else statement instead of try and catch exception in this code
// try and catch block to catch exception if file not found
try
{
fr = new FileReader("MyData.txt");
pw = new PrintWriter("Results.txt");
}
catch (FileNotFoundException fe)
{
System.out.println("File not found");
}
File file = new File("MyData.txt");
try {
Scanner sc = new Scanner(file);
while(sc.hasNextLine()){
// we just need to use \t as delimiter
sc.useDelimiter("\t");
str = sc.next().trim();
if(!str.isEmpty()){
age = Integer.parseInt(str);
sum += age;
}else{
break;
}
if(age<younger)
younger = age;
sc.useDelimiter("\t");
gender = sc.next().trim();
if(gender.equals("Male"))
maleCount++;
sc.useDelimiter("\n");
sc.next().trim();
totalNumberOfMembers++;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (NumberFormatException e) {
e.printStackTrace();
}
pw.write("Average age: "+sum/totalNumberOfMembers+"\n");
pw.flush();
pw.write("Youngest age: "+younger+"\n");
pw.flush();
pw.write("Number of male members: "+maleCount+"\n");
pw.flush();
}
How can I use if else statement instead of try and catch exception in this code
Aucun commentaire:
Enregistrer un commentaire