Page 1 of 2 12 LastLast
Results 1 to 20 of 25

Thread: for loop

  1. #1
    newbie79 is offline Member
    Join Date
    Oct 2010
    Posts
    16
    Rep Power
    0

    Default for loop

    Hi I am new to java and I have this assignment to do a loop to determine all the prime numbers from 1 to 1000, but to try it, i did my loop from 1 to 10.

    This is my code:

    public class premier
    {
    public static void main (String [] args)
    {
    int diviseur = 0;
    int resultat = 0;
    int nombre = 0;
    int diviseurs = 0;
    int nbdiviseurs = 0;

    for(int valeur = 1; valeur <= 10; valeur++)
    {
    for(diviseur = 2; diviseur < valeur; diviseur++)
    {
    resultat = valeur % diviseur;

    if(resultat != 0)
    {
    System.out.println(valeur+" est premier");
    }

    else
    {

    diviseurs = diviseur;
    System.out.println(valeur+ " est divisible par : "+diviseurs);
    }
    }
    }
    }
    }

    However, because my system.out.print is i the diviseur loop. it prints for every diviseur

    Print:

    3 est premier
    4 est divisible par : 2
    4 est premier
    5 est premier
    5 est premier
    5 est premier
    6 est est divisible par : 2
    6 est divisible par : 3
    6 est premier
    6 est premier
    ...

    However, I am supposed to do

    3 est premier
    4 est divisible par : 2, soit 1 diviseurs
    5 est premier
    6 est divisible par 2, 3, soit 2 diviseurs
    ...

    However everytime I try printing out of the diviseur loop, the modulo is not the right value anymore so it prints est premier for all values.

    I was woundering if somebody could help me with this simple problem

    thanks a lot

  2. #2
    jac0117 is offline Member
    Join Date
    Jan 2008
    Posts
    9
    Rep Power
    0

    Default

    public class premier
    {
    public static void main (String [] args)
    {
    int diviseur = 0;
    int resultat = 0;
    int nombre = 0;
    int diviseurs = 0;
    int nbdiviseurs = 0;

    for(int valeur = 1; valeur <= 10; valeur++)
    {
    for(diviseur = 2; diviseur < valeur; diviseur++)
    {
    resultat = valeur % diviseur;

    if(resultat == 0)
    {
    diviseurs = diviseur;
    }
    }
    System.out.println(valeur+ " est divisible par : "+diviseurs);
    }
    }
    }

  3. #3
    newbie79 is offline Member
    Join Date
    Oct 2010
    Posts
    16
    Rep Power
    0

    Default

    thks for replying so quickly, however, that wasn't exactly what i had to do...thks anyways for answering...

  4. #4
    Zack's Avatar
    Zack is offline Senior Member
    Join Date
    Jun 2010
    Location
    Destiny Islands
    Posts
    692
    Rep Power
    5

    Default

    You have to store a boolean value, something like isPrime, before the diviseur begins (hint: it should start as true), then if it finds something to divide by, change it. After the loop, you can print if it is or is not prime.

  5. #5
    newbie79 is offline Member
    Join Date
    Oct 2010
    Posts
    16
    Rep Power
    0

    Default

    Hi Zack, your little hint was extremely helpful, I thank you very much

    This is my new code:

    public class premier
    {
    public static void main (String [] args)
    {
    int diviseur = 0;
    int resultat = 0;
    int nombre = 0;
    int diviseurs = 0;
    int nbdiviseurs = 0;
    boolean premier = true;

    for(int valeur = 1; valeur <= 20; valeur++)
    {
    premier = true;

    for(diviseur = 2; diviseur < valeur; diviseur++)
    {
    resultat = valeur % diviseur;

    if(resultat == 0)
    {
    diviseurs = diviseur;
    premier = false;
    System.out.print(diviseurs+" ,");
    }
    }

    if(premier)
    {
    System.out.println(valeur+" est premier");
    }

    else
    {

    System.out.println(valeur+ " est divisible par : "+diviseurs);
    }

    }
    }
    }

    wich works perfectly for the prime number, however the new print is still faulty:

    C:\Users\Anne-Qing\Desktop> java premi
    1 est premier
    2 est premier
    3 est premier
    2 ,4 est divisible par :
    5 est premier
    2 ,3 ,6 est divisible par :
    7 est premier
    2 ,4 ,8 est divisible par :
    3 ,9 est divisible par :
    2 ,5 ,10 est divisible par :
    11 est premier
    2 ,3 ,4 ,6 ,12 est divisible par :
    13 est premier
    2 ,7 ,14 est divisible par :
    3 ,5 ,15 est divisible par :
    2 ,4 ,8 ,16 est divisible par :
    17 est premier
    2 ,3 ,6 ,9 ,18 est divisible par :
    19 est premier
    2 ,4 ,5 ,10 ,20 est divisible par :

    as you can see the diviseurs are before the value, the thing is that if I printed diviseurs int the print outside of the loop, it would only print one diviseurs from this i gathered that i had to print the diviseurs inside the second loop...but because of you I am getting closer to my goal...thanks alot

    Alex

  6. #6
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,565
    Rep Power
    12

    Default

    newbie: could you edit your post so that we can see the various loops properly? You put [code] at the start of the code and [/code] at the end.

    (Also 1 n'est pas premier - but I wouldn't worry about that yet.)

  7. #7
    Zack's Avatar
    Zack is offline Senior Member
    Join Date
    Jun 2010
    Location
    Destiny Islands
    Posts
    692
    Rep Power
    5

    Default

    If printing out what the number is divisible by, that should be inside the diviseurs loop. Remember, that is where the value of diviseurs is valid:
    Java Code:
    loop through numbers {
        set isPrime to true
        loop through divisors {
            if (divisible) { it is not prime, set isPrime to false and print this number out }
        }
        print the value of isPrime out
    }

  8. #8
    DarrylBurke's Avatar
    DarrylBurke is offline Forum Police
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,404
    Rep Power
    20

  9. #9
    newbie79 is offline Member
    Join Date
    Oct 2010
    Posts
    16
    Rep Power
    0

    Default

    Hi Zack, I'm not sure i understand what you are saying...if I print is prime wont it print false?? Also I was woundering how I could set my diviseurs counter for it tell me how many diviseurs there is for each number.

    DB I understand what you did, however for this assigment we are not allowed to use function like that...thks anyways.

    Last question: is there a way to change the print order???


    thks a lot guys

  10. #10
    newbie79 is offline Member
    Join Date
    Oct 2010
    Posts
    16
    Rep Power
    0

    Default

    for pbrockway2...I don't know if this is better

    public class premier
    {
    public static void main (String [] args)
    {
    int nbofdivisors = 0;
    boolean isprime = true;

    for(int valeur = 1; valeur <= 20; valeur++){

    ispreme = true;

    for(int divisor = 2; divisor < valeur; divisor++){

    if(valeur % divisor == 0){
    int DivisorS = divisor;
    ispremier = false;
    System.out.print(DivisorS+", ");}

    }

    if(ispreme){
    System.out.println(valeur+" est premier");}

    else{

    System.out.println(valeur+ " can be divided by:");}
    }
    }
    }

    Now the problem is that if I print the divisor in the first loop it only prints one of them. and if I print it in the second for loop it prints all of them but before can be divided by:

    thks a gain for helping me

  11. #11
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,565
    Rep Power
    12

    Default

    Java Code:
    public class premier
    {
       public static void main (String [] args)
       {
          int nbofdivisors = 0;
          boolean isprime = true;
    
          for(int valeur = 1; valeur <= 20; valeur++){
    
             ispreme = true;
    
             for(int divisor = 2; divisor < valeur; divisor++){
    
                if(valeur % divisor == 0){
                   int DivisorS = divisor;
                   ispremier = false;
                   System.out.print(DivisorS+", ");}
    
             }
    
             if(ispreme){
                System.out.println(valeur+" est premier");}
    
             else{
    
                System.out.println(valeur+ " can be divided by:");}
          }
       }
    }

    Or, to make the placement of "{" consistent and because "}" at the end of a line is a bit hazardous:


    Java Code:
    public class premier {
       public static void main (String [] args) {
          int nbofdivisors = 0;
          boolean isprime = true;
    
          for(int valeur = 1; valeur <= 20; valeur++) {
             ispreme = true;
    
             for(int divisor = 2; divisor < valeur; divisor++) {
                if(valeur % divisor == 0) {
                   int DivisorS = divisor;
                   ispremier = false;
                   System.out.print(DivisorS+", ");  // <----------- Too soon!
                }
             }
    
             if(ispreme) {
                System.out.println(valeur + " est premier");
             } else {
                System.out.println(valeur + " can be divided by: ");
             }
          }
       }
    }

    As you say printing the divisors in the for loop (when you find them) mucks up your output.

    What to do?

    1) You could run the for loop and print the "est premier" message if the value is prime. And if it is not prime you print "can be divided by: " then use another for loop to print the factors.

    But that's a bit messy - having a loop to detect primes and another to display factors.

    2) At the line I've marked you could remember the factor that you've found instead of printing it. By "remember" I mean put them in a collection of some sort. Then you can print out the collection's contents at the appropriate time.

    (Note that the number of factors that this collection ends up with determines whether the number is prime: a prime number has exactly two factors. So you don't need the ispreme flag if you do this. I think the technical term is "accumulate the factors".)

    Most people would use a List<Integer> to store the factors because it grows as big as it needs to be. If you don't know about lists you could use an array to store the factors but, if I were doing it and I was limited to arrays, I think I would opt for version 1).

  12. #12
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,565
    Rep Power
    12

    Default

    Oh yes, a couple of things about forum (any forum) usage:

    If you are going to post in multiple places, please post links at both places (as Darryl has done for you) so that everybody knows what is going on. I don't want to waste my time on the question if it as answered elsewhere, also I want to be able to follow the entire discussion. (and it is a discussion, something the facebook "solution" seems to have missed.)

    The (forum) formatting is really useful. Especially where loops and things are concerned I rely on indenting massively to literally see the logic. (others may be different). Here it works like this:

    You post:

    [code]
    class HelloForum {
    public static void main(String[] args) {
    System.out.println("How do I look?");
    }
    }
    [/code]

    (or something like that. It shouldn't be double spaced.) And what appears is:

    Java Code:
    class HelloForum {
       public static void main(String[] args) {
          System.out.println("How do I look?"); 
       }
    }

  13. #13
    jac0117 is offline Member
    Join Date
    Jan 2008
    Posts
    9
    Rep Power
    0

    Default

    You need to do something like this

    Java Code:
      public static void findPrimes( int n){
            int i = 0;
            
            //loop while i++ is less or equal to n
    
                int number = (int) Math.ceil(Math.sqrt(i));
    
                //set prime flag to false
    
               //lop while number is greater than one
              {
               //if i equals number and i is divisible by number               
               //           set prime to false and break
                  
                //else set prime to true
               //decrement number by one
                
                //print the number only if prime flag is true
            }
    
        }
    Last edited by jac0117; 10-03-2010 at 11:16 PM.

  14. #14
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,565
    Rep Power
    12

    Default

    //print the number only if prime flag is true
    The OP wants to print the number (i) in either case. In the case of composites he wants to print all the factors so the "while number is greater than 1" loop must run completely.

  15. #15
    Zack's Avatar
    Zack is offline Senior Member
    Join Date
    Jun 2010
    Location
    Destiny Islands
    Posts
    692
    Rep Power
    5

    Default

    Quote Originally Posted by newbie79 View Post
    Hi Zack, I'm not sure i understand what you are saying...if I print is prime wont it print false?? Also I was woundering how I could set my diviseurs counter for it tell me how many diviseurs there is for each number.
    Setting it to record how many primes there are for each number is a different story. However I'm having a difficult time figuring out what part of my post is unclear... the pseudocode there should set you in the right direction--your loops are already set up; the idea is that if a number is prime, it is printed AFTER the loop while if it is NOT prime, then it is printed mid-loop.

  16. #16
    newbie79 is offline Member
    Join Date
    Oct 2010
    Posts
    16
    Rep Power
    0

    Default

    I tried to add a list, the printing order is now right, however, it prints to many diviseurs:

    this is my print:

    4 est divisible par : [2]soit 1 diviseurs
    5 est premier
    6 est divisible par : [2, 2, 3]soit 3 diviseurs
    7 est premier
    8 est divisible par : [2, 2, 3, 2, 4]soit 5 diviseurs
    9 est divisible par : [2, 2, 3, 2, 4, 3]soit 6 diviseurs
    10 est divisible par : [2, 2, 3, 2, 4, 3, 2, 5]soit 8 diviseurs
    11 est premier
    12 est divisible par : [2, 2, 3, 2, 4, 3, 2, 5, 2, 3, 4, 6]soit 12 diviseurs
    13 est premier
    14 est divisible par : [2, 2, 3, 2, 4, 3, 2, 5, 2, 3, 4, 6, 2, 7]soit 14 diviseu
    rs
    15 est divisible par : [2, 2, 3, 2, 4, 3, 2, 5, 2, 3, 4, 6, 2, 7, 3, 5]soit 16 d
    iviseurs
    16 est divisible par : [2, 2, 3, 2, 4, 3, 2, 5, 2, 3, 4, 6, 2, 7, 3, 5, 2, 4, 8]
    soit 19 diviseurs
    17 est premier
    18 est divisible par : [2, 2, 3, 2, 4, 3, 2, 5, 2, 3, 4, 6, 2, 7, 3, 5, 2, 4, 8,
    2, 3, 6, 9]soit 23 diviseurs
    19 est premier
    20 est divisible par : [2, 2, 3, 2, 4, 3, 2, 5, 2, 3, 4, 6, 2, 7, 3, 5, 2, 4, 8,
    2, 3, 6, 9, 2, 4, 5, 10]soit 27 diviseurs

    and I am also woudering if I can eliminate the brakets

    This is my new code:

    XML Code:
    import java.util.ArrayList;
    import java.util.List;
    
    public class premier
    {
            public static void main (String [] args)
            {
    			System.out.print("\nExercice 3\npartie 1\n");
    			
    			int nbdiviseurs = 0;
    			boolean premier = true;
    			List list = new ArrayList();
    			int size = 0;
    					
                for(int valeur = 1; valeur <= 20; valeur++)
    			{	
    				premier = true;
    				
    				for(int diviseur = 2; diviseur < valeur; diviseur++)
    				{
    					if(valeur % diviseur == 0)
    					{
    						nbdiviseurs++;
    						premier = false;
    						list.add(diviseur);
    						size = list.size();
    					}
    				}
    				
    				if(premier)
    			    {
    					System.out.println(valeur+" est premier");
    				}
    					
    				else
    				{
    					System.out.println(valeur+ " est divisible par : "+list+ "soit "+size+" diviseurs");
    				}
    			}
    }
    I'm sorry guys im not really good with this stuff...as always thks for your help

  17. #17
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,565
    Rep Power
    12

    Default

    The number of divisors is steadily growing! You have to clear (empty) your list after you have printed so that it's ready for the next number you are looking at.

  18. #18
    newbie79 is offline Member
    Join Date
    Oct 2010
    Posts
    16
    Rep Power
    0

    Default

    thks pbrockway It works, however, everytim I compile, I get this warning:

    C:\Users\Anne-Qing\Desktop>javac premier.java
    Note: f.java uses unchecked or unsafe operations.
    Note: Recompile with -Xlint:unchecked for details.

    so I recompiled using javac premier.java -Xlint and I get this warning:

    C:\Users\Anne-Qing\Desktop>javac f.java -Xlint
    f.java:25: warning: [unchecked] unchecked call to add(E) as a member
    type java.util.List
    list.add(diviseur);
    ^
    1 warning

    I was woundering what it meant

    Since my print is :

    Exercice 3
    partie 1
    1 est premier
    2 est premier
    3 est premier
    4 est divisible par : [2] soit 1 diviseurs
    5 est premier
    6 est divisible par : [2, 3] soit 2 diviseurs
    7 est premier
    8 est divisible par : [2, 4] soit 2 diviseurs
    9 est divisible par : [3] soit 1 diviseurs
    10 est divisible par : [2, 5] soit 2 diviseurs
    11 est premier
    12 est divisible par : [2, 3, 4, 6] soit 4 diviseurs
    13 est premier
    14 est divisible par : [2, 7] soit 2 diviseurs
    15 est divisible par : [3, 5] soit 2 diviseurs
    16 est divisible par : [2, 4, 8] soit 3 diviseurs
    17 est premier
    18 est divisible par : [2, 3, 6, 9] soit 4 diviseurs
    19 est premier
    20 est divisible par : [2, 4, 5, 10] soit 4 diviseurs

    I was woundering if there was a way to take the [ ] off since in this assignment I am not supposed to have any

    thks again

  19. #19
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,565
    Rep Power
    12

    Default

    As far as the warning goes, you are not using generics, so you get the warning. There is a section on Generics in Oracle's Tutorial.

    You declare:

    Java Code:
    List list = new ArrayList();

    which is fine. What you have is list which is a collection of any sort of object instance (Integer, String, Double, etc). But later on you say:

    Java Code:
    list.add(diviseur);

    and at this point the compiler gets worried. It has constructed an Integer from diviseur and put it into the list. The problem is that you might later take the object out and cast it to a String or a Double etc. You don't do this, but the compiler's warning occurs because you might and it wants to stop you from making that mistake if it can.

    The solution is to tell the compiler right from the start that you want a list of Integers rather than just a plain list. Ie you would change the declaration and initialisation to:

    Java Code:
    List<Integer> list = new ArrayList<Integer>();

    Now the compiler will be happy because you are adding an int to the list which you declared to be of the right type: a list of Integers. (The conversion between int and Integer happens automatically.)

    Sorry this was a bit long (for a one line change!), but the tutorial I linked to - although good in other respects - is a bit brief on this warning message. There is a longer discussion of generics later in the tutorial.

    -----

    As far as the printing is concerned: that's just the way Lists print themselves! If you want nicer formatting you have make a loop and print each element of the list.

  20. #20
    newbie79 is offline Member
    Join Date
    Oct 2010
    Posts
    16
    Rep Power
    0

    Default

    ok thks again

    I think I figured it out, however i dont seem to completely understand why it is this way

    XML Code:
    public class Premier
    {
        public static void main (String [] args)
        {
        System.out.print("Exercice 3\npartie 1\n");       // Partie 1
        
        int nbdiviseurs = 0;                              // Compteur de diviseurs
        boolean premier = true;                      // I dont think it is necessary
        
        for(int valeur = 1; valeur <= 1000; valeur++)
        {
            premier = true;
            nbdiviseurs = 0;                  // reinitialiser compteur = 0 pour chaque valeur
            
            for(int diviseur = 2; diviseur < valeur; diviseur++)
            {
            if(valeur % diviseur == 0)
            {
                nbdiviseurs++;
                premier = false;
                    
                if(nbdiviseurs == 1)              // i think that this condition should be nbdivisors >1
                {
                System.out.print(valeur+" est divisible par : "); //How come when I print this inside the divisor loop, it prints only once for every value?????
                }
                    
                System.out.print(diviseur+",");
            }
                
            }
            
            if(nbdiviseurs == 0)
            {
            System.out.println(valeur+"  est premier");      
            }
    
            if(nbdiviseurs > 1)
            {
            System.out.print(" soit "+nbdiviseurs+" diviseurs\n"); // This is just because if the is only one divisor it is singular
            }
            
            if(nbdiviseurs == 1)      //iI am not sure i understand why if I print them outside of the divisor loop, there is only one divisor
            {
            System.out.print(" soit "+nbdiviseurs+" diviseur\n"); 
            }
    }
        }
    I am just not sure why if you print outside of the loop it only prints one divisor, also I am not sure wy even if I print in the divisor loop, ":est divisible par prints only once for every value

    thks alot

    U have helped me alot

    I hope you are not to annoyed by my lack of understanding

Page 1 of 2 12 LastLast

Similar Threads

  1. Replies: 5
    Last Post: 04-30-2010, 05:05 PM
  2. Do While Loop
    By s4rd59 in forum New To Java
    Replies: 2
    Last Post: 02-14-2010, 03:29 PM
  3. Help on Do-While loop
    By SwEeTAcTioN in forum New To Java
    Replies: 6
    Last Post: 10-30-2009, 04:09 AM
  4. while-loop stopping on first loop
    By davester in forum New To Java
    Replies: 6
    Last Post: 06-26-2009, 08:46 PM
  5. How to use Do While loop
    By Java Tip in forum java.lang
    Replies: 0
    Last Post: 04-17-2008, 07:45 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •