Monday, October 19, 2015

PyramidOfStars

public class PyramidOfStars
{
    public static void main(String[] args)
    {
        //prints number of spaces 
        int lines = 8;
       
        //first for loop determines how many lines are printed
        for(int i = 1; i <= 8; i++)
        {
            //second loop prints spaces
            for(int spaces = 1; spaces < lines; spaces++)
            {
                System.out.print(" ");
            }
            //decrements line number
            lines--;
            //third loop prints stars..start at one to print first star
            //and double i to get pyramid rather than triangle..eighth line
            //will be 15 stars and all lines will have an odd number of stars
                for(int stars = 1; stars < i * 2; stars++)
                {
                  System.out.print("*");
                }
            //creates a new line
            System.out.println();
       }
   }
}

I used a different strategy on this one. The loops determine spacing and printing stars rather than forcing formatting with specifiers.

StringColumnWords


import java.util.Scanner;
public class Practice_7_2
{
   public static void main(String[] args)
   {
   //declare variables
   char ch;
   int end, num = 1;
   //do while loop allows user to go again
   do
   {
   //prompt user and get input string
   System.out.print("Enter a string: ");
   Scanner input = new Scanner(System.in);
   String sentence = input.nextLine();
   //prints title for first word
   System.out.print("Word #1:\t");
   //for loop runs for length of string
   for (int i = 0; i < sentence.length(); i++)
   {
   //ch is a character in the string
   ch = sentence.charAt(i);
   //if statement prints letters untiil there is white space
   if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'))
      {
         System.out.print(ch);
               }
         else
         {
            //increments the word number and prints word
            num++;
            System.out.print("\nWord #" + num + ":\t");
         }          
   }
   //asks user if they want to go again and ends if 0 is typed
   System.out.print("\nDo you want to go again? ");
   end = input.nextInt();
   //resets word number to 1
   num = 1;
   }
   while (end != 0);
   }
}

http://math.hws.edu/eck/cs124/javanotes4/c3/ex-3-4-answer.html

This post helped me somewhat, although I didn't want to use the character method because we have not covered that in class yet and I would like to be able to solve each problem with the knowledge introduced so far.

This program has a problem if there is any punctuation, so I need to figure out how commas and periods could be covered in the if statement simply.




Friday, October 16, 2015

SumOfEvens

This do while business is getting easier! Total coding time was like 45 minutes. Most wasted time was spent trying to figure out why the compiler would not recognize the variable stop in the very last line of code.

 Problem solved by declaring variables outside of all loops, statements, etc. I tried to declare it as it was inputted, but I guess the do while loop needs to know it is coming before the do part!

import java.util.Scanner;
public class SumOfEvens
{
   public static void main(String[] args)
   {
   //declare variables
   int sum = 0, stop, num;
   //allow user to rerun if desired
   do
   {
   //create scanner and receive input integer
   System.out.print("Enter an integer between 20 and 60: ");
   Scanner input = new Scanner(System.in);
   num = input.nextInt();
   //resets sum to zero in subsequent iterations
   sum = 0;
   //loop starts at two, determines if incremented number is even
   //and stops when entered integer is reached
   for (int i = 2; i <= num; i++)
   {
      //number is even if modulo is zero
      if (i % 2 == 0)
         //sum accumulates the added digits
         sum = sum + i;
   }
   //Print results
   System.out.println("Entered value: " + num);
   System.out.println("Sum of even numbers between 2 and " + num + " is: " + sum);
   //prompts user to go again
   System.out.print("Continue (0 to end)? ");
   stop = input.nextInt();
   }
   //ends program if user enters 0
   while (stop != 0);
   }
}

Useful site: http://stackoverflow.com/questions/25706216/what-does-a-cannot-find-symbol-compilation-error-mean

ComputeCDValue 5.31

Compute CD Value

This was a pretty easy problem. It was nice to practice formatting!

import java.util.Scanner;
public class ComputCDValue
{
   public static void main(String[] args)
   {
   int end;
   //do while loop allows user to rerun program with different inputs
   do
   {
   //create scanner and input numbers
      Scanner input = new Scanner(System.in);
      System.out.print("Enter the initial deposit amount: ");
      double deposit = input.nextDouble();
      System.out.print("Enter annual percetage yield: ");
      double yield = input.nextDouble();
      System.out.print("Enter maturity period (number of months): ");
      int months = input.nextInt();
   //print headers
      System.out.println("Month   CD Value");
   //loop calculates cd value for each month
      for (int i = 1; i <= months; i++)
      {
         deposit= deposit + deposit * yield / 1200;
         System.out.print(i + "\t");
         System.out.printf("$%8.2f\n", deposit);
      }
      //Prints results
      System.out.println("New calculation? (0 to end): ");
      end = input.nextInt();
      }  
   while (end != 0);
   }
}

Patterns 5.18

Display four patterns using loops

This was hard and thank you Stack Overflow and textbook! I definitely need more practice here as I had to look so much up!

public class Patterns
{
   public static void main(String[] args)
   {
      //prints pattern title
      System.out.println("Pattern A");
      //starts at one increments up to 6
      for (int i = 1; i < 7; i++)
      {
         //stores value in string
         String A = "";
         int start = 1;
         //starts at 1 and and continues until 6
         while(start <= i)
         {
            //adds each new term to the string and increments
            //start by 1
            A += start + " ";
            start++;
         }
         //prints string after each iteration until 7 is reached
         System.out.println(A);
      }
      //places an empty line between patterns
      System.out.println();
      System.out.println("Pattern B");
      //loop starts at 6 and decrements to 1
      for (int i = 6; i > 0; i--)
      {
         String B = "";
         int start = 1;
         while (start <= i)
         {
            B += start + " ";
            start++;
         }
         System.out.println(B);
      }
      System.out.println("Pattern C");
      //starts at 1 and runs 6 times
      for (int i = 1; i < 7; i++)
      {
         String C = "";
         int start = i;
         while (start >= 1)
         {
            //starts at printing 1-6 and decrements
            C += start + " ";
            start --;
         }
         //output the string with a width of at least 
         //12 spaces and then start a new line
         System.out.printf("%12s\n", C);
      }
      System.out.println("\nPattern D");
      for (int i = 6, space = 0; i >0; i--)
      {
         String D = "";
         int start = 1;
         while(start <= i)
         {
            D += start + " ";
            start++;
         }
         System.out.printf("%12s\n", D);
      }
   }
}


I need to study formatting a bit more, so here goes!

%b              boolean value                    true of false
%c               character                           'a'
%d              decimal integer                 200
%f               floating point number       45.4600000
%e               scientific notation            4.556000e+01
%s               string                                "Hello World"

%5c            output the character and add four spaces because the width is five
%6b            output the Boolean value and add one space before the false and two before true
%5d            output integer with a width of at least 5..add spaces before if < 5 increase width if >
%10.2f       output floating point, width 10+ and two decimal places (7 allocated before decimal
%10.2e       output floating point, width 10+ and two decimal places
%12s          output string, width 12+ add spaces if fewer than 12.. increase width if more

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);
   }
}

PostiveNegative 5.1

Count positive and negative numbers and compute the average of the numbers.



import java.util.Scanner;
public class PositiveNegative
{
   public static void main(String[] args)
   {
      int pos = 0, neg = 0;
      int numbers, close;
      double total= 0;
      boolean zero = true;
      // create scanner and ask for integers
      Scanner input = new Scanner(System.in);
      System.out.print("Enter an integer, the input ends if it is 0: ");
      //do while loop for ending program
      do
      {
         //do while loop to process input
         do
         {
            //input integers
            numbers = input.nextInt();
            //if integer is zero, set zero to false and end this run
            if (numbers == 0)
               zero = false;  
            //determines if positive and counts
            else if (numbers > 0)
            {
               pos++;
               total = total + numbers;
            }
            //determines if negative and counts
            else        
            {
               neg++;
               total = total + numbers;
            }    
         }
         //if number is not zero, keeps looping, ends if zero
         while (numbers != 0);
         //prints results
         if (total != 0)
         {
            System.out.println("The number of positives is " + pos);
            System.out.println("The number of negatives is " + neg);
            System.out.println("The total is " + total);
            System.out.println("The average is " + (total / (neg + pos)));
         }
         //if only number is zero prints
         else
         {
            System.out.print("No numbers are entered except 0.");
         }
         //Continues or stops main do while loop
         System.out.println("Do you want to continue? (0 to stop)");
         close = input.nextInt();
      }
      while(close != 0);
   }
}

Place to Post Problems Solved! First up..5.41

Write a program that read integers, finds the largeste of them, and counts its occurrences.
Zeros stops each series.
Allow the user to go again in the same run if desired.
Zero will also stop the program.

I first wrote the inner while loop and got that portion working. For some reason if you change the else if statement to an if statement, the program doesn't work properly. I will have to figure that one out as I thought that they were interchangeable in this instance.


import java.util.Scanner;
public class OccurenceOfMaxNumbers
//read integers and find the largest and count its occurrences
{
   public static void main(String[] args)
   {
      //Declare variables
      int numbers, end, max = 0, count = 0;
      do
      {
      //create scanner and ask for integers
      Scanner input = new Scanner(System.in);
      System.out.print("Enter numbers: ");
      //input numbers in the while loop..zero will end
      while ((numbers = input.nextInt()) != 0)
      {
         //if number is greater than the max it becomes max and
         //count restarts at 1
         if (numbers > max)
         {
            max = numbers;
            count = 1;
         }
         //if the number is equal to max, count increases by one
         else if (numbers == max)
         {
            count++;
         }
         }
      //print results
      System.out.println("The largest number is " + max);
      System.out.println("The occurrence count of the largest number is " + count);
      //Ask if user wants to go again, 0 to end, any key to continue
      System.out.println("Do you want to end (type 0): ");
      end = input.nextInt();
      //reset count and max to zero
      count = 0;
      max = 0;
      }
      while (end !=0);
   }
}