QuestionQuestion

Homework #1
1.1 Here is a listing of a program, which demonstrates calculating area of a circle whose radius is 2.

      public class FirstJavaHello {
            public static void main(String[] args) {
                  int radius = 2;
                  double area;
                  final double pi = 3.142;

                  area= pi * radius * radius;

                  System.out.print("The area is: ");
                  System.out.println(area);
             }
      }
Modify the above program and use only one print statement instead of one print and one println statements to show the same output (“The area is: xxxx.xx”).

1.2 Following code uses scanner to get the radius from user during run time, calculates area and displaysit. You have to import Scanner class from java.util (import java.util.Scanner; ) package

                                                 Scanner readInput = new Scanner(System.in);
                                                 //extra line feed
                                                 System.out.println();
                                                 System.out.print("Enter the radius: ");
                                                 radius = readInput.nextInt();

                                                 area= pi * radius * radius;

                                                System.out.print("The area is: ");
                                                System.out.println(area);

Modify the above program instead of hard-coding the value of PI in the program, get the value of PI from the user as well.

1.3 Following code demonstrate that radius could be a byte type. It also displays how to get a character input from user, and clean the input buffer with any remaining characters or end of line marker.

                                                //extra line feed
                                                System.out.println();
                                                System.out.print("Enter the radius: ");
                                                   byte newRadius = readInput.nextByte();

                                                area= pi * newRadius * newRadius;
                                                System.out.print("The area is: ");
                                                System.out.println(area);

                                                 //extra line feed
                                                System.out.println();
                                                System.out.print("What is your first name?: ");
                                                 char yourInitial = readInput.next().charAt(0);

                                              System.out.println("Hello Mr. " + yourInitial + ".");

                                                //the input buffer will still have enter character '\n'
                                                // so that needs to be cleaned.
                                                //You can do that by using .nextLine() method.
                                                readInput.nextLine();

Following code demonstrate use of printf(), and format specifiers

                                              //extra line feed
                                              System.out.println();
                                              System.out.printf("5185 is fun course.\n\n");

                                              System.out.printf("First Name \tLast Name\tCity\n");
                                              System.out.printf("----------- \t---------\t---\n");
                                              System.out.printf("Bill \tClinton \tHarlem\n");

                                             System.out.printf("\n");

                                           //extra line feed
                                           System.out.println();
                                           System.out.printf("How do you print double quotes?\n");
                                           System.out.printf("Who said\"Test Scores Can Be Used ....\"\n");

Modify the above demo code so that you are not hard coding the name, and city (Bill Clinton, Harlem etc) but, get the values from user.

a) Add a column for zip code as well
b) Declare four variables (decide on data type): First Name, Last Name, City, and Zip
c) Ask user for the values for these variables and display them instead of using the hardcoded name like Bill Clinton Harlem

Homework #2

Note: You need to know the loops before you complete some of the problems here

2.1 Here is a listing of a program, which asks a user to enter his/her age. It will print:
      a) “You are a golden” if the entered age is 50 and
      b) “You are not so golden” otherwise.

   import java.util.Scanner;
   
   public class FirstJavaHello {
         public static void main(String[] args) {
               int yourAge;

               Scanner readInput = new Scanner(System.in);
               System.out.printf("How old are you?: ");
               yourAge= readInput.nextInt();
               if (yourAge == 50)
                     System.out.printf("You are golden\n");
               else
                     System.out.printf("You are not so golden\n");
          }
    }

Modify the above program, so that it will print:
    a) “You are a kid” if the age is less than 13
    b) “You are a teenager” if the age is between 13 and 19
    c) “You are an adult” if greater than 19

2.2 Here is a calculator program. The program gives a prompt and waits for user to enter a number, operator and another number and gives the output like this:
          int firstN;
          int secondN;
          char operator;

          Scanner readInput = new Scanner(System.in);

          System.out.printf("Type a number, operator, number --"
                                 + "separated by a space: ");
          firstN = readInput.nextInt();
          operator = readInput.next().charAt(0);
          secondN = readInput.nextInt();

          if (operator == '+')
                System.out.printf("%d + %d = %d",
                      firstN, secondN, firstN + secondN);
          else if (operator == '-')
                System.out.printf("%d - %d = %d",
                        firstN, secondN, firstN - secondN);
          else if (operator == '*')
                System.out.printf("%d * %d = %d",
                        firstN, secondN, firstN * secondN);
          else if (operator == '/')
                System.out.printf("%d / %d = %d",
                      firstN, secondN, firstN / secondN);
          else if (operator == '%')
                System.out.printf("%d %% %d = %d",
                            firstN, secondN,firstN % secondN);
          else
                System.out.printf("Unknown operator");
          System.out.printf("\n\n");

