correct way to check user input with scanner - java

I'm very new to programming, I've wrote an app for working the area out of certain shapes.
I have the AreaCalculations in another class can provide if needed but that works fine.
My problem is checking when the user types a character instead of a double. As you can see from my code i got it to work by using a while loop and (!reader.NextDouble()) .
This works but i then have to repeat the question. I could do this throughout the program but is there an easier/tidier way of doing this???
Thanks,
Craig
My code so far :
package areaprog;
import java.util.Scanner;
public class Mainprog {
public static void main (String [] args){
//Area Menu Selection
System.out.println("What shape do you need to know the area of?\n" +
"1: Square?\n" +
"2: Rectangle?\n" +
"3: Triangle?\n" +
"4: Circle? \n" +
"5: Exit\n"
);
//User input for menu
Scanner reader = new Scanner(System.in);
System.out.println("Number: ");
//Menu syntax checking
while (!reader.hasNextDouble())
{
System.out.println("Thats not a number you tool.\n");
System.out.println("Now pick again\n" +
"1: Square?\n" +
"2: Rectangle?\n" +
"3: Triangle?\n" +
"4: Circle? \n" +
"5: Exit\n"
);
reader.next(); //ask for next token?
}
double input = reader.nextDouble();
reader.nextLine();
//Depending on user selection, depends on what method is called using switch.
Scanner scan = new Scanner(System.in);
//Square selection
if (input == 1){
System.out.println("What is a length of 1 side of the Square?\n");
double s1 = scan.nextDouble();
double SqAns = AreaCalculator.getSquareArea(s1);
System.out.println("The area of you square is: " + SqAns);
}
//Rectangle selection
if (input == 2){
System.out.println("What is the width of your rectangle?.\n");
double r1 = scan.nextDouble();
System.out.println("What is the height of your rectangle?\n");
double r2 = scan.nextDouble();
double RecAns = AreaCalculator.getRectArea(r1, r2);
System.out.println("The area of your rectangle is: " + RecAns);
}
//Triangle selection
if (input == 3){
System.out.println("What is the base length of the triangle?.");
double t1 = scan.nextDouble();
System.out.println("What is the height of your triangle?");
double t2 = scan.nextDouble();
double TriAns = AreaCalculator.getTriArea(t1, t2);
System.out.println("The area of your triangle is " + TriAns);
}
//Circle selection
if (input == 4){
System.out.println("What is the radius of your circle?.");
double c1 = scan.nextDouble();
double CircAns = AreaCalculator.getCircleArea(c1);
System.out.println("The area of your circle is " + CircAns);
}
//Exit application
if (input == 5){
System.out.println("Goodbye.");
}
}
}
Ok so I've added in a Exception to catch the error. So its a bit cleaner now in the way it handles people not using intergers.
Number:
1
What is a length of 1 side of the Square?
a
Why are you trying to be clever? use an interger.
But then the program just ends.... How would i either get them back to the main menu or even get them to re-input there last effort?
Thanks,
Craig

As far as menu driven programs are concerned,its well and good.But as you said:
"This works but i then have to repeat the question."
So read Exception handling tutorial in java
So, your code will look something like this :
try
{
System.out.println("Thats not a number you tool.\n");
System.out.println("Now pick again\n" +
"1: Square?\n" +
"2: Rectangle?\n" +
"3: Triangle?\n" +
"4: Circle? \n" +
"5: Exit\n"
);
input = reader.nextDouble();
}
catch(InputMismatchException err)
{
System.out.print(err.getMessage());
}
Don't forget to import import java.util.InputMismatchException or import java.util.*
And try to declare variables outside the try block, may not be visible outside.

Related

cannot find symbol error in condition of while loop

I'm writing a program for an assignment that should give random problems for the user to solve. what I am attempting to make it do is after selecting a problem type and answering one question the program should load the menu up again.
Originally I wrote a method that would be called in the else statement on line 147. The method successfully looped however the assignment specifically asks for a loop to make it happen. I've tried several different ways to change the loops condition statement but I'm not sure where I went wrong? any help would be appreciated.
I want very badly to use a switch statement but I can't as we haven't learned that in class.
// Importing Scanner and Random class for later.
import java.util.Scanner;
import java.util.Random;
class AlgebraTutor {
// Solve for Y method.
public static void solve_for_y() {
// Creation of a random number generator.
Random number_gen = new Random();
// Generates random integers from -100 to 100.
int var_m = number_gen.nextInt(101) - 100;
int var_x = number_gen.nextInt(101) - 100;
int var_b = number_gen.nextInt(101) - 100;
// Print problem out for student to see
System.out.println("Problem: y = " + var_m + "(" + var_x +")" + "+" + var_b);
System.out.println(" m =" + var_m);
System.out.println(" x =" + var_x);
System.out.println(" b =" + var_b);
// This formula will calculate the value of y.
float var_y = (var_m * var_x) + var_b;
// Using the scanners class a scanner object called userInput was created to record students answer. Answer was taken as a string and converted to an integer.
Scanner user_input = new Scanner(System.in);
System.out.println("Please solve for y:");
String user_answer = user_input.nextLine();
int answer = Integer.parseInt(user_answer);
if (answer == var_y){
System.out.println("correct");
}else{
System.out.println("incorrect, The answer is:" + var_y);
}
}
// -------------------------------------------------------------------------
// Solve for M method.
public static void solve_for_m() {
// Creation of a random number generator.
Random number_gen = new Random();
// Generates random integers from -100 to 100.
int var_y = number_gen.nextInt(101) - 100;
int var_x = number_gen.nextInt(101) - 100;
int var_b = number_gen.nextInt(101) - 100;
// Print problem out for student to see.
System.out.println("Problem: " + var_y + " = m (" + var_x +") + " + var_b);
System.out.println(" y =" + var_y);
System.out.println(" x =" + var_x);
System.out.println(" b =" + var_b);
// This formula will calculate the value of m.
float var_m = (var_y - var_b) / var_x;
// Using the scanners class a scanner object called userInput was created to record students answer. Answer was taken as a string and converted to an integer.
Scanner user_input = new Scanner(System.in);
System.out.println("Please solve for m:");
String user_answer = user_input.nextLine();
int answer = Integer.parseInt(user_answer);
if (answer == var_m){
System.out.println("correct");
}else{
System.out.println("incorrect, The answer is:" + var_m);
}
}
// -------------------------------------------------------------------------
// Solve for B method
public static void solve_for_b() {
// Creation of a random number generator.
Random number_gen = new Random();
// Generates random integers from -100 to 100.
int var_y = number_gen.nextInt(101) - 100;
int var_x = number_gen.nextInt(101) - 100;
int var_m = number_gen.nextInt(101) - 100;
// Print problem out for student to see.
System.out.println("Problem: " + var_y + " = " + var_m + " (" + var_x +") " + "+ b");
System.out.println(" y =" + var_y);
System.out.println(" x =" + var_x);
System.out.println(" m =" + var_m);
// This formula will calculate the value of m.
float var_b = var_y / (var_m * var_x);
// Using the scanners class a scanner object called userInput was created to record students answer. Answer was taken as a string and converted to an integer.
Scanner user_input = new Scanner(System.in);
System.out.println("Please solve for b:");
String user_answer = user_input.nextLine();
int answer = Integer.parseInt(user_answer);
if (answer == var_b){
System.out.println("correct");
}else{
System.out.println("incorrect, The answer is:" + var_b);
}
}
// -------------------------------------------------------------------------
public static void main(String[] args) {
do{
System.out.println("Which type of problem would you like to practice?");
System.out.println("1) Solve for y");
System.out.println("2) Solve for m");
System.out.println("3) Solve for b");
System.out.println("4) To quit");
Scanner selection_input = new Scanner(System.in);
String user_selection = selection_input.nextLine();
if ( user_selection.equals("1")){
solve_for_y();
} else if (user_selection.equals("2")){
solve_for_m();
} else if (user_selection.equals("3")){
solve_for_b();
} else if (user_selection.equals("4")){
System.out.println("Quitting Program");
System. exit(0);
} else{
System.out.println("Please choose from the given options");
}
} while(user_selection.equals("1") &&
user_selection.equals("2") &&
user_selection.equals("3") &&
user_selection.equals("4"));
}
}
You must declare the user_inpout variable outside the do...while loop, then you can check its value in the while() expression. Also you should initialize the scanner only once at the beginning of your program.
public static void main(String[] args)
{
Scanner selection_input = new Scanner(System.in);
String user_selection=null;
do
{
System.out.println("Which type of problem would you like to practice?");
System.out.println("1) Solve for y");
System.out.println("2) Solve for m");
System.out.println("3) Solve for b");
System.out.println("4) To quit");
user_selection = selection_input.nextLine();
if (user_selection.equals("1"))
{
solve_for_y();
}
else if (user_selection.equals("2"))
{
solve_for_m();
}
else if (user_selection.equals("3"))
{
solve_for_b();
}
else if (user_selection.equals("4"))
{
System.out.println("Quitting Program");
System.exit(0);
}
else
{
System.out.println("Please choose from the given options");
}
}
while (!user_selection.equals("4"));
}
For the case "4" you have two exists now:
else if (user_selection.equals("4"))
{
System.out.println("Quitting Program");
System.exit(0);
}
and:
while (!user_selection.equals("4"));
Only one of both is needed. So you may either remove the first one or replace the while statement by while(true).

