Question

In: Computer Science

// TASK #2 Add an import statement for the Scanner class // TASK #2(Alternate) // Add...

// TASK #2 Add an import statement for the Scanner class
// TASK #2(Alternate)
// Add an import statement for the JOptionPane class

/**
This program demonstrates how numeric types and
operators behave in Java.
*/

public class NumericTypes
{
public static void main (String [] args)
{
// TASK #2 Create a Scanner object here
// (not used for alternate)

// Identifier declarations
final int NUMBER = 2 ; // Number of scores
final int SCORE1 = 100; // First test score
final int SCORE2 = 95; // Second test score
final int BOILING_IN_F = 212; // Boiling temperature
int fToC; // Temperature Celsius
double average; // Arithmetic average
String output; // Line of output

// TASK #2 declare variables used here
// TASK #3 declare variables used here
// TASK #4 declare variables used here

// Find an arithmetic average.
average = (SCORE1 + SCORE2) / NUMBER;
output = SCORE1 + " and " + SCORE2 +
" have an average of " + average;
System.out.println(output);

// Convert Fahrenheit temperature to Celsius.
fToC = 5/9 * (BOILING_IN_F - 32);
output = BOILING_IN_F + " in Fahrenheit is " +
fToC + " in Celsius.";
System.out.println(output);
System.out.println(); // To leave a blank line

// ADD LINES FOR TASK #2 HERE
// Prompt the user for first name
// Read the user's first name
// Prompt the user for last name
// Read the user's last name
// Concatenate the user's first and last names
// Print out the user's full name

System.out.println(); // To leave a blank line

// ADD LINES FOR TASK #3 HERE
// Get the first character from the user's first name
// Print out the user's first initial
// Convert the user's full name to uppercase
// Print out the user's full name in uppercase

System.out.println(); // To leave a blank line

// ADD LINES FOR TASK #4 HERE
// Prompt the user for a diameter of a sphere
// Read the diameter
// Calculate the radius
// Calculate the volume
// Print out the volume
}
}

Task #2a Using the Scanner Class for User Input (4 pts)
⦁   Add an import statement above the class declaration to make the Scanner class available to your program.
⦁   In the main method, create a Scanner object and connect it to the System.in object.
⦁   Prompt the user to enter his or her first name.
⦁   Read the name from the keyboard using the nextLine method and store it into a variable called firstName (you will need to declare any variables you use).
⦁   Prompt the user to enter his or her last name.
⦁   Read the name from the keyboard and store it in a variable called lastName.
⦁   Concatenate the firstName and lastName with a space between them and store the result in a variable called fullName.
⦁   Print out the fullName.
⦁   Compile, debug, and run, using your name as test data.
⦁   Since we are adding on to the same program, each time we run the program we will get the output from the previous tasks before the output of the current task.
Task #2b (alternate) Using Dialog Boxes for User Input (4 pts)
⦁   Add an import statement above the class declaration to make the JOptionPane class available to your program.
⦁   In the main method, prompt the user to enter his or her first name by displaying an input dialog box and storing the user input in a variable called firstName (you will need to declare any variables you use).
⦁   Prompt the user to enter his or her last name by displaying an input dialog box and storing the user input in a variable called lastName.
⦁   Concatenate the firstName and lastName with a space between them and store the result in a variable called fullName.
⦁   Display the fullName using a message dialog box.
⦁   Compile, debug, and run, using your name as test data.
⦁   Since we are adding on to the same program, each time we run the program we will get the output from the previous tasks before the output of the current task.

Task #3 Working with Strings (4 pts)
⦁   Use the charAt method to get the first character in firstName and store it in a variable called firstInitial (you will need to declare any variables that you use).
⦁   Print out the user’s first initial.
⦁   Use the toUpperCase method to change the fullName to uppercase and store it back into the fullName variable.
⦁   Add a line that prints out the value of fullName and how many characters (including the space) are in the string stored in fullName (use the length method to obtain that information).
⦁   Compile, debug, and run. The new output added on after the output from the previous tasks should have your initials and your full name in uppercase.
Task #4 Using Predefined Math Functions (4 pts)
⦁   Add a line that prompts the user to enter the diameter of a sphere.
⦁   Read in and store the number into a variable called diameter (you will need to declare any variables that you use).
⦁   The diameter is twice as long as the radius, so calculate and store the radius in an appropriately named variable.
⦁   The formula for the volume of a sphere is:
r3
Convert the formula to Java code and add a line which calculates and stores the value of volume in an appropriately named variable. Use Math.PI for and Math.pow to cube the radius.
⦁   Print your results to the screen with an appropriate message.
⦁   Compile, debug, and run using the following test data and record the results.

Diameter   Volume (hand calculated)   Volume (resulting output)
2      
25.4      
875,000      
Task #5 Create a program from scratch (4 pts)
In this task you will create a new program that calculates gas mileage in miles per gallon. You will use string expressions, assignment statements, input and output statements to communicate with the user.

⦁   Create a new file in your IDE or text editor.
⦁   Create the shell for your first program by entering:
public class Mileage
{
   public static void main(String[] args)
   {
       // Add your declaration and code here.
   }
}
⦁   Save the file as Mileage.java.
⦁   Translate the algorithm below into Java code. Don’t forget to declare variables before they are used. Each variable must be one word only (no spaces).
Print a line indicating this program will calculate mileage
Print prompt to user asking for miles driven
Read in miles driven
Print prompt to user asking for gallons used
Read in gallons used
Calculate miles per gallon by dividing miles driven by gallons used
Print miles per gallon along with appropriate labels
⦁   Compile the program and debug, repeating until it compiles successfully.
⦁   Run the program and test it using the following sets of data and record the results:

Miles driven   Gallons used   Miles per gallon (hand calculated)   Miles per gallon
(resulting output)
2000   100      
500   25.5      
241.5   10      
100   0      

⦁   The last set of data caused the computer to divide 100 by 0, which resulted in what is called a runtime error. Notice that runtime can occur on programs which compile and run on many other sets of data. This emphasizes the need to thoroughly test you program with all possible kinds of data.
Task #6 Documenting a Java Program (2 pts)
⦁   Compare the code listings of NumericTypes.java with Mileage.java. You will see that NumericTypes.java has lines which have information about what the program is doing. These lines are called comments and are designated by the // at the beginning of the line. Any comment that starts with /** and ends with */ is considered a documentation comment. These are typically written just before a class header, giving a brief description of the class. They are also used for documenting methods in the same way.
⦁   Write a documentation comment at the top of the program which indicates the purpose of the program, your name, and today’s date.
⦁   Add comment lines after each variable declaration, indicating what each variable represents.
⦁   Add comment lines for each section of the program, indicating what is done in that section.
⦁   Finally add a comment line indicating the purpose of the calculation.

Solutions

Expert Solution

/**
This program demonstrates how numeric types and
operators behave in Java.
*/
import java.util.Scanner;
import java.lang.Math;
public class NumericTypes
{
   public static void main (String [] args)
   {
       // TASK #2 Create a Scanner object here
       Scanner in = new Scanner(System.in);
       // (not used for alternate)

       // Identifier declarations
       final int NUMBER = 2 ; // Number of scores
       final int SCORE1 = 100; // First test score
       final int SCORE2 = 95; // Second test score
       final int BOILING_IN_F = 212; // Boiling temperature
       int fToC; // Temperature Celsius
       double average; // Arithmetic average
       String output; // Line of output
      
      
       // TASK #2 declare variables used here
       // TASK #3 declare variables used here
       // TASK #4 declare variables used here
       String firstName;
       String lastName;
       String fullName;
       char firstNameInit;
      
       double radius;
       double area;
       double volume;
      
       // Find an arithmetic average.
       average = (SCORE1 + SCORE2) / NUMBER;
       output = SCORE1 + " and " + SCORE2 +
       " have an average of " + average;
       System.out.println(output);
      

       // Convert Fahrenheit temperature to Celsius.
       fToC = 5/9 * (BOILING_IN_F - 32);
       output = BOILING_IN_F + " in Fahrenheit is " +
       fToC + " in Celsius.";
       System.out.println(output);
       System.out.println(); // To leave a blank line

       // ADD LINES FOR TASK #2 HERE
       // Prompt the user for first name
       // Read the user's first name
       // Prompt the user for last name
       // Read the user's last name
       // Concatenate the user's first and last names
       // Print out the user's full name
      
       System.out.print("Enter Your First Name: ");
       firstName = in.nextLine();
       System.out.print("Enter Your Last Name: ");
       lastName = in.nextLine();
       fullName = firstName + " "+ lastName;
       System.out.println("Full Name: "+fullName);

       System.out.println(); // To leave a blank line

       // ADD LINES FOR TASK #3 HERE
       // Get the first character from the user's first name
       // Print out the user's first initial
       // Convert the user's full name to uppercase
       // Print out the user's full name in uppercase
       firstNameInit = firstName.charAt(0);
       System.out.println("First Name initial: " + firstNameInit);
       fullName = fullName.toUpperCase();
       System.out.println("Full Name in UpperCase : "+fullName);
      
      
       System.out.println(); // To leave a blank line

       // ADD LINES FOR TASK #4 HERE
       // Prompt the user for a diameter of a sphere
       // Read the diameter
       // Calculate the radius
       // Calculate the volume
       // Print out the volume
       System.out.print("Enter Radius of sphere: ");
       radius = in.nextDouble();
       area = Math.PI * Math.pow(radius,2);
       volume = (4/3.0) * Math.PI * Math.pow(radius,3);
       System.out.println("Sphere area: "+area);
       System.out.println("Sphere Volumen: "+volume);
   }
}

/**
* Milage.java
* This program is used to calculate Milage.
**/
import java.util.Scanner;

public class Mileage
{
public static void main(String[] args)
{
System.out.println("\n---------- Milage Calculator ---------\n");

Scanner in = new Scanner(System.in);
//variables needed
double miles;
double gallons;
double milesPerGallon;

//prompt and read for number of miles driven
System.out.print("Enter Number of miles driven: ");
miles = in.nextDouble();
//validate the miles
if(miles <=0)
{
       System.out.println("Error: Invalid Number of miles driven entered\n");
       return;
   }

//prompt and read number of gallons used
System.out.print("Enter Number of gallons used: ");
gallons = in.nextDouble();
//validate the gallons
if(gallons <=0)
{
       System.out.println("Error: Invalid Number of gallons used entered\n");
       return;
   }

milesPerGallon = miles/gallons;
System.out.println("Miles Per Gallon: "+milesPerGallon);

}
}


Related Solutions

TASK: Based upon the following code: import java.util.Scanner; // Import the Scanner class public class Main...
TASK: Based upon the following code: import java.util.Scanner; // Import the Scanner class public class Main {   public static void main( String[] args ) {     Scanner myInput = new Scanner(System.in); // Create a Scanner object     System.out.println("Enter (3) digits: ");     int W = myInput.nextInt();     int X = myInput.nextInt();     int Y = myInput.nextInt();      } } Use the tools described thus far to create additional code that will sort the integers in either monotonic ascending or descending order. Copy your code and...
JAVA program Create a class called Array Outside of the class, import the Scanner library Outside...
JAVA program Create a class called Array Outside of the class, import the Scanner library Outside of main declare two static final variables and integer for number of days in the week and a double for the revenue per pizza (which is $8.50). Create a method called main Inside main: Declare an integer array that can hold the number of pizzas purchased each day for one week. Declare two additional variables one to hold the total sum of pizzas sold...
////Fixme(1) add a statement to import ArrayList class public class ListManipulation { public static void main(String[]...
////Fixme(1) add a statement to import ArrayList class public class ListManipulation { public static void main(String[] args) { //Fixme(2) create an ArrayList of integers and name the ArrayList list. //Fixme(3) add the following numbers to the list: 10, 15, 7, -5, 73, -11, 100, 20, 5, -1    displayList(list); System.out.println(); displayListBackwards(list);       }    public static void displayList(ArrayList<Integer> list) { for(Integer i: list) System.out.print(i + " ");    } //Fixme(4) define a method displayListBackwards, which takes an ArrayList as...
This for Java Programming Write a java statement to import the java utilities. Create a Scanner...
This for Java Programming Write a java statement to import the java utilities. Create a Scanner object to read input. int Age;     Write a java statement to read the Age input value 4 . Redo 1 to 3 using JOptionPane
import java.lang.UnsupportedOperationException; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc...
import java.lang.UnsupportedOperationException; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in);    // parse the number of strings int numStrings = Integer.parseInt(sc.nextLine());    // parse each string String[] stringsArray = new String[numStrings]; for (int i = 0; i < numStrings; i++) { stringsArray[i] = sc.nextLine(); }    // print whether there are duplicates System.out.println(hasDuplicates(stringsArray)); }    private static boolean hasDuplicates(String[] stringsArray) { // TODO fill this in and remove the below line...
import chapter6.date.SimpleDate; import java.util.Scanner; public class SimpleDateTestDefault { public static void main(String[] args) { Scanner stdin...
import chapter6.date.SimpleDate; import java.util.Scanner; public class SimpleDateTestDefault { public static void main(String[] args) { Scanner stdin = new Scanner(System.in); SimpleDate d1 = new SimpleDate(); SimpleDate d2 = new SimpleDate(stdin.nextInt(), stdin.nextInt(), stdin.nextInt()); System.out.println(d1); System.out.println(d2); System.out.println(d1.before(d2)); System.out.println(d2.before(d1)); } } Implement SimpleDate class in chapter6.date package with the following attributes: day, (int type,  private) month, (int type,  private) year (int type,  private) The class should have the following methods: a constructor with three parameters: year, month, and day a constructor with no parameters which initialize the...
Please add comments to this code! Item Class: import java.text.NumberFormat; public class Item {    private...
Please add comments to this code! Item Class: import java.text.NumberFormat; public class Item {    private String name;    private double price;    private int bulkQuantity;    private double bulkPrice;    /***    *    * @param name    * @param price    * @param bulkQuantity    * @param bulkPrice    */    public Item(String name, double price, int bulkQuantity, double bulkPrice) {        this.name = name;        this.price = price;        this.bulkQuantity = bulkQuantity;        this.bulkPrice = bulkPrice;   ...
Add code to the Account class and create a new class called BalanceComparator. import java.util.*; public...
Add code to the Account class and create a new class called BalanceComparator. import java.util.*; public final class Account implements Comparable {     private String firstName;     private String lastName;     private int accountNumber;     private double balance;     private boolean isNewAccount;     public Account(             String firstName,             String lastName,             int accountNumber,             double balance,             boolean isNewAccount     ) {         this.firstName = firstName;         this.lastName = lastName;         this.accountNumber = accountNumber;         this.balance = balance;         this.isNewAccount = isNewAccount;     }     /**      * TO DO: override equals      */     @Override     public boolean equals(Object other) {...
NEed UML diagram for this java code: import java.util.ArrayList; import java.util.Scanner; class ToDoList { private ArrayList<Task>...
NEed UML diagram for this java code: import java.util.ArrayList; import java.util.Scanner; class ToDoList { private ArrayList<Task> list;//make private array public ToDoList() { //this keyword refers to the current object in a method or constructor this.list = new ArrayList<>(); } public Task[] getSortedList() { Task[] sortedList = new Task[this.list.size()];//.size: gives he number of elements contained in the array //fills array with given values by using a for loop for (int i = 0; i < this.list.size(); i++) { sortedList[i] = this.list.get(i);...
------------------------------------------------------------------------------------ import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner input =...
------------------------------------------------------------------------------------ import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner input = new Scanner(System.in); int result = 0; System.out.print("Enter the first number: "); int x = input.nextInt(); System.out.print("Enter the second number: "); int y = input.nextInt(); System.out.println("operation type for + = 0"); System.out.println("operation type for - = 1"); System.out.println("operation type for * = 2"); System.out.print("Enter the operation type: "); int z = input.nextInt(); if(z==0){ result = x + y; System.out.println("The result is " + result); }else...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT