Question

At the very bottom of my code I have a System.out.print printing the wrong sets of numbers. In the output terminal it says it is factoring 13 numbers, but as you can see it is a lot more numbers than just 13.

Here is my code:

import java.io.*;
import java.util.Scanner;
public class Project4
{
    public static void main(String[] args)
    throws FileNotFoundException
    {
        Scanner in = new Scanner(new File("data4.txt"));              
        System.out.println("Tanner Triggs  CM111 Lecture   Project #4    Due Friday Oct 18");
        int ctr= 0;
        int x = in.nextInt();
        while (x != -999)
        {
            int y = x;
            int z = 2;
            System.out.printf("\r\n For the number %9d the prime factors are",x);
            ctr++;
            while (z< y)
            {
                int remainder = x%z;
                if (remainder == 0)
                {                    
                    System.out.print(","+z);
                    x= x/z;
                }
                else
                {
                    z++;
                }
            }
            if (x==y)
            {                
                System.out.print("  "+x);
            }
            x = in.nextInt();
        }
        System.out.printf("\n\n %9d Sets of numbers factored",ctr);        
    }
}

This is my data4.txt file:

459
120
340
379217
56
457
315
548153764
1001
240652872
123456789
32159
456
-999
Was it helpful?

Solution

You increase ctr for every line you read from your file, so you end up with a correct 13. If you want to count how many prime factors are processed, you should move the incrementing into the inner while loop.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top