Adding a 'While' Loop To My Program [duplicate]

This question already has an answer here:
How to use java.util.Scanner to correctly read user input from System.in and act on it?
(1 answer)
Closed 6 years ago.
I'm working on a program that calculates the area of either a circle (C), square (S), or rectangle (R), depending on what letter the user inputs. I've tested it and it works fine; the code is below:
import java.util.Scanner;
public class TestLoops {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("What is your shape? Enter C for circle, S for " +
"square, R for rectangle, or X to exit: ");
String Shape = input.nextLine();
if (Shape.equals("C")) {
System.out.println("What is your circle's radius?: ");
double Radius = input.nextDouble();
double cFormula = (3.14 * Radius * Radius);
System.out.println("Your circle's area = " + cFormula);
}
else if (Shape.equals("S")) {
System.out.println("What is the length of your shape's sides?: ");
double Side = input.nextDouble();
double sFormula = (Side * Side);
System.out.println("Your square's area = " + sFormula);
}
else if (Shape.equals("R")) {
System.out.println("What is your rectangle's height?: ");
double Height = input.nextDouble();
System.out.println("What is your rectangle's width?: ");
double Width = input.nextDouble();
double rFormula = (Height * Width);
System.out.println("Your rectangle's area = " + rFormula);
}
}
}
Now, what I want to do is add a loop to the program. For example, if the user inputs C for circle and puts in the number 22 for the radius, they'll get an answer, but I want the program to loop back to the beginning again so that it asks the user "What is your shape?...". Also, if the user types in X instead of C, S, or R, I want the program to quit, but I'm not sure how to add that in, either.
I know that I need to add a 'while' loop, but I was hoping someone could point me in the right direction, because I don't know where to insert that part of the code. Do I add the 'while' loop somewhere at the beginning of the code, after the last "if else" statement, or... Also, I'm not actually sure what to type. Should it be something like,
while (Shape == C, S, R) {
....?
Any help or pointers would be appreciated by any one in the coding community! I will continue to work on this code on my own as well.
I would go for the do, while
So, the program will always do something while the conditions that are set are being accomplished, so you want your program to look something like:
public class TestLoops {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean thisB = false; /*this is the guy who will tell the loop to stop the execution when the user inserts X*/
String shape;
do{
System.out.println("What is your shape? Enter C for circle, S for " +
"square, R for rectangle, or X to exit: ");
shape = input.next();
if(shape.equalsIgnoreCase("C") || shape.equalsIgnoreCase("S") || shape.equalsIgnoreCase("R")) {
if (shape.equals("C")) {
System.out.println("What is your circle's radius?: ");
double Radius = input.nextDouble();
double cFormula = (3.14 * Radius * Radius);
System.out.println("Your circle's area = " + cFormula);
} else if (shape.equals("S")) {
System.out.println("What is the length of your shape's sides?: ");
double Side = input.nextDouble();
double sFormula = (Side * Side);
System.out.println("Your square's area = " + sFormula);
} else if (shape.equals("R")) {
System.out.println("What is your rectangle's height?: ");
double Height = input.nextDouble();
System.out.println("What is your rectangle's width?: ");
double Width = input.nextDouble();
double rFormula = (Height * Width);
System.out.println("Your rectangle's area = " + rFormula);
}
}
else if (shape.equalsIgnoreCase("X")) thisB = true;/*or in other words: stop*/
}
while(!thisB);
}
}
Things to consider:
1) Naming conventions, always start variable names with undercase using camelCase, in your example shape started with UpperCase
2) When in a while loop, use only next(), not nextLine() to pick up the values as the latter will duplicate the question in the System.out.Println.
3) The optimum way to do this is to put all your if clauses in a method and call it with the parameter from the Scanner input. Even better would be having a method per shape, as things can get hairy depending on requests

How do you include an applet in a Java application?

So for my computer science class we have to make a gpa calculator and include an applet in the same program to display the full name of the student and their GPA. I have the program working
import java.util.*;
import java.text.DecimalFormat;
import javax.swing.JApplet;
import java.awt.*;
public class Project1_Michael_Micool extends JApplet
{
public static void main(String[]args)
{
String first_name, last_name, course1, course2, course3, course4;
//Sets all the needed variables to string values for first, last and course names
int cred_course1, cred_course2, cred_course3, cred_course4, total_credits;
//Sets all the course credits as int values
float grade_course1, grade_course2, grade_course3, grade_course4, grade_point1, grade_point2, grade_point3, grade_point4, total_grades_added, gpa;
Scanner scan = new Scanner(System.in);
DecimalFormat fmt = new DecimalFormat("0.##");
System.out.println("Welcome to the UNG GPA calculator.");
System.out.println();
System.out.println("Please enter your first name");
first_name = scan.next(); //Assigns the entered name as first_name
System.out.println("Please enter your last name");
last_name = scan.next(); //Assigns the entered name as last_name
System.out.println();
System.out.println("A: 4.0 A-:3.67 ");
System.out.println("B+:3.33 B:3.00 B-:2.67");
System.out.println("C+: 2.33 C:2.00 C-:1.67");
System.out.println("D+: 1.33 D:1.00 F:0.00");
System.out.println();
System.out.println("Please enter your first course name and number. EX: PSYC1101");
course1 = scan.next();
System.out.println("Please enter the number of credits for course 1.");
cred_course1 = scan.nextInt();
System.out.println("Please enter your grade for course 1 using the chart. EX: B+= 3.33");
grade_course1 = scan.nextFloat();
System.out.println();
System.out.println();
System.out.println("Please enter your second course name and number. EX: PSYC1101");
course2 = scan.next();
System.out.println("Please enter the number of credits for course 2.");
cred_course2 = scan.nextInt();
System.out.println("Please enter your grade for course 2 using the chart. EX: B+= 3.33");
grade_course2 = scan.nextFloat();
System.out.println();
System.out.println();
System.out.println("Please enter your third course name and number. EX: PSYC1101");
course3 = scan.next();
System.out.println("Please enter the number of credits for course 3.");
cred_course3 = scan.nextInt();
System.out.println("Please enter your grade for course 3 using the chart. EX: B+= 3.33");
grade_course3 = scan.nextFloat();
System.out.println();
System.out.println();
System.out.println("Please enter your fourth course name and number. EX: PSYC1101");
course4 = scan.next();
System.out.println("Please enter the number of credits for course 4.");
cred_course4 = scan.nextInt();
System.out.println("Please enter your grade for course 4 using the chart. EX: B+= 3.33");
grade_course4 = scan.nextFloat();
total_credits = cred_course1 + cred_course2 + cred_course3 + cred_course4;
grade_point1 = grade_course1 * cred_course1;
grade_point2 = grade_course2 * cred_course2;
grade_point3 = grade_course3 * cred_course3;
grade_point4 = grade_course4 * cred_course4;
total_grades_added = grade_point1 + grade_point2 + grade_point3 + grade_point4;
gpa = total_grades_added / total_credits;
gpa = Math.abs(gpa);
course1 = course1.toUpperCase();
course2 = course2.toUpperCase();
course3 = course3.toUpperCase();
course4 = course4.toUpperCase();
System.out.println("Your name is " + first_name + " " + last_name);
System.out.println("You are taking " + course1 + " which is worth " + cred_course1 + " credit hours");
System.out.println("You are taking " + course2 + " which is worth " + cred_course2 + " credit hours");
System.out.println("You are taking " + course3 + " which is worth " + cred_course3 + " credit hours");
System.out.println("You are taking " + course4 + " which is worth " + cred_course4 + " credit hours");
System.out.println("Your total credit hours is " + total_credits);
System.out.println("Your GPA is " + fmt.format(gpa));
}
}
Here is the applet that I think should work.
public void paint(Graphics page)
{
page.drawString(first_name + " " + last_name, 110, 70);
page.drawString(gmt.format(gpa), 130, 100);
}
So my question is, how to you incorporate the applet into the program?
What you posted is not an "Applet"; it's just the paint method of something that might be an AWT widget (e.g. an applet). Just use that method in a widget that you integrate into your UI.
An Applet (or JApplet) would not typically have a main(String[]) unless it is an hybrid application/applet (where the application is based around a Frame or JFrame), but that main method is focused on the command line.
There is no practical way to use the command line code in either an applet or an application. It needs to be rewritten to use a GUI.
..for my computer science class..
Please refer the instructor to Why CS teachers should stop teaching Java applets.

Writing an infinite loop [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am writing code that should create an infinite loop, but is currently terminating unexpectedly.
When I either type in 'Y' for yes or 'N' for no, this code should enter a non-terminating loop.
import java.util.Scanner;
import java.text.NumberFormat;
import java.text.DecimalFormat;
public class Math_Island_XTENDED_Final
{
static Scanner sc = new Scanner(System.in);
static Scanner keyboard = new Scanner(System.in);
public static void main(String[] args)
{
//Declarations
int Bignumber;
int Mednumber;
int Smallnumber;
double addition;
double subtraction;
double multiplcation;
double division;
double sphere_radius1;
double sphere_radius2;
double sphere_radius3;
double rectangle_measurements;
char repeat;
String input;
System.out.println("Welcome to Math Island :D ! ");
System.out.println("We will use some numbers for our Formula ! ");
System.out.println("1 rule, NO DECIMALS !! ");
System.out.println("Please Pick a # from 1 to 100 NOW!! ");
Bignumber = sc.nextInt();
System.out.print("Please Pick a # from 1 to 20 NOW!! ");
Mednumber = sc.nextInt();
System.out.print("Please Pick a # from 1 to 5 NOW!! ");
Smallnumber = sc.nextInt();
//Results
addition = Bignumber + Mednumber + Smallnumber;
subtraction = Bignumber - Mednumber - Smallnumber;
multiplcation = Bignumber * Mednumber * Smallnumber;
division = Bignumber / Mednumber / Smallnumber;
sphere_radius1 = Bignumber * 3.14 * 3.14;
sphere_radius2 = Mednumber * 3.14 * 3.14;
sphere_radius3 = Smallnumber * 3.14 * 3.14;
rectangle_measurements = Bignumber * Mednumber * Smallnumber;
System.out.println();
System.out.println();
//results 2
System.out.println(" Your addition answer would be " + addition);
System.out.println(" Your subtraction answer would be " + subtraction);
System.out.println(" Your multiplcation answer would be " + multiplcation);
System.out.println(" Your division answer would be " + division);
System.out.println(" Your first sphere answer would be " + sphere_radius1);
System.out.println(" Your second sphere answer would be " + sphere_radius2);
System.out.println(" Your third sphere answer would be " + sphere_radius3);
System.out.println(" Your recangle size would be " + rectangle_measurements+ " in cubic Feet");
System.out.println();
System.out.println();
System.out.println("Would you like to Play again ? ");
System.out.println("Y for yes, & N for no " );
input = keyboard.nextLine();
repeat = input.charAt(0);
while (repeat == 'Y');
System.out.println();
while (repeat == 'N');
System.out.println();
System.out.println("Goodbye!");
}
}
You have semicolons after your while loops:
while (repeat == 'Y'); // <-- Right here
System.out.println();
If you remove it, you should get an infinite loop if repeat == 'Y' is true.
The same goes for the other loop. Just make sure you use braces around the code that you want to loop over:
while (repeat == 'Y')
System.out.println();
while (repeat == 'N') {
System.out.println();
System.out.println("Goodbye!");
}
If you want to use the loop to play the game again, I would recommend using a do/while loop, since you want to play at least once:
do {
System.out.println("Welcome to Math Island :D ! ");
System.out.println("We will use some numbers for our Formula ! ");
System.out.println("1 rule, NO DECIMALS !! ");
System.out.println("Please Pick a # from 1 to 100 NOW!! ");
Bignumber = sc.nextInt();
System.out.print("Please Pick a # from 1 to 20 NOW!! ");
Mednumber = sc.nextInt();
System.out.print("Please Pick a # from 1 to 5 NOW!! ");
Smallnumber = sc.nextInt();
//Results
addition = Bignumber + Mednumber + Smallnumber;
subtraction = Bignumber - Mednumber - Smallnumber;
multiplcation = Bignumber * Mednumber * Smallnumber;
division = Bignumber / Mednumber / Smallnumber;
sphere_radius1 = Bignumber * 3.14 * 3.14;
sphere_radius2 = Mednumber * 3.14 * 3.14;
sphere_radius3 = Smallnumber * 3.14 * 3.14;
rectangle_measurements = Bignumber * Mednumber * Smallnumber;
System.out.println();
System.out.println();
//results 2
System.out.println(" Your addition answer would be " + addition);
System.out.println(" Your subtraction answer would be " + subtraction);
System.out.println(" Your multiplcation answer would be " + multiplcation);
System.out.println(" Your division answer would be " + division);
System.out.println(" Your first sphere answer would be " + sphere_radius1);
System.out.println(" Your second sphere answer would be " + sphere_radius2);
System.out.println(" Your third sphere answer would be " + sphere_radius3);
System.out.println(" Your recangle size would be " + rectangle_measurements+ " in cubic Feet");
System.out.println();
System.out.println();
System.out.println("Would you like to Play again ? ");
System.out.println("Y for yes, & N for no " );
input = keyboard.nextLine();
repeat = input.charAt(0);
} while (repeat == 'y');
System.out.println("Goodbye!");*
encase the entire code in a while loop
define repeat as a boolean before the while loop- set it as True
then replace
while (repeat == 'Y') {
System.out.println();
}
while (repeat == 'N') {
System.out.println();
System.out.println("Goodbye!");
}
with an if statement that checks if the user input is "n", in which case change repeat to False. Otherwise keep repeat as True.
Also- lots of syntax errors in the code- clean those up and you should be fine
Take all the code you want to repeat and put it inside of its own function:
void myMathGame() {
//code for one round: setup, get user input, calculate values, print them
}
Then simply construct an unconditional infinite loop inside of your main function which you break if the user doesn't want another round:
public static void main(String[] args) {
while (true) {
myMathGame();
System.out.println("Would you like to Play again? (Y/N) ");
if (keyboard.nextLine().charAt(0) != "Y") {
break;
}
}
}

OOP advice - should I change how my program runs?

below I have a small program i wrote for working out the area of shapes....
My question is this the right way to do it, a friend did similar and had multiple shapes which inherited from main shape. OOP? is mine ok as i will only ask the area of a shape and no more? and how would i change this to make it more OO?
Main Prog /////
package areaprog;
import java.util.Scanner;
import java.util.InputMismatchException;
public class Mainprog {
public static void main (String [] args){
//Area Menu Selection
System.out.println("What shape do you need to know the area of?\n" +
"1: Square?\n" +
"2: Rectangle?\n" +
"3: Triangle?\n" +
"4: Circle? \n" +
"5: Exit\n"
);
//User input for menu
Scanner reader = new Scanner(System.in);
System.out.println("Number: ");
//Menu syntax checking
while (!reader.hasNextDouble())
{
System.out.println("Thats not a number you tool.\n");
System.out.println("Now pick again\n" +
"1: Square?\n" +
"2: Rectangle?\n" +
"3: Triangle?\n" +
"4: Circle? \n" +
"5: Exit\n"
);
reader.next(); //ask for next token
}
double input = reader.nextDouble();
reader.nextLine();
//Depending on user selection, depends on what method is called using switch.
Scanner scan = new Scanner(System.in);
//Square selection and InputMismatch Exception
try {
if (input == 1){
System.out.println("What is a length of 1 side of the Square?\n");
double s1 = scan.nextDouble();
double SqAns = AreaCalculator.getSquareArea(s1);
System.out.println("The area of you square is: " + SqAns);
}
}
catch (InputMismatchException e)
{
System.out.println("Why are you trying to be clever? use an interger");
}
//Rectangle selection
if (input == 2){
System.out.println("What is the width of your rectangle?.\n");
double r1 = scan.nextDouble();
System.out.println("What is the height of your rectangle?\n");
double r2 = scan.nextDouble();
double RecAns = AreaCalculator.getRectArea(r1, r2);
System.out.println("The area of your rectangle is: " + RecAns);
}
//Triangle selection
if (input == 3){
System.out.println("What is the base length of the triangle?.");
double t1 = scan.nextDouble();
System.out.println("What is the height of your triangle?");
double t2 = scan.nextDouble();
double TriAns = AreaCalculator.getTriArea(t1, t2);
System.out.println("The area of your triangle is " + TriAns);
}
//Circle selection
if (input == 4){
System.out.println("What is the radius of your circle?.");
double c1 = scan.nextDouble();
double CircAns = AreaCalculator.getCircleArea(c1);
System.out.println("The area of your circle is " + CircAns);
}
//Exit application
if (input == 5){
System.out.println("Goodbye.");
}
}
}
AreaCalculator.java ////
package areaprog;
public class AreaCalculator {
public static double getRectArea(double width, double height) {
double aValue = width * height;
return aValue;
}
public static double getCircleArea(double radius){
double PI = Math.PI;
double aValue = PI * Math.pow(radius, 2);
return aValue;
}
public static double getSquareArea(double side) {
double aValue = Math.pow(side, 2);
return aValue;
}
public static double getTriArea(double base , double height) {
double aValue = (base/2)* height;
return aValue;
}
}
Having multiple classes inheriting from a single base class or interface is definitely a better design here. Use classes to encapsulate given functionality or objects(in that case triangle, square etc. Also when you have multiple classes sharing some functionality better extract it as a common interface to achieve better level of abstraction.
The simple answer is to use an interface of 'shape' like this
interface Shape {
double[] dimensions;
double calcArea();
}
And have all your shapes implement this interface.
say
class Circle implements Shape {
...
}
and implement different calcArea() methods for each shape
In your runner, you init a Circle, box, etc...
When you need area, you don't have to care about which shape is actually behind it, just call the method shape.calcArea() and it will find the right one.

Categories

Resources