Modify the above program, so that it will:
            a) Accept decimal numbers from the user instead of integers.
            b) Once the output is displayed, ask the user if they want to continue, if they say yes, then repeat the process 2.3 Ternary/conditional operator ?: works like if .. else.

Here is an example, which finds the maximum of two numbers. It shows how can it be written using if else, and ?: both.
          int max, a = 10, b = 20; // get value for a and b from user

          //using if else
          if (a > b) {
                max = a;
          }
          else {
                max = b;
          }

          //using ternary operator
          max = (a > b) ? a : b; // what is the value of max?

Re-write the above ternary operator code to find the max of three numbers, for example, a, b, and c.
Bonus, declare a, b, and c as integer variable and ask the users to enter these three values instead of hard coding them. Also, ask the user to continue if they like to find max of another set of integers.

Hint: You need to daisy chain the conditions!

Homework #3

3.1 Here is a listing of a program, use a paper computer and answer how many times each loop is executed

             a) How many times this loop is executed?

                            int i = 0;
                            while (i++ < 10) {
                                     System.out .println("Hello World: " + i);
                              }
            
             b) How many times this loop is executed if we changed the counter increment to ++i?
                            i = 0;
                            while (++i < 10) {
                                     System.out .println("Hello World: " + i);
                            }
             c) How many times this loop is executed, if it is executed immediately after the loop in #b, i.e. i is not reinitialized before the loop?
                     
                            while (++i < 10) {
                                     System.out .println("Hello World: " + i);
                            }

3.2 This program draws a box 20 characters in width and 10 characters in height, using a '-' for horizontal line and '|' for vertical line.

                            System.out .println("Using brutal force: ");
                            System.out .println("--------------------");
                            System.out .println("|                      |");
                            System.out .println("|                      |");
                            System.out .println("|                      |");
                            System.out .println("|                      |");
                            System.out .println("|                      |");
                            System.out .println("|                      |");
                            System.out .println("|                      |");
                            System.out .println("|                      |");
                            System.out .println("--------------------");

Only println() is used for this purposes. A good solution could involve a loop, which now you know. So, write the solution-using loop.
Hint: One way to solve this would be by writing a loop to draw top line and nested loops to draw the middle lines and later similar loop like top for the bottom line.

3.3 Change the while loop in 3.2 to do..while loop to print the same box.

3.4 Change the while loop in 3.3 to for-loop to print the same box.

3.5 Modify the program in 3.4 and use variables for horizontal, vertical characters instead of hard coded values like '|', '-'. Ask user for all these values height, width, and characters to draw ('|', '-') instead of using hard coded values.

3.6 Modify the program in 3.5 so that it repeats the drawing by asking user to continue. If user enters 'y' then continue drawing more boxes.

Homework #4

4.1 Write a program, which will display the menu with 5 items. It will ask the use to give their choice. It will trap all possible errors and then print the result when correct input is provided before exiting the program.

4.2 Write a program that will give the user prompt to enter two float (or double) values. If the values inputted are correct then display the inputted two values. If user enters characters instead of numbers or if they enter invalid numbers then the program will display the error message and ask the user to re-enter the correct values again. It only exits when the correct input is received and displayed.
Example user interface:

4.3 Here is a definition of integer array for 7 temperatures of the week. It is already initialized and there are variables declared for the minimum, maximum, total and average temperatures. These variables are going to be used to get the these values for this weekly temperature
          int weeklyTemp[] = { 69, 70, 71, 68, 66, 71, 70 };
          int i, max = 0, min = 0;
          float total = 0, average;
Given the above definition, write the code to:
            a) Print the daily temperature (assume, first day Sunday), e.g. The temperature on day 1 was 69:
            b) Find and print the minimum and maximum temperature of the week
            c) Calculate and print the average temperature of the week
Hint: Use loops (for or while)

Homework #5

5.1 Write a static method called getUserChoice(), which returns an integer as menu choice based on the requirement in the problem 4.1 (Homework #4). You can re-use the code you wrote from HW#4.1 or from the model answer provided. Modify the main method and all your new method getUserChoice to get the choice from user. Print the choice given by the user in the main method.

5.2 Write a static method called getTwoFloats(), which returns an array of two floats based on the problem 4.2 (Homework #4). You can re-use the code you wrote from HW#4.2 or from the model answer provided. Modify the main method to call getTwoFloats and print the two floats in the main method.

Homework #6 : A Simple Calculator
5185 Programming with Java for Beginners

Summary: Write a console program (character based) to do simple calculations (addition, subtraction, multiplication and division) of two numbers, using your understanding of Java.

Description: You need to write a program that will display a menu when it is run. The menu gives five choices of operation: addition, subtraction, multiplication, division, and a last choice to exit the program. It then prompts the user to make a choice of the calculation they want to do. Once the user selects the operation, it will check for valid menu choice (and give an appropriate message if a wrong choice was selected) and then prompts the user to enter two numbers, separated by a space. If the user enters valid numbers, it will do the operation desired, and then displays the result. If the user enters invalid numbers, it displays an error message and asks for the correct input. After displaying the result, it displays Press enter key to continue. Once enter key is pressed, it displays the menu again. The program repeats until the user selects the choice to exit.

Sample Run of the program:

Welcome to <John Doe’s> Handy Calculator
   1. Addition
   2. Subtraction
   3. Multiplication
   4. Division
   5. Exit
What would you like to do? 3

Please enter two floats to multiply, separated by a space: 24.0 4.0
Result of multiplying 24.00 and 4.00 is 96.00.

Press enter key to continue ….

Welcome to <John Doe’s> Handy Calculator
   1. Addition
   2. Subtraction
   3. Multiplication
   4. Division
   5. Exit
What would you like to do? 4

Please enter two floats to divide separated by a space: 2.0 0
You can’t divide by zero please re-enter both floats: asasfs asdfasfas
You have entered invalid floats please re-enter: 16.0 4.0
Result of dividing 16.0 by 4.00 is 4.00.

Press enter key to continue….

Welcome to <John Doe’s> Handy Calculator
   1. Addition
   2. Subtraction
   3. Multiplication
   4. Division
   5. Exit
What would you like to do? 5

Thank you for using <John Doe’s> Handy Calculator

Note:
1) Replace the <John Doe’s> with your name  My name is Seulki Lee
2) Make sure to properly word the output for the choices and result. If user selects ‘1’ from the menu, the prompt should be for “Addition’ not multiplication as shown in the example.
3) 3, 24.0 4.0 are shown in the example to emphasize that it is entered by the user and not part of the program. Underline and italics are not a requirement.
4) Your program should allow input of integer and decimal numbers (floats). The output should always be in decimals, with two decimal digits as precision.
5) Make sure your program will continue displaying the menu after the result is shown and user has pressed the enter key. Your program will exit only when user selects 5.
6) If the user selects an option other than 1-5, show a message that they must select a number between 1 and 5. Give them a chance to re-enter. Continue until a valid number is entered.
7) If they enter invalid values instead of numbers (e.g. strings), provide an error message and give them chances to re-enter. Continue until valid numbers are entered. You don/t need to worry about range of floats.
8) Make sure to catch the divide by zero issue. In the case of a division choice, the second number should not be a zero. The users should be given a second chance to enter other than a zero.
9) You should decompose your program in many static methods. So, you can call these static methods from main method to do the functionality required. Your class need not to be instantiated with a ‘new’. All methods are directly called from main of same class because they are static methods.

Submission requirement: Submit your source code. Submit all java file (Calculator. Java only)
Main Class: The public class which does the calculation must be named as Calculator and sotred in Calculator.java file.


Homework #7

Note: First complete your HW#6 and then try this homework as you can use part of the code from your HW#6 to complete this homework

Description: Convert your Midterm –A Simple Calculator Program-- into a class based program, using your knowledge of Object Oriented Programming techniques.

Write a OOPCalculator class, by giving it proper states and behaviors. For example, you can have menuChoice, firstFloat, secondFloat as member variables. You can give it behaviors like, askCalcChoice, askTwoValues, displayResults to get the choice from users, to get the numbers and display the calculation results respectively. All of the code written for calculation needs to be properly placed within these methods of the OOPCalculator class. For example: askCalcChoice first displays the menu, prompts the user to input the choice, and then waits until user presses enter. Once a valid input is entered, it returns the choice (between 1 to 5 or A for addition, S for subtraction, M for multiplication, D for division or X for exit). Similarly, other methods will implement rest of the behaviors. The users of your OOPCaluclator class do not need to know internal details of how you have implemented your behaviors. These are the only public interface exposed to the users, rest of the details stays with OOPCalculator class.

So, a driver program (written by user of your OOPCalculator or even from within main of your own class) can use your class by writing a code like this:

public class TestCalculator {
          public static void main(String[] args) {
               OOPCalculator calc = new OOPCalculator();
               while (calc. askCalcChoice () != 5){ //it will set choice
                            calc. askTwoValues ();                  //it will set two values
                            calc.displayResults();         //do calc, display result
                                                          //and wait on press enter key
               }
             calc.displayBye();            //thanks the user for using and waits for press enter key
         } //end main
} //end class

All the error checking and exception handling for a wrong choice, or wrong value input are handled by your OOPCalculator class, the user should not need to handle it.

Sample Run of the program: When the driver program is run, the behavior is exactly same as Midterm I, except, provide one more functionality. Allow user to select ‘A’ or ‘a’ for addition,’ S’ or ’s’ for subtraction,’ M’ or ‘m’ for multiplication, ‘D’ or ‘d’ for division, and ‘X’ or ‘x’ for exit, along with integer choice between 1 to 5.

Welcome to <John Doe’s> Handy Calculator

                1. Addition
                2. Subtraction
                3. Multiplication
                4. Division
                5. Exit
                What would you like to do? M

                Please enter two numbers to multiply separate by a space: 24.0 4.0
                Result of multiplying 24.00 and 4.00 is 96.00.

                Press enter key to continue ….

Welcome to <John Doe’>s Handy Calculator

                1. Addition
                2. Subtraction
                3. Multiplication
                4. Division
                5. Exit
                What would you like to do?

Continue until user selects 5, or ‘x’, or ‘X’ to exit

Solution PreviewSolution Preview

These solutions may offer step-by-step problem-solving explanations or good writing examples that include modern styles of formatting and construction of bibliographies out of text citations and references. Students may use these solutions for personal skill-building and practice. Unethical use is strictly forbidden.

public class Homework1_1 {

public static void main(String[] args) {
    int radius = 2;
    double area;
    final double pi = 3.142;
   
    area= pi * radius * radius;
   
    System.out.println("The area is: " + area);
}

}

public class Homework1_2 {

public static void main(String[] args) {
    int radius;
    double pi;
    double area;
   
    Scanner readInput = new Scanner(System.in);
   
    //extra line feed
    System.out.println();
   
    System.out.print("Enter pi: ");
    pi = readInput.nextDouble();
   
    System.out.print("Enter the radius: ");
    radius = readInput.nextInt();
   
    area= pi * radius * radius;
   
    System.out.println("The area is: " + area);
}

}


public class Homework1_3 {

public static void main(String[] args) {
    double pi;
    double area;
   
    Scanner readInput = new Scanner(System.in);
   
    //extra line feed
    System.out.println();
   
    System.out.print("Enter pi: ");
    pi = readInput.nextDouble();
   
    System.out.print("Enter the radius: ");
    byte newRadius = readInput.nextByte();
   
    area= pi * newRadius * newRadius;
    System.out.println("The area is: " + area);
   
    //extra line feed
    System.out.println();
    System.out.print("What is your first name?: ");
    char yourInitial = readInput.next().charAt(0);
   
    System.out.println("Hello Mr. " + yourInitial + ".");
   
    //the input buffer will still have enter character '\n'
    // so that needs to be cleaned.
    //You can do that by using .nextLine() method.
    readInput.nextLine();
   
    //extra line feed
    System.out.println();
    System.out.printf("5185 is fun course.\n\n");
   
    System.out.printf("First Name \tLast Name \tCity \n");
    System.out.printf("----------- \t--------- \t---   \n");
    System.out.printf("Bill       \tClinton    \tHarlem\n");
   
    System.out.printf("\n");
   
    //extra line feed
    System.out.println();
    System.out.printf("How do you print double quotes?\n");
    System.out.printf("Who said\"Test Scores Can Be Used ....\"\n");
   
    String firstName;
    String lastName;
    String city;
    String zipCode;
   
    System.out.print("What is your first name: ");
    firstName = readInput.next();
    while (firstName.length() < 11)
      firstName += " ";
    System.out.print("What is your last name: ");
    lastName = readInput.next();
    while (lastName.length() < 11)
      lastName += " ";
    System.out.print("What is your city: ");
    city = readInput.next();
    while (city.length() < 11)
      city += " ";
    System.out.print("What is your zip code: ");
    zipCode = readInput.next();
   
    System.out.printf("First Name \tLast Name \tCity       \tZip Code \n");
    System.out.printf("----------- \t--------- \t---       \t---- \n");
    System.out.printf(firstName + " \t" + lastName + " \t" + city + " \t" + zipCode + " \n");
}
}...

By purchasing this solution you'll be able to access the following files:
Solution.zip.

50% discount

Hours
Minutes
Seconds
$100.00 $50.00
for this solution

or FREE if you
register a new account!

PayPal, G Pay, ApplePay, Amazon Pay, and all major credit cards accepted.

Find A Tutor

View available Java Programming Tutors

Get College Homework Help.

Are you sure you don't want to upload any files?

Fast tutor response requires as much info as possible.

Decision:
Upload a file
Continue without uploading

SUBMIT YOUR HOMEWORK
We couldn't find that subject.
Please select the best match from the list below.

We'll send you an email right away. If it's not in your inbox, check your spam folder.

  • 1
  • 2
  • 3
Live Chats