Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading