Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Write a java program that allows the user to input the name of a fil.docx
1. Write a java program that allows the user to input the name of
a file that contains positive integers (one integer per line) The
number of integers in the file The program should find all odd
and even numbers and write the odd numbers to a file
"odd.txt" and write the even numbers to another file
"even.txt"
Solution
package expertques;
import java.io.File;
import java.io.PrintWriter;
import java.util.Scanner;
public class evenoddwithfile {
public static void main(String[] args) throws Exception {
File in;//file input
File even = new File("f://even.txt");//creates file even
File odd = new File("f://odd.txt");//creates file odd
Scanner s = new Scanner(System.in);//reads input from console
or user
System.out.println("Enter the file name with path: ");
in = new File(s.nextLine());
System.out.println("Enter the number of integers n the file:
");
2. int n = s.nextInt();
if (in.exists()) {//checks if input file exist or not
Scanner ins = new Scanner(in);//reads input file
PrintWriter pe = new PrintWriter(even);//write to even file
PrintWriter po = new PrintWriter(odd);//writes to odd file
for (int i = 0; i < n; i++) {//loop till the numbers exists
int x = ins.nextInt();//reads from input file
if (x % 2 == 0) {//checks for even or odd
pe.println(x);//if even writes in even file
} else {
po.println(x);//if odd writes in odd file
}
}
pe.close();//closes even file very important else nothing will be
written in the file
po.close();//closes odd file very important else nothing will be
written in the file
System.out.println("File successfully written with odds and
evens");
} else {
System.out.println("Error file not found at specified
path");//if file not exist
}
}
3. }
output
run:
Enter the file name with path:
f://integers.txt
Enter the number of integers n the file:
8
File successfully written with odds and evens
BUILD SUCCESSFUL (total time: 6 seconds)