How to read intergers from file?

I want to write a program that reads numbers from both.txt file and write to even.txt if its even and to odd.txt if its odd numbers in java. i need help

i have managed to create these files

I have tried the following but its not working:

public static void main(String[] args) throws FileNotFoundException, IOException{
  File both = new File("/home/eddie/Desktop/both.txt"); 
  File odd = new File("/home/eddie/Desktop/odd.txt");      
  File even = new File("/home/eddie/Desktop/even.txt");
  
  Scanner myObj = new Scanner(System.in);
   int number,remainder;
    System.out.println("Please enter a number!");
        number = myObj.nextInt();
    
     
    try (PrintWriter pwboth = new PrintWriter(both)) {
        pwboth.println(number);
        pwboth.close(); 
    }
    remainder = number/2;
    
    if (remainder != 0)
    {
        
                
        
            try (PrintWriter pwodd = new PrintWriter(odd)) {
                pwodd.println(number);
                pwodd.close();
            }
    } 
    else if(remainder > 0)
{
      try (PrintWriter pweven = new PrintWriter(even)) {
           pweven.println(number);
           pweven.close();
        }
}
}

This code is only printing to odd.txt and both.txt even if its even number and i want the program to read numbers from the both file i just don’t know how to go about it.

>Solution :

To know if a number is odd or even, you have to know if it is divisible by 2 or not.

if (number % 2 == 0) {
  // It's an even number, write it to even.txt
} else {
  // It's an odd number, write it to odd.txt
}

number % 2 == 0 means that the number is divisible by 2 and leaves no remainder behind when divided by 2.

number %2 != 0 means that the number is NOT divisible by 2 and leaves a remainder behind when divided by 2.

Leave a Reply