Need help with Java Coding data.txt 4 100 50 9 1 100 50 9 2 100 50 9 3 100 50 9
ID: 3851213 • Letter: N
Question
Need help with Java Coding
data.txt
4
100 50 9 1
100 50 9 2
100 50 9 3
100 50 9 8
Explanation / Answer
make sure your input file is available to StopInsects.java
and make sure you name your input file as "data.txt"
import java.io.*;
public class StopInsects
{
public static void main(String a[])
{
try{
//reads contents of file data.txt
File file = new File("data.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
//reading no of test cases will be there in data.txt(number mentioned in first line of data.txt)
int testCases = Integer.parseInt(br.readLine());
for(int i=0;i<testCases;i++){
//reading line by line contents of data.txt
String line = br.readLine();
//splitting into separate values which are inputs of testcase i,e s,p,r,x
String ar[] = line.split(" ");
int s=Integer.parseInt(ar[0]),p=Integer.parseInt(ar[1]),r=Integer.parseInt(ar[2]),x=Integer.parseInt(ar[3]);
int loop=1;
long females=s,males=s;
//looping till we reach x th week
while(loop<x)
{
long pFemale = calculatePercentage(females,p);
long pMale = calculatePercentage(males,p);
//killing insects of p percent in males and females
females-=pFemale;
males-=pMale;
//reproduction
long tempFem = females;
females+=(females*((int)(r/2)));
males+=(tempFem*((int)(r/2)));
if(r%2!=0)
{
females+=tempFem;
}
//System.out.println(females+" "+males);
loop++;
}
System.out.println("Female="+females+" Male="+males);
}
}
catch(Exception e){
e.printStackTrace();
}
}
//calculates percentage of population
public static long calculatePercentage(long population,int percentage)
{
return (long)population*percentage/100;
}
}