Week 03 Answers

1.  What are the three logical operators?

&&   ||    !

 

2.  Write “truth-tables” for && and ||.

 

A        B               A && B             A || B

T         T                    T                       T

T         F                     F                       T

F         T                     F                       T

F         F                     F                       F

 

3.   Is the following boolean expression true or false?    ((3 < 5) && !(1 > 14) && (-5 < -15)) || ((6 == 6) && !(2 == 2))

False

 

4.  If s1 and s2 are variables representing Strings, what Java boolean expression is equivalent to “s1 is not the same as s2”?

!s1.equals(s2)

 

5.  What statement should be included at the top of a file in order to use the Scanner easily in the file?

import java.util.Scanner

 

6.  Write a java class called “UserInput”.  In the main method, declare three variables:  an int, a float, and a String.  Name the variables “age”, “weight”, and “name”.  Create a variable called “scan” of type Scanner, and set it equal to a new Scanner.  (Use the syntax shown in class).  Prompt the user to enter his/her age, weight, and name – read these entries in using the scanner and set the variables accordingly.  Then print the values of the three variables with appropriate labels.  For example:  “Name:  Frank     Age:  17    weight:  151.4”.

 

import java.util.Scanner;

public class UserInput {

      public static void main(String[] args) {

                  int age;

                  float weight;

                  String name;

                  Scanner scan = new Scanner(System.in);

                  System.out.print(“Enter your age: “);

                  age = scan.nextInt();

                  System.out.print(“Enter your weight: “);

                  Weight = scan.nextFloat();

                  System.out.print(“Enter your name:  “);

                  name = scan.next();

                  System.out.println(“Name: “ + name + “,  age: “ + age + “, weight: “ + weight);

      }

}

 

7.  Write a java class called “FahrenheitToCelcius”.  The main method will ask the user to enter a temperature in Fahrenheit.  (Use a variable of type “double” to store the value.)  Then calculate the equivalent temperature in Celcius, and print out a message telling the user what you found.  [Recall: C = (5/9)(F-32).]  Hint:  Be careful about doing arithmetic with integers!  Check your program by entering 212 degrees.  The output should be 100.

 

import java.util.Scanner;

public class FahrenheitToCelcius {

       

      public static void main(String[] args) {

            Scanner scanner = new Scanner(System.in);

            System.out.println("Enter temp (F): ");

            double fahrenheit = scanner.nextDouble();

            double celcius = 5.0/9.0 * (fahrenheit - 32);

            System.out.println("That is " + celcius + " degrees C.");

      }

}

 

8.  Modify the “FahrenheitToCelcius” question in the previous question so that the user can either go from F to C or vice versa.

 

import java.util.Scanner;

public class FahrenheitToCelcius {

      public static void main(String[] args) {

            Scanner scanner = new Scanner(System.in);

            System.out.print("Enter 1 to go from F to C; 2 for C to F:  ");

            int response = scanner.nextInt();

            if (response == 1) {

                  System.out.print("Enter temp (F): ");

                  double fahrenheit = scanner.nextDouble();

                  double celcius = 5.0/9.0 * (fahrenheit - 32);

                  System.out.println("That is " + celcius + " degrees C.");

            }

            else {

                  System.out.print("Enter temp (C): ");

                  double celcius = scanner.nextDouble();

                  double farenheit = celcius * 9.0 / 5.0 + 32;

                  System.out.println("That is " + farenheit + " degrees F.");

            }

      }

}

9.  FOR THIS EXERCISE, YOU SHOULD STRIVE TO AVOID REDUNDANT CODE!  Write a java class called “RequestInfo”.  The main method will ask the user to enter his species.  If the user enters “dog”, then ask him to enter the number of cats he has eaten this year.  If the user enters “cat”, ask him to enter the number of hairballs he has coughed up this year.  If the user enters “human”, ask him to enter BOTH the number of cats he has eaten this year AND the number of hairballs he has coughed up this year.  If the user enters anything else (not dog, cat or human), tell him that he is from another planet, and terminate the program.  If the user DID enter one of the three valid species (dog, cat, human) then print out a report in the following format:

          Species:  dog

              Number of cats eaten:  54

              Number of hairballs:  0

 

import java.util.Scanner;

public class RequestInfo {

      public static void main(String[] args) {

            Scanner scanner = new Scanner(System.in);

            System.out.print("What is your species?  ");

            String answer = scanner.next();

            int catsEaten = 0, hairballs = 0;

            if (answer.equals("dog") || answer.equals("cat") || answer.equals("human")) {

                  if (!answer.equals("cat")) {

                        System.out.print("How many cats have you eaten this year?  ");

                        catsEaten = scanner.nextInt();

                  }

                  if (!answer.equals("dog")) {

                        System.out.println("How many hairballs have you coughed up this year?  ");

                        hairballs = scanner.nextInt();

                  }

                  System.out.println("Species:  " + answer);

                  System.out.println("Number of cats eaten:  " + catsEaten);

                  System.out.println("Number of hairballs:  " + hairballs);

            }

            else {

                  System.out.println("You are from another planet!");

            }

      }

}

 

10.  Write a program that computes the letter grade for a student based on his/her numerical total.  The program will read in the total and compute the letter grade based on the following:  to get an A the total must be at least 90.0.  To get a B it must be at least 80.0.  For a C, at least 70.0.  For a D, at least 60.0.  Less than 60.0 is an F.

 

import java.util.Scanner;

public class LetterGrade {

      public static void main(String[] args) {

            Scanner scanner = new Scanner(System.in);

            System.out.print("What is your numerical total:  ");

            double total = scanner.nextDouble();

            char grade;

            if (total >= 90.0) {

                  grade = 'A';

              }  

            else if (total >= 80.0) {

                  grade = 'B';

            }

            else if (total >= 70.0) {

                  grade = 'C';

            }

            else if (total >= 60.0) {

                  grade = 'D';

            }

            else {

                  grade = 'F';

            }

            System.out.println("Your grade is " + grade);

      }

}

 

11.  Write a program that asks the user to enter up to four scores from 1 to 10.  At the end the program will print out the total of the scores, but without including the highest score.  The catch is that at any time the user may enter 999 to indicate that he has no more scores to report.  YOU MAY NOT USE ANY LOOPS!   For example, here are a couple of possible runs of the program:

Example 1:

Enter score 1:  5

Enter score 2:  7

Enter score 3:  9

Enter score 4:  3

The total (without the highest) was: 15

Example 2:

Enter score 1:  8

Enter score 2:  9

Enter score 3:  999

The total (without the highest) was: 8

 

 

import java.util.Scanner;

public class Scores {

      public static void main(String[] args) {

            Scanner scanner = new Scanner(System.in);

            int highest = 0;

            int total = 0;

            System.out.println("Enter up to 4 scores; use 999 if you are done.");

            System.out.print("Score 1: ");

            int score = scanner.nextInt();

            if (score != 999) {

                  if (score > highest) {

                        highest = score;

                  }

                  total = total + score;

                  System.out.print("Score 2: ");

                  score = scanner.nextInt();

                  if (score != 999) {

                        if (score > highest) {

                              highest = score;

                        }

                        total = total + score;

                        System.out.print("Score 3:  ");

                        score = scanner.nextInt();

                        if (score != 999) {

                              if (score > highest) {

                                    highest = score;

                              }

                              total = total + score;

                              System.out.print("Score 4:  ");

                              score = scanner.nextInt();

                              if (score != 999) {

                                    if (score > highest) {

                                          highest = score;

                                    }

                                    total = total + score;

                              }

                        }

                  }

            }

            total = total - highest;

            System.out.println("total (without highest) is: " + total);

      }

}

 

12.  Decide which of the following variable names are valid in Java:   dog, x11, _tomato, big$deal, how&why, 22down, aBcDeFg, _$__$, under_score, _5_$_5_hello13. 

Valid ones are:  dog, x11, _tomato, big$deal, aBcDeFg, _$__$, under_score, _5_$_5_hello

13.  Write a program that asks the user for an integer, call it n.  The program will then add up all of the integers from 1 to n and print out the total.  For example, if the user enters 4, then the output should be 10.  (Because 1 + 2 + 3 + 4 = 10).

 

Scanner s = new Scanner(System.in);

            System.out.println("Enter n: ");

            int n = s.nextInt();

            int total = 0;

            int counter = 1;

            while(counter <= n) {

                  total += counter;

                  counter++;

            }

            System.out.println("Total is: " + total);

 

14.  The factorial of an integer is the product of all positive integers that are less than or equal to it.  For example, 4 factorial is 2 * 3 * 4 = 24.  Write a program that asks the user to enter a value, n, and then prints n factorial.

 

Scanner s = new Scanner(System.in);

            System.out.println("Enter n: ");

            int n = s.nextInt();

            int product = 1;

            int counter = 2;

            while (counter <= n) {

                  product *= counter;

                  counter++;

}

            System.out.println(n + “ factorial is " + product);

 

15.  Write a program that asks the user to enter two values: x and y.  You must then compute the product of all integers from x to y.  For example, if the user has entered 10 and 7, then the output should be 5040 (because 7 * 8 * 9 * 10 = 5040).

 

Scanner s = new Scanner(System.in);

             

            System.out.println("Enter x: ");

            int x = s.nextInt();

            System.out.println("Enter y: ");

            int y = s.nextInt();

            int stepAmount;     // determines whether to count up or down

            if (x < y) {

                  stepAmount = 1;

            } else {

                  stepAmount = -1;

            }             

            int product = x;   // to accumulate the answer

            int counter = x;   // will go from x to y in steps of "stepAmount"

            while (counter != y) {

                  counter += stepAmount;

                  product *= counter;

            }

            System.out.println("Product is: " + product);

 

16.  Write a program that “simulates” the reading password process you go through while logging into a computer account.  The program will ask for a password, compare the value against two possible passwords (that are built-in), and print “Welcome” if the password provided by the user is valid. Otherwise, ask the user to enter the password again.  (This process repeats.)

 

final String password1 = "hello";

            final String password2 = "there";

             

            Scanner s = new Scanner(System.in);

            String entry;

            do {

                  System.out.println("Enter password: ");

                  entry = s.next();

            } while (!(entry.equals(password1) || entry.equals(password2)));

            System.out.println("Welcome!");

 

17.  Write a program that asks the user to enter the number of rows and columns.  It will then print out a rectangular grid of asterisks.  For example, if the user has entered 6 rows and 3 columns, then the output should be:

***

***

***

***

***

***

 

Scanner s = new Scanner(System.in);

            System.out.println("Rows: ");

            int rows = s.nextInt();

            System.out.println("Cols: ");

            int cols = s.nextInt();

            int rowCounter = 0;

            while (rowCounter++ < rows) {

                  int colCounter = 0;

                  while (colCounter++ < cols) {

                        System.out.print("*");

                  }

                  System.out.println();

            }

 

18.  Write a program that asks the user for a size (an integer).  The program will then print out four different triangles made out of asterisks of that size.  (You will need to print out spaces sometimes in front of the asterisks.)  Below is the output if the user selected size 4:

****

***

**

*

*

**

***

****

****

 ***

  **

   *

   *

  **

 ***

****

 

 

Scanner s = new Scanner(System.in);

            System.out.println("Size: ");

            int size = s.nextInt();

            int rowCounter;

             

            rowCounter = 0;

            while (rowCounter++ < size) {

                  int colCounter = 0;

                  while (colCounter++ <= size - rowCounter) {

                        System.out.print("*");

                  }

                  System.out.println();

            }

             

            System.out.println();

             

            rowCounter = 0;

            while (rowCounter++ < size) {

                  int colCounter = 0;

                  while (colCounter++ < rowCounter) {

                        System.out.print("*");

                  }

                  System.out.println();

            }

             

            System.out.println();

             

            rowCounter = 0;

            while (rowCounter++ < size) {

                  int colCounter = 0;

                  while(colCounter++ < size) {

                        if (colCounter < rowCounter) {

                                System.out.print(“ “);

                        } else {

                                Sytem.out.print(“*”);

                        }

                  }

                  System.out.println();

            }

             

            System.out.println();

             

            rowCounter = 0;

            while (rowCounter++ < size) {

                  int colCounter = 0;

                  while(colCounter++ < size) {

                        if (colCounter <= size – rowCounter) {

                               System.out.print(“ “);

                        } else {

                               Sytem.out.print(“*”);

                        }

                  System.out.println();

            }

             

19.  Write a program that asks the user for a size, and then prints out a multiplication table of that size.  (You don’t have to worry about spacing correctly, just try to get the numbers to all come out on the right rows.)  For example, if the user requests size 4, the output should be:

1 2 3 4

2 4 6 8

3 6 9 15

4 8 12 16

 

Scanner s = new Scanner(System.in);

         System.out.println("Size: ");

          

         int size = s.nextInt();

          

         int rowCounter = 0;

         while (rowCounter++ < size) {

               int colCounter = 0;

               while (colCounter++ < size) {

                     System.out.print(colCounter * rowCounter + " ");

               }

               System.out.println();

         }