If the user enters yes, here is the joke that should be displayed: "Q: Why was the computer tired when she got home?
If the user indicates no, the program should print out the below joke: "Q: Did you hear about the monkeys who shared an Amazon account?
A: They were Prime mates." Note
that you are required to use exactly one if statement and one else
statement to receive full credit on this assignment. (No else if
needed!)
Submit ComputerJokes.java to Canvas when you are finished.
Example Output:
Want to hear a bad joke (yes/no)? no
Okay. how about this one? A: They were Prime mates." Alternately,
Want to hear a bad joke (yes/no)? yes
"Q: Why was the computer tired when she got home? A: Because she had a hard drive." Assignment 8.3: What's Your Rock Star Name? (10pts) Open a new file in eclipse called RockStar Place a block comment at the top of the program with your name and the name of the assignment. Next, welcome the user and prompt for the user's first and last name, as shown below. Then greet the user by name, telling the user to Rock on!
Next, calculate the user's rock star name according to the below algorithm:
Sample Output: Enter your first name: Jennifer Enter your last name: Parrish Enter your first name: Geoff Enter your last name: Chen Assignment 7.2: Fruit Codes (10 pts) |
Letter Grade | GPA |
---|---|
A | 4.00 |
A- | 3.67 |
B+ | 3.33 |
B | 3.00 |
B- | 2.67 |
C+ | 2.33 |
C | 2.00 |
C- | 1.67 |
D+ | 1.33 |
D | 1.00 |
D- | 0.67 |
F | 0.00 |
Notice that the highest number is 4.0 and that there are no F+ or F- grades. Make sure that the highest grade number is 4.0 and that F+, F and F- are assigned 0.0 values.
Enter a letter grade: B- The numeric value is 2.67
Enter a letter grade: A+ The numeric value is 4.0
Enter a letter grade: F- The numeric value is 0.0
In the above three example runs, the user entered "B-", "A+" and "F-" (without the quotes) as the letter grades to convert.
Assignment 9.3: What's Your Sign? (10 pts)
- For this assignment, let's write an astrology program.
- Welcome the user (see sample output below)
- Prompt the user to enter a numerical value (1-12) for the month of his/her birth (see sample output)
- Prompt the user to enter a numerical value (1-31) for the day of his/her birth (see sample output)
- Using the chart below for the astrological signs, determine the user's sign based on his or her input.
- Expect to need to use if, else if and else statements.
- Expect to use logical operators (&&, ||).
- Submit your source code in a file called Sign.java to Canvas when finished
Taurus April 20-May 20
Gemini May 21 - June 21
Cancer June 22 - July 22
Virgo August 23 - September 22
Capricorn December 22 - January 19
Aquarius January 20 - February 18
Pisces February 19 - March 20
Your sample output must be identical to mine:
What's your sign?Please enter the month of your birth (1-12): 3
Please enter the day of your birth (1-31): 3
Your Sign is Pisces.
Alternately,
What's your sign?Please enter the month of your birth (1-12): 4
Please enter the day of your birth (1-31): 12
Your Sign is Aires.
Alternately,
What's your sign?Please enter the month of your birth (1-12): 100
Please enter the day of your birth (1-31): -2
Invalid Entry. Please run the program to try again.
Assignment 19.1: Getting Even More Methodical (10 pts)
- Copy and paste the starter code into a new file called EvenMore.java
- Write the required methods as described by the comments (i.e. you fill in the body of the method).
- Then, run the code when you are finished to see if you wrote the methods correctly.
- Check the test results and make any alterations to your methods as necessary.
- When all of the tests pass, upload your code to Canvas.
* @author
* CIS 36A
*
*/
import java.util.Scanner;
public class EvenMore {
/*
Given a String, return true if the String starts
with "hi" and false otherwise.
startHi("hi there") → true
startHi("hi") → true
startHi("hello hi") → false
*/
public static boolean startHi(String str) {
return false;
}
/*
Given a String and a non-negative int n,
the front of the String is the first 3 chars,
or whatever is there if the string is less than length 3
Return n copies of the front;
Hint: use a for loop and string concatenation
frontTimes("Chocolate", 2) → "ChoCho"
frontTimes("Abcd", 3) → "AbcAbcAbc"
frontTimes("Oy", 4) → "OyOyOyOy"
*/
public static String frontTimes(String str, int n) {
return "";
}
/*
Given 2 int values, return whichever value is nearest to the value 10,
or return 0 in the event of a tie.
Hint: recall that Math.abs(n) returns the absolute value of a number.
close10(8, 13) → 8
close10(13, 8) → 8
close10(13, 7) → 0
*/
public static int close10(int a, int b) {
return 0;
}
/*
Given a String, return true if the first instance of "x" in
the String is immediately followed by another "x".
Hint: use a for loop and substring
doubleX("axxbb") → true
doubleX("axaxax") → false
doubleX("xxxxx") → true
*/
public static boolean doubleX(String str){
return false;
}
public static void main(String[] args)
{
String value;
boolean result;
int num;
System.out.println("***Testing startHi***\n");
result = startHi("hi there");
System.out.println("Should be true: " + result);
result = startHi("hi");
System.out.println("Should be true: " + result);
result = startHi("hello hi");
System.out.println("Should be false: " + result +"\n");
System.out.println("***Testing frontTimes***\n");
value = frontTimes("Chocolate", 2);
System.out.println("Should be ChoCho: " + value);
value = frontTimes("Abcd", 3);
System.out.println("Should be AbcAbcAbc: " + value);
value = frontTimes("Oy", 4);
System.out.println("Should be OyOyOyOy: " + value + "\n");
System.out.println("***Testing close10***\n");
num = close10(8, 13);
System.out.println("Should be 8: " + num);
num = close10(13, 8);
System.out.println("Should be 8: " + num);
num = close10(13, 7);
System.out.println("Should be 0: " + num + "\n");
System.out.println("***Testing doubleX***\n");
result = doubleX("axxbb");
System.out.println("Should be true: " + result);
result = doubleX("axaxax");
System.out.println("Should be false: " + result);
result = doubleX("xxxxx");
System.out.println("Should be true: " + result + "\n");
System.out.println("***End of Tests***");
}
}
- Let's write a program, in a file named ValidEmail2.java, to check an email address to see if it is valid.
- For the purposes of this assignment, we will use three criteria to determine if an email address is valid:
- The address must end with one of the following extensions: .com, .org or .edu
- The address must not contain a space
- The address must have an @ character contained somewhere in the String
- You will write 3 methods and 3 Javadoc comments. Each method will check each of the above conditions.
- Your first method signature should look like this:
public static boolean validExtension(String address) {
//method body will go here
}
- The second method signature should look like this:
public static boolean containsSpace(String address) {
//method body will go here
- The third method signature should look like this:
public static boolean containsAt(String address) {
//method body will go here
- Hint: Do not alter the starter code, given below, in any way. Your job is only to add to it where indicated.
- Additionally, you are not allowed to use any String methods other than length(), charAt() or substring() in your solution.
- You are also not allowed to use anything we have not covered in class, otherwise you will get no credit for this assignment.
* @author Name
*/
import java.util.Scanner;
public class ValidEmail2 {
public static void main(String[] args) {
String address;
Scanner input = new Scanner(System.in);
System.out.print("Enter your email address: ");
address = input.nextLine();
if (!containsAt(address)) { // the method will return true or false so
// we can check in an if statement
System.out.println("Invalid email. Your email address must contain an @ symbol");
} else if (false) { // replace false with method call here
System.out.println("Invalid email. Your email address cannot contain a space");
} else if (false) { // replace false with method call here
System.out.println("Invalid email. Your email must contain a .com, .edu or .org extension");
} else {
System.out.println("Your email address is valid.");
}
}
// write method body here
return false;
}
//Write JAVADOC comment here for containsSpace
// write method body here
return false;
}
// write method body here
return false;
}
}
Invalid email. Your email address must contain an @ symbol
Sample Output:
Invalid email. Your email address cannot contain a space
Sample Output:
Invalid email. Your email must contain a .com, .edu or .org extension
Sample Output:
Your email address is valid.
- Your task is to write a calculator program that can perform 10 different operations.
- Each of the operations needs to be its own method
- You
may optionally write a method to handle Input Validation for input
mismatch exceptions (when user enters a String and you expect a
numerical input).
- Your program will begin by welcoming the user and listing the different operations it can perform (please see sample output below).
- The methods you need to write are as follows:
Note: Do not use any of the methods from the Math class here. You must write your own ceiling, floor, power, absolute value methods.
Enter the first number: ten
Enter the first number: 10
Enter a number: ten
Enter a number: -10
Enter a number: ten
Enter a number: 10.1
Alternately:
Enter the first number: ten
Enter the first number: 10
Enter a number: ten
Enter a number: 10.9
Alternately:
Enter the first number: ten
Enter the first number: 10
Alternately:
Enter the first number: ten
Enter the first number: 10
Alternately:
Enter the first number: ten
Enter the first number: 10
Alternately:
Enter the first number: two
Enter the first number: 2
Alternately:
Enter the first number: ten
Enter the first number: 10
Assignment 18.2: Getting More Methodical (10 pts)
- Copy and paste the starter code into a new file called More.java
- Write the required methods as described by the comments (i.e. you fill in the body of the method).
- Then, run the code when you are finished to see if you wrote the methods correctly.
- Check the test results and make any alterations to your methods as necessary.
- When all of the tests pass, upload your code to Canvas.
* @author
* CIS 36A
*
*/
import java.util.Scanner;
public class More {
/**
* Given a string, take the last char and return a new String with the last char added at the front and back,
* so "cat" yields "tcatt". The original string will be length 1 or more.
* backAround("cat") → "tcatt"
* backAround("Hello") → "oHelloo"
* backAround("a") → "aaa"
* @param str the input String
* @return a new String with the last char added to front and back
*/
public static String backAround(String str) {
return "";
}
/**
* Given 2 strings, a and b, return a String of the form short+long+short,
* with the shorter String on the outside and the longer String on the inside.
* The Strings will not be the same length, but they may be empty (length 0).
* comboString("Hello", "hi") → "hiHellohi"
* comboString("hi", "Hello") → "hiHellohi"
* comboString("aaa", "b") → "baaab"
* @param a the first String to combine
* @param b the second String to combine
* @return a new String short+long+short
*/
public static String comboString(String a, String b)
{
return "";
}
/**
* Given a String of even length, return a String
* made of the middle two chars, so the String
* "string" yields "ri".
* Note: You can assume the String length will be at least 2.
* middleTwo("string") → "ri"
* middleTwo("code") → "od"
* middleTwo("Practice") → "ct"
* @param str the String to extract the middle
* @return the middle of the String
*/
public static String middleTwo(String str){
return "";
}
/**
* Given a string, return a new String made of 3 copies of the last 2 chars of the original String.
* The String length will be at least 2.
* extraEnd("Hello") → "lololo"
* extraEnd("ab") → "ababab"
* extraEnd("Hi") → "HiHiHi"
* @param str the String to copy
* @return the repeated characters
*/
public static String extraEnd(String str) {
return "";
}
/**
* Given a String, determines whether the given character is in the String
* contains('@', "bob@jobs.com") → true
* contains('@', "bobajobs.com") → false
* contains('2', "tr2dat") → true
* @param c the character to locate in the String
* @param s the String to search
* @return whether c is in s
*/
public static boolean contains(char c, String s) {
return false;
}
public static void main(String[] args)
{
String value;
boolean b;
System.out.println("***Testing backAround***\n");
value = backAround("cat");
System.out.println("Should print tcatt: " + value);
value = backAround("Hello");
System.out.println("Should print oHelloo: " + value);
value = backAround("a");
System.out.println("Should print aaa: " + value +"\n");
System.out.println("***Testing comboString***\n");
value = comboString("Hello", "hi");
System.out.println("Should be hiHellohi: " + value);
value = comboString("hi", "Hello");
System.out.println("Should be hiHellohi: " + value);
value = comboString("aaa", "b");
System.out.println("Should be baaab: " + value + "\n");
System.out.println("***Testing middleTwo***\n");
value = middleTwo("string");
System.out.println("Should be ri: " + value);
value = middleTwo("code");
System.out.println("Should be od: " + value);
value = middleTwo("Practice");
System.out.println("Should be ct: " + value + "\n");
System.out.println("***Testing extraEnd***\n");
value = extraEnd("Hello");
System.out.println("Should be lololo: " + value);
value = extraEnd("ab");
System.out.println("Should be ababab: " + value);
value = extraEnd("feet");
System.out.println("Should be etetet: " + value + "\n");
System.out.println("***Testing contains***\n");
b = contains('@', "bob@jobs.com");
System.out.println("Should be true: " + b);
b = contains('@', "bobajobs.com");
System.out.println("Should be false: " + b);
b = contains('2', "tr2dat");
System.out.println("Should be true: " + b);
System.out.println("***End of Tests***");
}
}
Assignment 18.3: Taco Tuesdays (10 pts)
- Write a program to calculate the total price of purchasing a meal from the Vegan Veganos Mexican food truck, that pops up around San Jose.
- Name your program Tacos.java
- For this program, you will need to write 3 methods, as follows:
- Takes in a double parameter for the price of the food.
- Takes in a second double parameter for the percent tip
- calls the addTax method to add taxes to the price.
- calls the addTip method to add the tip to the price.
- Displays the price to two decimal places along with the message "With taxes and tip, your total comes to $<price>"
- returns nothing
addTax
- Takes in a double parameter for the subtotal for the food.
- Calculates the tax, assuming the tax rate is 9.25% in San Jose
- adds the tax onto the the total price,
- returns the update price
addTip
- Takes in a double parameter for the current bill (price of food + tax).
- Takes in a second double parameter for the percent tip
- Calculates the tip and adds the tip onto the the total price
- returns the updated price
Additional Specifications
- Each method must also have a full Javadoc comment in the style described in class or you will lose 3 points.
- Important: You should call the formatTotal method inside of main, not the other two methods.
- The other 2 methods should be called inside of the formatTotal method.
- Hint: addTip will work very similarly to the addTax method
- Note:
If the user does not select option A, B, or C for the tip, you should
automatically assign a tip of 20% (as shown in the second sample output
below).
* @author FILL IN YOUR NAME HERE
* CIS 36A
*/
import java.util.Scanner;
public class Tacos {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int numTacos;
int numHorchatas;
int numNachos;
final double PRICE_TACOS = 4.25;
final double PRICE_HORCHATAS = 5.00;
final double PRICE_NACHOS = 14.50;
final double SUBTOTAL, TIP;
String choice;
System.out.println("Welcome to Vegan Veganos!\n");
System.out.print("Enter the number of tacos: ");
numTacos = input.nextInt();
System.out.print("Enter the number of nachos: ");
numNachos = input.nextInt();
System.out.print("Enter the number of horchatas: ");
numHorchatas = input.nextInt();
}
- Your program should work identically to the following:
Enter the number of tacos: 4
Enter the number of nachos: 2
Enter the number of horchatas: 2
A: 10%
B: 15%
C: 20%
Enter your choice: B
You selected 15%
With taxes and tip, your total comes to $70.36.
Thank you! Please come again!
- Alternately:
Enter the number of tacos: 5
Enter the number of nachos: 0
Enter the number of horchatas: 5
Would you like to tip:
A: 10%
B: 15%
C: 20%
Enter your choice: Z
You selected 20%
With taxes and tip, your total comes to $60.63.
Thank you! Please come again!
- Alternately,
Enter the number of tacos: 4
Enter the number of nachos: 6
Enter the number of horchatas: 10
Would you like to tip:
A: 10%
B: 15%
C: 20%
Enter your choice: A
You selected 10%
With taxes and tip, your total comes to $185.07.
Thank you! Please come again!
- When your program works as shown above, submit it to Canvas.
Assignment 19.2: Number of Numbers (10 pts)
- For this assignment you will be working with arrays.
- Open a new Java project called Nums
- Prompt a user to enter in the length of the array (the number of numbers).
- Use this information to declare an array of the user-specified length.
- Next, using a for loop, prompt the user to enter that many numbers, and store each one in your array until your array is at full capacity.
- Using the same, or a second, for loop, sum the numbers and report their sum to the user.
- Also, multiply the numbers together and report their product to the user.
- The sum and the product should be printed to one decimal value only.
- Your program should work identically to the sample output below:
Enter the number of numbers: 4
Enter 4 numbers:
Number 1: 3.2
Number 2: 6.7
Number 3: 2.9
Number 4: 4.6
The sum of the numbers is: 17.4
And the product is: 286.0
- Another run of the program might give the following output:
Enter the number of numbers: 8
Enter 8 numbers:
Number 1: 2.1
Number 2: -5.6
Number 3: 9.0
Number 4: 8.7
Number 5: -2.2
Number 6: 8.2
Number 7: 9.5
Number 8: 1.4
The sum of the numbers is: 31.1
And the product is: 220931.3
- Upload Nums.java to Canvas when you are finished.
Assignment 19.3: Billboard Top 10 Songs of June, 2019 (10 pts)
- In
this assignment we will write a program that stores 10 Strings in a
String
array -- representing the Billboard top 10 songs of June, 2019 -- and 10
doubles in a double array (duration of the song) and then writes the
contents of
the two arrays to the console.
- Create a new Java file, and save it as
Billboard.java
. - At the top of main declare a String array named titles of length 10.
- Then, declare a double array of length 10 named durations.
- Store the following values in the String array, one at each index:
- Remember: you can do this, using either static or non-static intialization.
- Next, store the following song durations in the double array, one at each index:
3.26
3.14
3.43
3.20
- Next, print the contents of the arrays to the console.
- First, inside of main, add the following print statement:
System.out.println("Billboard Top 10 Tracks:");
- Next, write a method that prints out the the two arrays.
- Copy and paste the below javadoc comment and method signature outside of main:
- Inside
your method, you will need a for loop to print the arrays to the
console, side-by-side, as shown below, with the duration in parenthesis,
displayed to two decimal places:
Bad Guy (3.26)
Talk (3.14)
I Don't Care (3.43)
Sucker (3.20)
Sunflower (2.42)
Wow (2.38)
Dancing with a Stranger (3.16)
Suge (3.45)
Sweet But Psycho (3.28)
- See the class notes if you get stuck for an example of using for loops with arrays or how to write a method to display an array to the console.
- Next,
below your System.out.print statement for the Billboard Top 10 Tracks,
call the printArrays method, passing it the two arrays as arguments.
- Finally, compile and run your code and verify that the following output appears in the console window:
Billboard Top 10 Tracks
Old Town Road (1.54)
Bad Guy (3.26)
Talk (3.14)
I Don't Care (3.43)
Sucker (3.20)
Sunflower (2.42)
Wow (2.38)
Dancing with a Stranger (3.16)
Suge (3.45)
Sweet But Psycho (3.28)
- Submit your
Billboard.java
program to Canvas when you are finished.
Assignment 19.2: Billboard Top 10 Songs of November, 2019 (10 pts)
- In
this assignment we will write a program that stores 10 Strings in a
String
array -- representing the Billboard top 10 songs of November, 2019 -- and 10
doubles in a double array (duration of the song) and then writes the
contents of
the two arrays to the console.
- Create a new Java file, and save it as
Billboard.java
. - At the top of main declare a String array named titles of length 10.
- Then, declare a double array of length 10 named durations.
- Store the following values in the String array, one at each index:
- Remember: you can do this, using either static or non-static intialization.
- Next, store the following song durations in the double array, one at each index:
3.26
3.14
3.43
3.20
- Now, inside of main, add the following print statement:
System.out.println("Billboard Top 10 Tracks:");
- Next, write a method that prints out the the two arrays.
- Copy and paste the below javadoc comment and method signature outside of main:
- Inside
your method, you will need a for loop to print the arrays to the
console, side-by-side, as shown below, with the duration in parenthesis,
displayed to two decimal places:
Circles (3.26)
Memories (3.20)
Lose You to Love Me (3.16)
- See the class notes if you get stuck for an example of using for loops with arrays or how to write a method to display an array to the console.
- Next,
below your System.out.print statement for the Billboard Top 10 Tracks,
call the printArrays method, passing it the two arrays as arguments.
- Finally, compile and run your code and verify that the following output appears in the console window:
Billboard Top 10 Tracks
Someone You Loved (1.54)
Circles (3.26)
Senorita (3.14)
Good as Hell (3.43)
Memories (3.20)
Truth Hurts (2.42)
No Guidance (2.38)
Lose You to Love Me (3.16)
Panini (3.45)
10,000 Hours (3.28)
- Submit your
Billboard.java
program to Canvas when you are finished.
Assignment 5.2: Applying Integer Division and Modulus (10 pts)
- In Java dividing one integer by another truncates the remainder,
which removes the decimal part. To compute the integer remainder, we use
the remainder operator (
%
), also known as the modulus operator. - The
%
operator finds the remainder after division of one number by another. The Java expressiona % b
(pronounced a mod b) returns the remainder of the division ofa
byb
if both numbers are positive. For example:
3 r 1 2 ) 7 -6 1 remainder
- For this assignment we will use both the division and remainder operators to extract single digits form an integer number.
- Write a program that gets three numbers from the user and then sums:
- the hundreds digit of the first number
- with the tens digit of the second number and
- the unit digit of the third number.
-
For example, the sum of the diagonal digits of the following three
numbers is 3 because the numbers are all 1 on the diagonal as shown by
the highlight.
123 416 781
- Name the source code file Remainder.java and include all your code in this single file.
- Be careful of the spelling, including capitalization, as you will
lose points for a misspelled name. Naming is important in programming.
Enter first number: 123 Enter second number: 416 Enter third number: 781 Sum of diagonal digits is 3
Enter first number: 123 Enter second number: 456 Enter third number: 789 Sum of diagonal digits is 15
Enter first number: 134 Enter second number: 56 Enter third number: 789 Sum of diagonal digits is 15
Enter first number: 1 Enter second number: 2 Enter third number: 3 Sum of diagonal digits is 3
In the above example output, the user entered the values shown in aqua italics (for emphasis) to produce the output. Your program does NOT print the characters in aqua italics, nor does the user input appear in aqua italics.
Notice the fourth example. Entering a 1 is the same as 001. Similarly, entering a 2 is the same as entering 002 and entering a 3 is the same as entering 003. Thus arranging the three numbers in a matrix of rows and columns shows us how the answer was derived.
001 002 003
- Ask the user for the three integer numbers, and no other input, as shown in the Example Output.
- Use the division operator (
/
) and remainder operator (%
) to extract digits from the numbers entered by the user. - Example Output: The input prompts and outputs of the program must look like the following for full credit, including the same order of input and same wording of the output. For the input shown you must get the same output. However, the output must change properly if the inputs are different.
- After displaying the output, exit the program.
- Do not use
if
-statements, strings or techniques we have not covered. - Submit Remainder.java to Canvas when your program works as shown.
Assignment 6.2: Catchy Headlines (10 pts)
- With
so many competing news sources onf the internet, newspaper and magazine
publishers need catchy headlines to attract the attention of readers.
- In this assignment, you will write a program to produce suggested headlines based on a topic selected by the user.
- Write a program that produces the following five (5) headlines based on user input of a topic and number:
[number] Reasons [topic] Will Change The Way You Think About Everything!
You Will Never Believe This Awesome Truth Behind [topic]
Here's What No One Tells You About [topic]
[number] Ways [topic] Can Help You Live To 100!
- The name of the source code file for this program must be Headlines.java (note the capitalization of the H in Headlines).
- Be careful of the spelling, including capitalization, as you will lose points for a misspelled name. Naming is important in programming.
- Ask the user for the following inputs (and no other input) in this order:
- Single word topic
- Integer number between 3 and 20
- Assume the user only enters correct data.
- The words [topic] and [number] (shown in square brackets above for emphasis) must be replaced by the user input.
- Note that your program output should change depending on the input typed by the user.
- Once your program is working properly, submit Headlines.java to Canvas.
Mr. Boole is a college professor and you have been invited to his home for tea.
During your visit you can discuss anything you want. However, when he
asks what you want for tea, you must answer true
or false
to his questions. In this assignment, you will write a program to simulate
asking questions about how you want your tea and then summarize the
beverage choice.
Project Specifications
- Complete each of the following Boolean logic problems and code your
solutions into the worksheet after the labeling comments. See the
Example Runs to verify the correctness of each computation.
- Ask for a second teaspoon of sugar only if the first teaspoon of sugar was requested.
- If black tea is requested print "Black tea", otherwise print "Green tea".
- If milk is requested, print ", with milk". If milk is not requested print ", no milk". Otherwise do not print anything.
- If sugar is requested print ", and".
- If no sugar is requested print " unsweetened". Otherwise print either ("one" or "two") teaspoons of sugar depending on the amount of sugar requested.
- Example Output: The input prompts and outputs of the program must look like the following for full credit, including the same order of input and exact wording of the output. For the input shown you must get the same output. However, the output must change properly if the inputs are different.
We have two types of tea, Black and Green. Would you like Black tea? true Would you like milk in your tea? true Would you like sugar? true Would you like more sugar? false Black tea, with milk, and one teaspoon of sugar.
We have two types of tea, Black and Green. Would you like Black tea? true Would you like milk in your tea? true Would you like sugar? true Would you like more sugar? true Black tea, with milk, and two teaspoons of sugar.
We have two types of tea, Black and Green. Would you like Black tea? false Would you like milk in your tea? false Would you like sugar? false Green tea, no milk, unsweetened.
In the above example outputs, the user entered the values shown in aqua italics (for emphasis) to produce the output. Your program does NOT print the characters in aqua italics, nor does the user input appear in aqua italics.
- Hint: Use the nextBoolean() method for the Scanner.
- After displaying the output, exit the program.
- Submit the source code file
Tea.java
Assignment 9.3: Fruit Codes - Redux (10 pts)
- 70% of the produce sold in the U.S. contains pesticide residues [1].
- One large study published in the respected medical journal JAMA, found that people who consumed the most organic foods had 25% fewer cancers than those who ate no organic food [2].
- Additionally, foods that are genetically modified tend to be sprayed with large amounts of weed killers [3].
- Regardless
of these concerns, most nutrition experts agree that eating fruits and
vegetables - either conventional or organic - in large quantities is one
of the most important things you can do for your health [4]
- Write a program to read in the code printed the sticker on a piece of fruit and print out whether the fruit was grown organically, or conventionally or was genetically modified.
- The
program should prompt the user to enter the numeric code on the fruit's
sticker, and then read in the user's response as a String.
- Codes that are 4 digits long indicate that the fruit has been grown conventionally.
- In this case, print the message: "Your fruit was grown conventionally, with the use of pesticides and chemicals."
- Codes that are 5 digits long, and start with an 8, indicate that the fruit has been genetically modified.
- In this case, print the message: "Your fruit was genetically modified."
- Codes that are 5 digits long, and start with a 9, indicate that the fruit was grown organically.
- In this case, print the message: "Your fruit was not genetically modified, and was grown according USDA organic standards."
- Codes that do not follow the above format are considered invalid.
- Name your file Fruit.java.
- The program should work identically to the sample output below.
- Additionally, your code should use exactly one if, two else ifs and one else.
- For full credit, you must use the String methods covered in class in your solution to this assignment.
Your fruit was not genetically modified, and was grown according USDA organic standards.
Sample Output:
Your fruit was grown conventionally, with the use of pesticides and chemicals.
- When your program is working as shown above and meets the specified requirements, submit it to Canvas.
- Remember our class activity where we calculated a user's weight on the moon
- Let's update the program to calculate a user's weight on different planets.
- Create a Java file called Planet.java.
- Our assignment will make use of skills you used last class:
- Switch statements
- Final variables - avoid magic numbers!
- Decimal formatting (printf)
- Begin your program by declaring a double variable named weight, and a String variable named planet.
- You will need to write a switch statement with a series of cases, like the following:
switch(planet) {
}
- Your default clause gives you the opportunity to do some error checking on the user input.
- If the user inputs an invalid planet, you should output the message: You entered an invalid name for a planet. Please re-run the program to try again.
- To provide the proper weight, you will need to know the conversion rate for each of the planets. The conversion is as follows:
- Mercury - multiply by 0.38
- Venus - multiply by 0.91
- Mars - multiply by 0.38
- Jupiter - multiply by 2.54
- Saturn - multiply by 1.08
- Uranus - multiply by 0.91
- Neptune - multiply by 1.19
- Pluto - multiply by 0.06
- Note that to avoid magic numbers, you will need to declare a final variable for each of the multipliers above. Your final variables should look like this:
- Important: The output for the weight should only have one number after the decimal point. Therefore, you need to make use of System.out.printf to print out the weights rather than println
- Your program should work identically to the following, except user input will vary:
- Alternately, your program should output the following if the user provides an invalid entry:
- Create a new Java file called AB.java.
- In this assignment, we are going to write another program that uses one
for
loop. - Within the for loop, declare a variable A to count from -5.0 to 5.0, counting by 0.5.
- Inside the body of the loop, set another variable B to be the current value of A raised to the fifth power.
- For output, you will need to display the current values of both A and B in a chart, as shown below.
- Note that you should print out "A" above the A column and "B" above the B column.
- Also, you should display the values to exactly one decimal point.
- You will need to use \t, System.out.printf and the Math.pow(base,exp)in your program to receive full credit for this assignment.
- When you are finished, upload your source code to Canvas.
-5.0 -3125.0
-4.5 -1845.3
-4.0 -1024.0
-3.5 -525.2
-3.0 -243.0
-2.5 -97.7
-2.0 -32.0
-1.5 -7.6
-1.0 -1.0
-0.5 -0.0
0.0 0.0
0.5 0.0
1.0 1.0
1.5 7.6
2.0 32.0
2.5 97.7
3.0 243.0
3.5 525.2
4.0 1024.0
4.5 1845.3
5.0 3125.0
Assignment 11.1: Valentine Loop (10 pts)
- Create a new Java file Valentine.java.
- Write a program that uses a while loop to print the numbers from 1 to 150, with each number printed on its own line.
- For multiples of 3, print "Roses are red." instead of the number.
- For the multiples of 5, print "Violets are blue." instead of the number.
- For numbers which are multiples of both 3 and 5, print "Sugar is sweet, and so are you!".
- You must use a while loop for full credit.
- Hint: Test for numbers that are multiples of both 3 and 5 first.
- When you are finished, and your output looks identical to mine, upload your assignment to Canvas.
2
Roses are red.
4
Violets are blue.
Roses are red.
7
8
Roses are red.
Violets are blue.
11
Roses are red.
13
14
Sugar is sweet, and so are you!
16
17
Roses are red.
19
Violets are blue.
Roses are red.
22
23
Roses are red.
Violets are blue.
26
Roses are red.
28
29
Sugar is sweet, and so are you!
31
32
Roses are red.
34
Violets are blue.
Roses are red.
37
38
Roses are red.
Violets are blue.
41
Roses are red.
43
44
Sugar is sweet, and so are you!
46
47
Roses are red.
49
Violets are blue.
Roses are red.
52
53
Roses are red.
Violets are blue.
56
Roses are red.
58
59
Sugar is sweet, and so are you!
61
62
Roses are red.
64
Violets are blue.
Roses are red.
67
68
Roses are red.
Violets are blue.
71
Roses are red.
73
74
Sugar is sweet, and so are you!
76
77
Roses are red.
79
Violets are blue.
Roses are red.
82
83
Roses are red.
Violets are blue.
86
Roses are red.
88
89
Sugar is sweet, and so are you!
91
92
Roses are red.
94
Violets are blue.
Roses are red.
97
98
Roses are red.
Violets are blue.
101
Roses are red.
103
104
Sugar is sweet, and so are you!
106
107
Roses are red.
109
Violets are blue.
Roses are red.
112
113
Roses are red.
Violets are blue.
116
Roses are red.
118
119
Sugar is sweet, and so are you!
121
122
Roses are red.
124
Violets are blue.
Roses are red.
127
128
Roses are red.
Violets are blue.
131
Roses are red.
133
134
Sugar is sweet, and so are you!
136
137
Roses are red.
139
Violets are blue.
Roses are red.
142
143
Roses are red.
Violets are blue.
146
Roses are red.
148
149
Sugar is sweet, and so are you!
- Write a program that allows a user to enter a sentence and then the position of two characters in the sentence.
- The program should then report whether the two characters are identical or different.
- When the two characters are identical, the program should display the message:
- Note that <char> should be replaced with the characters from the String. See example output below for more information.
- When the two characters are different, the program should display the message:
- Name your program CharComp.java
- Your program must use a do-while loop to allow the user to enter a series of sentences, or "X" to exit.
- The program should accept both lower and upper case "X" as an indication the user wishes to exit the program.
- Please see example output below
- It should also verify that the user provides numerical input for the positions of the characters in the String.
- Hint: Use a while loop and !input.hasNextInt() to check for input mismatch exception.
- See Lesson 15 notes for a discussion on input mismatch exception
- You will need two while loops, one for each input.nextInt() statement for the numeric location of each character in the String
- Important:
Note that you will need to use input.nextLine() to account for the fact
that the loop causes an input.nextInt() to come before an
input.nextLine().
- See lesson 15 notes regarding the problem that can occur when you use input.nextInt() before an input.nextLine()
- When your program runs identically to the example output below, submit it to Canvas.
Enter a sentence or X to exit: Let's have cake and ice cream for dinner!
Enter the numeric location of the first letter: 1
Enter the numeric location of the second letter: 9
e and e are identical.
Enter a sentence or X to exit: "Flight Behavior" is a good book.
Enter the numeric location of the first letter: six
Error! Enter a number, not text!
Enter the numeric location of the first character: six
Error! Enter a number, not text!
Enter the numeric location of the first character: six
Error! Enter a number, not text!
Enter the numeric location of the first character: 6
Enter the numeric location of the second letter: 10
t and h are unique characters.
Enter a sentence or X to exit: Summer vacation is almost here!
Enter the numeric location of the first letter: 2
Enter the numeric location of the second letter: three
Error! Enter a number, not text!
Enter the numeric location of the second character: three
Error! Enter a number, not text!
Enter the numeric location of the second character: three
Error! Enter a number, not text!
Enter the numeric location of the second character: 3
m and m are identical.
Enter a sentence or X to exit: x
Goodbye!
Important: To receive credit, you must only use concepts and material presented in class. It is your responsibility to stay current with the course material. Any assignment that contains Java code that was not demonstrated in class will result in your assignment receiving a 0.
- Both partners fill in, sign, date, and submit the pair programming contract
- Only one partner submit the code.
- Upload the document(s) along with your Lab code to Canvas.
- Please make sure both your names are on your file (hint: use a proper Javadoc comment)
- If you need help finding a partner, please contact me as soon as possible.
Money Matters
- Write a program in a file Money.java
- Begin with a correct Javadoc comment including your name and your partner's name, and the Assignment number.
- The purpose of this program is to convert a cost input for a particular product into dollars and cents.
- Ask the user to type in both a product and how much it costs in decimal numbers.
- Then print the price written as dollars and cents.
- Required: store the cost as a String to take advantage of the String methods length() and charAt().
- Required: use exactly one if statement and one else statement (the use of two if statements and the use of else if are both disallowed).
- The use of else if will result in a 0 on this assignment.
- The use of String methods we did not cover in class will result in a 0 on this assignment.
- Note that you can assume the user will always enter a price between $10.00 and $999.99
- Your program should work identically to the examples below (except the user may input different values):
Sample Output:
Enter the name of a product: bulk bubble gum
Enter the price: $29.95 bulk bubble gum cost is 29 dollars and 95 cents.
Sample Output:
Enter the name of a product: the iPhone 8
Enter the price: $295.35 the iPhone 8 cost is 295 dollars and 35 cents.
- When your program is complete, please upload it to Canvas.