Lab 7
Add three instance variables to your class RightTriangle from lab 5. The first two are of type int and are called xLoc and yLoc and the third is of type int called ID. Also add a static variable of type double called scaleFactor. This should be initialized to a default value of 1. Update the constructor to set the three new instance variables and add appropriate get and set methods for the four new variables. All set methods including those from lab 5 should verify that no invalid data is set. Also define a new method ScaleShape() which multiplies the base and height instance variables by the scaleFactor and then updates the hypotenuse.
Write an application which shows the user the following menu and implements all options. The program should continue to run and process requests until the user selects 9. The program should double-check that the user really wants to exit. You may use a limit of 10 possible triangles to simplify implementation. The program should assign new ids to assure their uniqueness, the user should not enter an id for a new object in option 1. All input must be validated and appropriate feedback given for invalid input. Option 4 should display all info about the object. This is 8 method calls.
1 – Enter a new right triangle
2 – Delete a right triangle
3 – Delete all right triangles
4 – Display all right triangles
5 – Move a triangle
6 – Resize a triangle
7 – Enter a scale factor
8 – Scale all triangles
9 – Exit program
This is the lab shell that was given
Page
of 4
ZOOM
import java.util.Scanner;
public class Lab7Shell
{
public static void main(String[] args)
{
// DATA
RightTriangle [] triangles = new RightTriangle[10];
int nextIDNumber = 1;
boolean exit = false;
int selection=0;
Scanner input = new Scanner(System.in);
int id=0;
int x=0, y=0;
double base=0, height=0;
boolean found = false;
// ALGORITHM
// loop until user exits
do
{
// display options
// get selection (validate)
// switch on selection
switch(selection)
{
case 1:
// get size from user (two variables only, calculate the
hypotenuse)
// get location from user (two variables, X,Y location)
// set found to false
// loop through array
for (int i = 0; i < triangles.length; i++)
{
// if this is an empty spot
if (triangles[i] == null)
{
// create new RightTriangle object and assign to
current array element
triangles[i] = new RightTriangle(nextIDNumber++,
base, height, x, y);
// set found to true
found = true;
// break out of loop
break;
}
}
// if not found, give error message
// break out of switch statement
break;
case 2:
// get id number to delete
// set found to false
// loop through array
for (int i = 0; i < triangles.length; i++)
{
// if this is a valid object and the correct object
if (triangles[i] != null && triangles[i].GetID() == id)
{
// delete object
triangles[i] = null;
// set found to true
// break out of loop
}
}
// if not found, give error message
// break out of switch statement
case 3:
// loop through array
// if this is a valid object
// delete object
// break out of switch statement
break;
case 4:
// display header
// loop through array
// if this is a valid object
// display all info about object. This should call
and display all 8 get methods that return information.
// break out of switch statement
break;
case 5:
// get id number to move
// get location from user (two variables new X,Y location)
// set found to false
// loop through array
// if this is a valid object and the correct object
// call two set methods
// set found to true
// break out of loop
// if not found, give error message
// break out of switch statement
break;
case 6:
// get id number to resize
// get size from user (two variables)
// set found to false
// loop through array
// if this is a valid object and the correct object
// call SetBaseAndHeight
// set found to true
// break out of loop
// if not found, give error message
// break out of switch statement
case 7:
// get new scale factor (validate)
// call SetScaleFactor to set the new scale factor
// break out of switch statement
break;
case 8:
// loop through array
// if this is a valid object
// call ScaleShape method on object
// break out of switch statement
break;
case 9:
// confirm user wants to exit
// set variable to break out of loop
// break out of switch statement
break;
}
// End loop
} while (!exit);
}
}
class RightTriangle
{
// with three instance variables of type double called base, height, and
hypotenuse.
private double base;
private double height;
private double hypotenuse;
// add three new instance variables
// add static scaleShape
// update constructor to take the new instance variables
public RightTriangle(int i, double b, double h, int x, int y)
{
SetBaseAndHeight(b, h);
// set the other instance variables
}
// a single set method which takes new values for base and height and
calculates the hypotenuse,
public void SetBaseAndHeight(double b , double h)
{
if (b > 0.0 && h > 0.0)
{
base = b;
height = h;
hypotenuse = Math.sqrt(base * base + height * height);
}
}
// add set methods for the three new instance variables
// get methods for all three instance variables
public double GetBase()
{
return base;
}
public double GetHeight()
{
return height;
}
public double GetHypotenuse()
{
return hypotenuse;
}
// add get methods for the three new instance variables
// and methods getArea and getPerimeter.
public double GetArea()
{
return 0.5 * base * height;
}
public double GetPerimeter()
{
return base + height + hypotenuse;
}
// add ScaleShape method
}
Here is the completed code for this problem. Comments are included, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. Thanks
// Lab7Shell.java
import java.util.Scanner;
public class Lab7Shell {
// helper method defined to read a valid positive double value from the user
static double getPositiveDoubleInput(String prompt, Scanner scanner) {
double input = -1;
// looping as long as input is invalid
while (input <= 0) {
try {
// prompting and reading input
System.out.print(prompt);
input = scanner.nextDouble();
// validating
if (input <= 0) {
// printing error message
System.out.println("Invalid input, try again!");
}
} catch (Exception e) {
// non numeric data entry
System.out.println("Invalid input, try again!");
input = -1;
}
}
return input;
}
// helper method to read a valid integer value from the user. the extra
// boolean parameter denotes if the user is allowed to enter negative values
// or not
static int getIntegerInput(String prompt, Scanner scanner,
boolean allowNegatives) {
int input = -1;
boolean done=false;
do {
try {
System.out.print(prompt);
input = scanner.nextInt();
if (input <= 0 && !allowNegatives) {
System.out.println("Invalid input, try again!");
}else{
//validated.
done=true;
}
} catch (Exception e) {
// non numeric data input
System.out.println("Invalid input, try again!");
done=false;
}
} while (!done);
return input;
}
public static void main(String[] args) {
// DATA
RightTriangle[] triangles = new RightTriangle[10];
int nextIDNumber = 1;
boolean exit = false;
int selection = 0;
Scanner input = new Scanner(System.in);
int id = 0;
int x = 0, y = 0;
double base = 0, height = 0, scaleFactor;
boolean found = false;
// ALGORITHM
// loop until user exits
do {
// display options
System.out.println("\n1 – Enter a new right triangle");
System.out.println("2 – Delete a right triangle");
System.out.println("3 – Delete all right triangles");
System.out.println("4 – Display all right triangles");
System.out.println("5 – Move a triangle");
System.out.println("6 – Resize a triangle");
System.out.println("7 – Enter a scale factor");
System.out.println("8 – Scale all triangles");
System.out.println("9 – Exit program");
// get selection (validate)
selection = getIntegerInput("Enter your selection: ", input, false);
// switch on selection
switch (selection) {
case 1:
// get size from user (two variables only, calculate the
// hypotenuse)
base = getPositiveDoubleInput("Enter the base: ", input);
height = getPositiveDoubleInput("Enter the height: ", input);
// get location from user (two variables, X,Y location)
x = getIntegerInput("Enter the x coordinate value: ", input,
true);
y = getIntegerInput("Enter the y coordinate value: ", input,
true);
// set found to false
found = false;
// loop through array
for (int i = 0; i < triangles.length; i++) {
// if this is an empty spot
if (triangles[i] == null) {
// create new RightTriangle object and assign to current
// array element
triangles[i] = new RightTriangle(nextIDNumber++, base,
height, x, y);
// set found to true
found = true;
// break out of loop
break;
}
}
// if not found, give error message
if (!found) {
System.out.println("Sorry, array is full!");
}
// break out of switch statement
break;
case 2:
// get id number to delete
id = getIntegerInput("Enter the id of triangle to delete: ",
input, false);
// set found to false
found = false;
// loop through array
for (int i = 0; i < triangles.length; i++) {
// if this is a valid object and the correct object
if (triangles[i] != null && triangles[i].GetID() == id) {
// delete object
triangles[i] = null;
// set found to true
found = true;
// break out of loop
break;
}
}
// if not found, give error message
if (!found) {
System.out
.println("Sorry, specified triangle is not found!");
}
// break out of switch statement
break;
case 3:
// loop through array
// if this is a valid object
// delete object
for (int i = 0; i < triangles.length; i++) {
if (triangles[i] != null) {
triangles[i] = null;
}
}
// break out of switch statement
break;
case 4:
// display header
System.out.printf("%10s %10s %10s %10s %10s %10s %10s %10s\n",
"ID", "BASE", "HEIGHT", "HYPOTENUSE", "X", "Y", "AREA",
"PERIMETER");
// loop through array
for (int i = 0; i < triangles.length; i++) {
// if this is a valid object
if (triangles[i] != null) {
// display all info about object. This should call and
// display
// all 8 get methods that return information.
System.out
.printf("%10d %10.2f %10.2f %10.2f %10d %10d %10.2f %10.2f\n",
triangles[i].GetID(),
triangles[i].GetBase(),
triangles[i].GetHeight(),
triangles[i].GetHypotenuse(),
triangles[i].GetxLoc(),
triangles[i].GetyLoc(),
triangles[i].GetArea(),
triangles[i].GetPerimeter());
}
}
// break out of switch statement
break;
case 5:
// get id number to move
id = getIntegerInput("Enter the id of triangle to move: ",
input, false);
// get location from user (two variables new X,Y location)
x = getIntegerInput("Enter the new x coordinate value: ",
input, true);
y = getIntegerInput("Enter the new y coordinate value: ",
input, true);
// set found to false
found = false;
// loop through array
for (int i = 0; i < triangles.length; i++) {
// if this is a valid object and the correct object
if (triangles[i] != null && triangles[i].GetID() == id) {
triangles[i].SetxLoc(x);
triangles[i].SetyLoc(y);
found = true;
break;
}
}
// if not found, give error message
if (!found) {
System.out.println("Not found!");
}
// break out of switch statement
break;
case 6:
// get id number to resize
id = getIntegerInput("Enter the id of triangle to resize: ",
input, false);
// get size from user (two variables)
base = getPositiveDoubleInput("Enter the new base: ", input);
height = getPositiveDoubleInput("Enter the new height: ", input);
// set found to false
found = false;
// loop through array
for (int i = 0; i < triangles.length; i++) {
// if this is a valid object and the correct object
if (triangles[i] != null && triangles[i].GetID() == id) {
// call SetBaseAndHeight
triangles[i].SetBaseAndHeight(base, height);
// set found to true
// break out of loop
found = true;
break;
}
}
// if not found, give error message
if (!found) {
System.out.println("Not found!");
}
// break out of switch statement
break;
case 7:
// get new scale factor (validate)
scaleFactor = getPositiveDoubleInput("Enter a scale factor: ",
input);
// call SetScaleFactor to set the new scale factor
RightTriangle.SetScaleFactor(scaleFactor);
// break out of switch statement
break;
case 8:
// loop through array
// if this is a valid object
// call ScaleShape method on object
// break out of switch statement
for (int i = 0; i < triangles.length; i++) {
if (triangles[i] != null) {
triangles[i].ScaleShape();
}
}
break;
case 9:
// confirm user wants to exit
System.out.print("You really want to exit? (y/n) ");
String ch = input.next();
if (ch.equalsIgnoreCase("y")) {
exit = true;
}
// set variable to break out of loop
// break out of switch statement
break;
}
// End loop
} while (!exit);
}
}
class RightTriangle {
// with three instance variables of type double called base, height, and
// hypotenuse.
private double base;
private double height;
private double hypotenuse;
// add three new instance variables
private int xLoc;
private int yLoc;
private int ID;
// add static scaleShape
static double scaleFactor = 1;
// update constructor to take the new instance variables
public RightTriangle(int i, double b, double h, int x, int y) {
SetBaseAndHeight(b, h);
// set the other instance variables
xLoc = x;
yLoc = y;
ID = i;
}
// a single set method which takes new values for base and height and
// calculates the hypotenuse,
public void SetBaseAndHeight(double b, double h) {
if (b > 0.0 && h > 0.0) {
base = b;
height = h;
hypotenuse = Math.sqrt(base * base + height * height);
}
}
// add set methods for the three new instance variables
// get methods for all three instance variables
public double GetBase() {
return base;
}
public double GetHeight() {
return height;
}
public double GetHypotenuse() {
return hypotenuse;
}
// add get methods for the three new instance variables
// and methods getArea and getPerimeter.
public double GetArea() {
return 0.5 * base * height;
}
public double GetPerimeter() {
return base + height + hypotenuse;
}
// new getters and setters
public int GetID() {
return ID;
}
public void SetID(int iD) {
if (iD > 0)
ID = iD;
}
public void SetxLoc(int xLoc) {
this.xLoc = xLoc;
}
public void SetyLoc(int yLoc) {
this.yLoc = yLoc;
}
public int GetxLoc() {
return xLoc;
}
public int GetyLoc() {
return yLoc;
}
// add ScaleShape method
public void ScaleShape() {
//scaling
base = base * scaleFactor;
height = height * scaleFactor;
//finding and assigning new hypotenuse
SetBaseAndHeight(base, height);
}
public static double GetScaleFactor() {
return scaleFactor;
}
public static void SetScaleFactor(double scaleFactor) {
//validating scale factor before setting
if (scaleFactor > 0)
RightTriangle.scaleFactor = scaleFactor;
}
}
/*OUTPUT (partial)*/
Lab 7 Add three instance variables to your class RightTriangle from lab 5. The first two...
Create a class Circle with one instance variable of type double called radius. Then define an appropriate constructor that takes an initial value for the radius, get and set methods for the radius, and methods getArea and getPerimeter. Create a class RightTriangle with three instance variables of type double called base, height, and hypotenuse. Then define an appropriate constructor that takes initial values for the base and height and calculates the hypotenuse, a single set method which takes new values...
You are to create a class Appointment.java that will have the following: 5 Instance variables: private String month private int day private int year private int hour private int minute 1 default constructor public Appointment() 1 non-default constructor that accepts arguments for all instance variables, your constructor must call the setter methods below to set the values of the instance variables public Appointment(String monthPassed, int dayPassed, int yearPassed, int hourPassed, int minutePassed) 5 setter methods (one for each instance variable)...
use java follow my code: public class q1 { // Instance Variables int currentFloor; double maximumWeight; int topFloor; // Constructor Declaration of Class public q1 (int currentFloor, double maximumWeight, int topFloor) { this.currentFloor = currentFloor; this.maximumWeight = maximumWeight; this.topFloor = topFloor; } // Property to get value of currentFloor instance variable public int getCurrentFloor() { return currentFloor; } // Property...
Programming assignment for Java: Do not add any other instance variables to any class, but you can create local variables in a method to accomplish tasks. Do not create any methods other than the ones listed below. Step 1 Develop the following class: Class Name: College Degree Access Modifier: public Instance variables Name: major Access modifier: private Data type: String Name: numberOfCourses Access modifier: private Data type: int Name: courseNameArray Access modifier: private Data type: String Name: courseCreditArray Access modifier:...
Write a class called Student. The specification for a Student is: Three Instance fields name - a String of the student's full name totalQuizScore - double numQuizesTaken - int Constructor Default construtor that sets the instance fields to a default value Parameterized constructor that sets the name instance field to a parameter value and set the other instance fields to a default value. Methods setName - sets or changes the student name by taking in a parameter getName - returns...
You may not add any instance variables to any class, though you may create local variables inside of a method to accomplish its task. No other methods should be created other than the ones listed here. Step 1 Develop the following class: Class Name: CollegeDegree Access Modifier: public Instance variables Name: major Access modifier: private Data type: String Name: numberOfCourses Access modifier: private Data type: int Name: courseNameArray Access modifier: private Data type: String [ ] Name: courseCreditArray Access...
You may not add any instance variables to any class, though you may create local variables inside of a method to accomplish its task. No other methods should be created other than the ones listed here. (I need step 2 please.) Step 1 Develop the following class: Class Name: CollegeDegree Access Modifier: public Instance variables Name: major Access modifier: private Data type: String Name: numberOfCourses Access modifier: private Data type: int Name: courseNameArray Access modifier: private Data type: String [...
C# programming 50 pts Question 2:2 1- Create the base class Book that has the following instance variables, constructor, and methods title (String) isbn (String) authors (String) publisher (String) edition ( int) published year (int) Constructor that takes all of the above variables as input parameters. set/get methods ToString method// that return sting representation of Book object. 2-Create the sub class New_Book that is derived from the base class Book and has the following instance variables, constructor, and methods: title...
The FoodItem.java file defines a class called FoodItem that contains instance variables for name (String) and calories (int), along with get/set methods for both. Implement the methods in the Meal class found in Meal.java public class FoodItem{ private String name; private int calories; public FoodItem(String iName, int iCals){ name = iName; calories = iCals; } public void setName(String newName){ name = newName; } public void setCalories(int newCals){ calories = newCals; } public int getCalories(){ return calories;...
Java Project Requirements: Account class Superclass Instance variables clearPassword String Must be at least 8 characters long encryptedPassword : String key int Must be between 1 and 10(inclusive) accountId - A unique integer that identifies each account nextIDNum – a static int that starts at 1000 and is used to generate the accountID no other instance variables needed. Default constructor – set all instance variables to a default value. Parameterized constructor Takes in clearPassword, key. Calls encrypt method to create...