Friday, October 16, 2015

DivisibleBy5And6 5.11

Find numbers divisible by 5 and 6

I tried to use the main for loop only once with constants and then adding the scanner inputs, but after much sweat, could not make it work, so i tacked on the same program bit and put it in a do-while loop so that the user could input his lows and highs.

Would love to know if I could do this in one for loop. Of course the do-while is needed to ask if the user wants to continue.

import java.util.Scanner;
public class DivisibleBy5And6
{
   //Create scanner
   Scanner input = new Scanner(System.in);
   public static void main(String[] args)
   {
      //Declare variables
      int end, count = 0;
      //first run..high and low given..num is set at 100 for the
      //low number and 200 for the high..the for loop increments 
      //by one starting at 100 and ending at 200
      for (int num = 100; num < 201; num++)
      {
         //Exclusive or require one, but not both statements
         //to be true..if either 5 or 6 (but not both) is a 
         //divisor, count is incremented
         if ((num % 5 == 0) ^ (num % 6 == 0))
         {
            //prints with a tab between each number to line up 
            //columns
            System.out.print(num + "\t");
            count ++;
            //next line every 10 integers that are divisible by 
            //5 or 6
            if (count % 10 == 0)
               System.out.println();
         }    
      }
      //lets user input new low and high points
      do
      {
         Scanner input = new Scanner(System.in);
         System.out.println("\nEnter new low number: ");
         int low = input.nextInt();
         System.out.println("Enter new high number: ");
         int high = input.nextInt();
         //resets count to 0 so previous iterations are not used in
         //determining where the rows of ten start
         count = 0;
         for (int num = low; num < (high + 1); num++)
         {
            if ((num % 5 == 0) ^ (num % 6 == 0))
            {
               System.out.print(num + "\t");
               count ++;
                  if (count % 10 == 0)
                  System.out.println();
            }    
         }
      //Asks user to continue..0 to stop and any other number to continue
      System.out.print("\n\nDo you want to continue: (0 to stop)");
      end = input.nextInt();
      }
      //ends while loop if user input 0
      while (end != 0);
   }
}

No comments:

Post a Comment