• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Jeanne Boyarsky
  • Bear Bibeault
Sheriffs:
  • Rob Spoor
  • Henry Wong
  • Liutauras Vilda
Saloon Keepers:
  • Tim Moores
  • Carey Brown
  • Stephan van Hulst
  • Tim Holloway
  • Piet Souris
Bartenders:
  • Frits Walraven
  • Himai Minh
  • Jj Roberts

For Loop help!

 
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
This is what I need to do: Write a program that asks the user for a number greater than 5 and prints all values between 1 and n that are multiples of 5

This is my code so far, i'm having trouble printing out only multiples of 5. I don't think using a modulus is the right way but i'm not sure. Any help would be awesome!



   
 
Saloon Keeper
Posts: 7999
70
Eclipse IDE Firefox Browser MySQL Database VI Editor Java Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

You're not quite think about this correctly, 'n' (according to the requirements) is the 'limit' of the loop. It should only be used once in the 'while' portion of the for() construct. You'll need a different variable to increment.
 
Sheriff
Posts: 16103
268
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Why don't you think the % operator would be correct here? (Hint: it actually is the right tool for this job)
 
Carey Brown
Saloon Keeper
Posts: 7999
70
Eclipse IDE Firefox Browser MySQL Database VI Editor Java Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Junilu Lacar wrote:Why don't you think the % operator would be correct here? (Hint: it actually is the right tool for this job)


I think his for() loop with "+=5" is a better approach.
 
Marshal
Posts: 72406
315
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Well, I think that 0 is a multiple of 5, but saying that is only an excuse to say something important:-

Welcome to the Ranch
 
Reed Kinney
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I added a variable J to the mix, it works now but I still can't get it to print in multiples of 5. I feel like using % isn't usefu because itl can only really work if you know how much you need to add but I don't cause the user decides. I'm probably wrong though lol programming is frustrating
 
Carey Brown
Saloon Keeper
Posts: 7999
70
Eclipse IDE Firefox Browser MySQL Database VI Editor Java Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The user doesn't decide how much to add, the user decides what the limit is of your counter variable in order to stop the loop. You decide how much to add. You can either add one and use modulus operator or you can add 5.
 
Junilu Lacar
Sheriff
Posts: 16103
268
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You're right, += 5 is more straightforward
 
Reed Kinney
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I almost got it now! I figured out the modulus, the only thing now is that my program keeps printing till 100 and doesn't stop at what 'n' is. Lastly, it starts at 10 instead of 1. I feel like my variable 'j' doesn't belong but if I assign n to 0 than the program doesn't run.

package pkg4.pkg2;
import java.util.Scanner;

/**
*
* @author bambo
*/
public class Main {

   /**
    * @param args the command line arguments
    */
   public static void main(String[] args) {
         Scanner keyboard = new Scanner(System.in);

         
         System.out.println("Please enter a number greater than 5");
         int n = keyboard.nextInt();
         int j;
         if (n<=5)
         {
             System.out.println("bad number, enter a number greater than 5");
             keyboard.nextInt();
         }
       
       
          for(j=0; n>5; n+=5)
         {
             if (n %5 ==0)
             {
             System.out.println(n);
             }
             else
             {
                 n=5;
             }
         while (n>=100)
             {
                 System.exit(0);
             }

         
       
   }
   }            
   }
Staff note (Knute Snortum) :

Thanks for the attempt at using code tags, but your code needs to be in between tags, like this: [code]your code here[/code]

 
Carey Brown
Saloon Keeper
Posts: 7999
70
Eclipse IDE Firefox Browser MySQL Database VI Editor Java Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Where did you get your magic number '100' from? There's nothing in your requirements that calls for it.

You previously determined with an if() that n > 5, then you test it to see if it's greater that 5, which is true, then you increase it to 10, then 15, then 20, etc.. It will ALWAYS be greater than 5 (until it overflows). You should probably read up on for() loops again because you're not using it in the correct way.
 
Campbell Ritchie
Marshal
Posts: 72406
315
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Carey Brown wrote:Where did you get your magic number '100' from? There's nothing in your requirements that calls for it. . . .

I am more concerned about the line following: System.exit(0); I think that using System.exit is often a bad idea, and you could avoid it by writing the loop correctly. Has anybody shown you the standard for loop structure to iterate the whole of an array?
 
Reed Kinney
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I've only had a brief lecture on it in my class and for some reason i'm having trouble understanding how to implement it in this program.
 
Reed Kinney
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I don't understand what the initialization part of the for loop would be, the user chooses 'n' so do I just leave the first part of the for loop blank? If I assign a value to 'n' in the first part of the for loop then it contradicts the whole program and it doesn't work.
 
Campbell Ritchie
Marshal
Posts: 72406
315
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
There is a default format for for loops, used because it is going to work and not throw out of bounds exceptions, nor miss out part of what it is traversing:-In your case, I think you want to replace something by n. By the way: What does your line 23 do?
 
Reed Kinney
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Line 23 stores the user's input in the integer 'n'.
 
Carey Brown
Saloon Keeper
Posts: 7999
70
Eclipse IDE Firefox Browser MySQL Database VI Editor Java Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Reed Kinney wrote:Line 23 stores the user's input in the integer 'n'.

No it doesn't. The returned value is tossed in the trash.
 
Campbell Ritchie
Marshal
Posts: 72406
315
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Reed Kinney wrote:Line 23 stores the user's input in the integer 'n'.

No, it doesn't. Look closely. Where does it say anything about n?
 
Reed Kinney
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I'm so confused lol this is beyond frustrating jeez, I was taught that when I have a line like 22-23 that since I have a scanner in the line then whatever the user inputs is stored in whatever I name the variable. I thought this was true since it worked in previous programs? I updated my code a little bit, am I close to getting this right? I feel like I just don't know what to name the initialization of the loop and how to design it so whatever the user inputs the output is in multiples of 5. I have the modulus set up properly I think but I don't know what to add to it in the 'else' statement. For example, if the user enters a 7 I would write +=3 in my else statement but if the user enters any number besides one that's -3 a multiple of 5 then my program doesn't do what's asked. package pkg4.pkg2;
import java.util.Scanner;

/**
*
* @author bambo
*/
public class Main {

   /**
    * @param args the command line arguments
    */
   public static void main(String[] args) {
         Scanner keyboard = new Scanner(System.in);

         
         System.out.println("Please enter a number greater than 5");
         int n = keyboard.nextInt();
     
         if (n<=5)
         {
             System.out.println("bad number, enter a number greater than 5");
             keyboard.nextInt();
         }
       
       
         for(; n>0; n+=5)
         {
           
            if (n%5==0)
            {
                System.out.println(n);
            }
            else {
               
            }
     

         
       
   }
   }            
   }
 
Campbell Ritchie
Marshal
Posts: 72406
315
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Reed Kinney wrote:. . . whatever the user inputs is stored in whatever I name the variable. . . .

There aren't any such variables named in line 23.
 
Sheriff
Posts: 7111
184
Eclipse IDE Postgres Database VI Editor Chrome Java Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Reed Kinney:

Please be careful to use the code tags correctly.  Your code should be inside the code tags, like this:

   [code=java]Code goes here[/code]

To be sure you've used them correctly, press the Preview button right next to the Submit button first.
 
Knute Snortum
Sheriff
Posts: 7111
184
Eclipse IDE Postgres Database VI Editor Chrome Java Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
This is how your code should look with code tags:

Now you can clearly see line 23.
 
Reed Kinney
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I almost have it I think, we had another lecture on it and i'm feeling a little more confident about loops. I'm so close, I just can't get the program to print in multiples of 5 because in my for loop I need to assign int i to 1 otherwise my program won't work. Ideally I think i'd want it set to 0 so it goes up by 5. I think I may have something wrong with my for loops though, I kinda just copied what we did in class and hoped for the best lol. I also don't know if I can fix this by adding something in an else statement, like if the number isn't divisible by 5 add a number to i so that it is.  
 
Carey Brown
Saloon Keeper
Posts: 7999
70
Eclipse IDE Firefox Browser MySQL Database VI Editor Java Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

There are two approaches to solving your problem and you're incorrectly mashing them together. One way would be to increment your loop by 1 and then use the modulus operator. The other would be for the loop to start at 5 and increment by 5 and forget the modulus all together.

Note that your 'else { }', because it is empty, isn't needed at all.
 
Campbell Ritchie
Marshal
Posts: 72406
315
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
There is a use for an empty else: it produces a compiler error if you put the dreaded extra semicolon after if (...);
 
Carey Brown
Saloon Keeper
Posts: 7999
70
Eclipse IDE Firefox Browser MySQL Database VI Editor Java Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Campbell Ritchie wrote:There is a use for an empty else: it produces a compiler error if you put the dreaded extra semicolon after if (...);


Interesting point but:
  • Compilers should give an error or at least a warning in such cases.
  • Code would look like hell if you did this for each and every if().


  • [edit] IMHO
     
    Campbell Ritchie
    Marshal
    Posts: 72406
    315
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    If there isn't exactly one statement/block between if (b) and else, the code won't compile. If you get an “if without else” compiler error, you look for the extraneous semicolon. You would of course delete the empty else aferwards.

    In Dijksra's programming theory, the most fundamental version of a selection statement is:-
    g ⟶ S ⊓ ¬g ⟶ T
    which is a combination of guards (⟶) and (non‑determinstic) choice (⊓) but the g and ¬g completely control the choice. That is equivalent to:-
    if g then S else T end
    In that theory, a “shortt conditional” statement is equivalent to
    g ⟶ S ⊓ ¬g ⟶ skip
    or
    if g then S else skip end
    so an if statement is really an if‑else with an empty else, which is usually omitted.
    ∴ My twisted logic means it is all right to write and delete an empy else.


    But maybe learning not to write extraneous semicolons is quicker
     
    Campbell Ritchie
    Marshal
    Posts: 72406
    315
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    A few minues ago, I wrote:. . . “if without else” compiler error . . .

    Maybe that should read, “else without if,” instead.
     
    Your mother was a hamster and your father was a tiny ad:
    SKIP - a book about connecting industrious people with elderly land owners
    https://coderanch.com/t/skip-book
    reply
      Bookmark Topic Watch Topic
    • New Topic