My program will calculate the area but I need to have each different shape in it's own method and I'm having difficulty understanding how to first separate them all into their own method and link them all together. Any help is much appreciated.
import java.util.Scanner;
public class Project4 {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String s = "Please choose which area/volume to calculate: 1-Circle 2-Triangle 3-Cone 4-Cylinder 5-Sphere 6-Quit: ";
System.out.print(s);
System.out.println(" ");
int num = keyboard.nextInt();
if (num < 1 || num > 6){
System.out.print("Please choose a number between 1 and 6: ");
num = keyboard.nextInt();
}
if(num == 1){
System.out.print("Please enter the radius: ");
double r = keyboard.nextDouble();
double a;
a = 3.14 * r * r;
System.out.print("The area of the circle is: " + a);
System.out.println(" ");
System.out.print(s);
num = keyboard.nextInt();
}
if(num == 2){
System.out.print("Please enter the base: ");
double b = keyboard.nextDouble();
double at;
System.out.print("Please enter the height: ");
double h = keyboard.nextDouble();
at = .5 * b * h;
System.out.print("The area of the triangle is: " + at);
System.out.println(" ");
System.out.print(s);
num = keyboard.nextInt();
}
if(num == 3){
System.out.print("Please enter the radius: ");
double r = keyboard.nextDouble();
System.out.print("Please enter the height: ");
double h = keyboard.nextDouble();
double v1;
v1 = (1/3) * 3.14 * r * r * h;
System.out.print("The volume of the cone is: " + v1);
System.out.println(" ");
System.out.print(s);
num = keyboard.nextInt();
}
if(num == 4){
System.out.print("Please enter the radius: ");
double r = keyboard.nextDouble();
System.out.print("Please enter the height: ");
double h = keyboard.nextDouble();
double vc;
vc = 3.14 * r * r * h;
System.out.print("The volume of the cylinder is: " + vc);
System.out.println(" ");
System.out.print(s);
num = keyboard.nextInt();
}
if(num == 5){
System.out.print("Please enter the radius: ");
double r = keyboard.nextDouble();
double vs;
vs = (4/3) * 3.14 * r * r * r;
System.out.print("The volume of the sphere is: " + vs);
System.out.println(" ");
System.out.print(s);
num = keyboard.nextInt();
}
if(num == 6){
System.out.print("Thank you for using this program");
}
}
}
You can use switch..case
switch(num) {
case 1: calculateCircleArea();
break;
case 2: calculateTriangleArea();
break;
case 3: calculateConeVolume();
break;
case 4: calculateCylinderVolume();
break;
case 5: calculateSphereVolume();
break;
case 6: System.out.print("Thank you for using this program");
break;
default: System.out.print("Please choose a number between 1 and 6: ");
break;
}
You can create new private/public methods to do the calculations and seperate them.
Take this part
if(num == 1){
System.out.print("Please enter the radius: ");
double r = keyboard.nextDouble();
double a;
a = 3.14 * r * r;
System.out.print("The area of the circle is: " + a);
System.out.println(" ");
System.out.print(s);
num = keyboard.nextInt();
}
You can create a new method for the calculation like so
public static double getArea(double radius)
{
return 3.14*radius*radius;
}
Then, inside your if statement you can say
if(num == 1){
System.out.print("Please enter the radius: ");
double r = keyboard.nextDouble();
double a;
a = getArea(r);
System.out.print("The area of the circle is: " + a);
System.out.println(" ");
System.out.print(s);
num = keyboard.nextInt();
}
you see in this case, you get a one-line method which isn't very usefull. But you can split off more extensive calculations as well, this is just as an example. In addition, instead of all the if-blocks, you can use a switch statement like the other answer shows you.
Related
My code is about looping and method, A program that will let user either compute an area or use the 4 basic math operations. the (Triangle, Square,Rectangle) with their choice of process: Addition, Subtraction, Multiplication and Division.
I think i properly closed the addition function there and i already check the closing every functions they seem work well other than the addtion function since thats the only error i got.
import java.util.Scanner;
public class Main{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
//WHILE LOOP FOR CHOICES
while(true){//CHOICES LOOP
System.out.println("∘₊✧─────────────────────────────────────✧₊∘");
System.out.println("Input Choice of Process");
System.out.println("1 - Addition process");
System.out.println("2 - Subtraction process");
System.out.println("3 - Multiplication process");
System.out.println("4 - Division process");
System.out.println("5 - Compute process");
System.out.println("Your choice: ");
int option = scan.nextInt();
System.out.println("∘₊✧─────────────────────────────────────✧₊∘");
if(option == 1){
Add();
}
else if(option == 2){
Sub();
}
else if(option == 3){
Mul();
}
else if(option == 4){
Div();
}
else if(option == 5){
Com();
}
else if((option>=6)&&(option<=100)){//INVALID
System.out.println("Invalid Input, Please Input Choice Again.");
}
else{//- if user input other number, the program will break and stop from looping
break;
}
Here Im getting a error here im not sure what is it
public static void Add(){
System.out.println("ADDITION");
System.out.println("Enter two numbers: ");
System.out.println("1st number: ");
int add1=scan.nextInt();
System.out.println("2nd number: ");
int add2=scan.nextInt();
int addtotal=add1+add2;
if(addtotal>100){// In addition, if the sum is higher than 100, print the answer the word high. if equal and below 100, print low
System.out.println("Total is "+addtotal+" High");
}
else if(addtotal<100){
System.out.println("Total is "+addtotal+" Low");
}
}
public static void Sub(){//SUBTRACTION
System.out.println("SUBTRACTION");
System.out.println("Enter two numbers: ");
System.out.println("1st number: ");
int sub1=scan.nextInt();
System.out.println("2nd number: ");
int sub2=scan.nextInt();
int subtotal=sub1-sub2;
if(subtotal<0){// In subtraction, if the difference is negative, print invalid. If 0 or above, print the difference and the word valid.
System.out.println("Invalid ");
}
else if(subtotal>0){
System.out.println("Total is "+subtotal+" Valid");
}
}
public static void Mul(){//MULTIPLICATION
System.out.println("MULTIPLICATION");
System.out.println("Enter two numbers: ");
System.out.println("1st number: ");
double multi1=scan.nextDouble();//In multiplication, make it accepts decimal value
System.out.println("2nd number: ");
double multi2=scan.nextDouble();
double multitotal=multi1*multi2;
System.out.println("Total is "+multitotal);
}
public static void Div(){
System.out.println("DIVISION");
System.out.println("Enter two numbers: ");
System.out.println("1st number: ");
int div1=scan.nextInt();
System.out.println("2nd number: ");
int div2=scan.nextInt();
int divtotal= div1 / div2;
int divremainder= div1 % div2;//In division, if it has remainder, print the answer and the remainder.
System.out.println("Total is "+divtotal);
System.out.println("Remainder is "+divremainder);
}
public static void Com(){// If user choose 5, the user needs to choose again on a ,b or c. If other letter, print invalid and then go pack on choosing of process.
System.out.println("∘₊✧─────────────────────────────────────✧₊∘");
System.out.println("Input Choice of Process");
System.out.println("a - Rectangle");
System.out.println("b - Square");
System.out.println("c - Triangle");
System.out.println("Your choice: ");
Scanner Keyboard = new Scanner(System.in);
Scanner input = new Scanner(System.in);
char choice = Keyboard.nextLine().charAt(0);
System.out.println("∘₊✧─────────────────────────────────────✧₊∘");
if (choice == 'A' || choice == 'a')//rectangle
{
System.out.println("Enter length of rectangle's base: ");
double base = input.nextDouble();
System.out.println("Enter length of rectangle's height: ");
double height = input.nextDouble();
double rArea = base * height;
System.out.println("The area of a rectangle with a base length of " + base + " and a height of " + height + " is " + rArea + ".");
}
else if (choice == 'B' || choice == 'b') //square
{
System.out.println("Enter length of square's sides: ");
double sSide = input.nextDouble();
double sArea = sSide * sSide;
System.out.println("The area of a square with a side length of " + sSide + " is " + sArea + ".");
}
else if (choice == 'C' || choice == 'c') //traingle
{
System.out.println("Enter traingle's side length: ");
double tSide = input.nextDouble();
double tArea = tSide * tSide * tSide;
System.out.println("The area of a triangle with a side length of " + tSide + " is " + tArea + ".");
}
else //invalid
{
System.out.println("You've entered an invalid character.");
}
}
}
You haven't got a closing brace for your main method
I cannot quite figure out how to make my basic financial calculator be able to run a new set of numbers without closing the program. What I currently have allows me to run one set of numbers, and when I get to "Would you like to continue?", when I press 1 it simply will print "Would you like to continue?" however many times I press 1. Here is what I have so far:
package Register;
import java.util.Scanner;
public class Register {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Register myRegister = new Register();
System.out.println("Welcome to the Electricity Bill calculator.");
System.out.print("Enter amount of electricity (kW) used in the daytime: ");
float num1 = scan.nextFloat();
System.out.print("Enter amount of electricity (kW) used in the evening: ");
float num2 = scan.nextFloat();
System.out.print("Enter rate for daytime: ");
float num3 = scan.nextFloat();
System.out.print("Enter rate for evening: ");
float num4 = scan.nextFloat();
float day1 = num1 * num3;
float night2 = num2 * num4;
float total = day1 + night2;
{
System.out.println("Electricity Bill: $" + total);
}
System.out.println("");
boolean keepLooping = true;
while (keepLooping) {
System.out.print("Would you like to continue? Press 1 continue or 0 to exit.");
int answer = scan.nextInt();
if(answer == 0) {
keepLooping = false;
} else {
keepLooping = true;
}
}
}
}
You have used while loop around asking choice statements only. So use while loop at the beginning in main method as below:
import java.util.Scanner;
public class Register{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Register myRegister = new Register();
boolean keepLooping = true;
while(keepLooping) {
System.out.println("Welcome to the Electricity Bill calculator.");
System.out.print("Enter amount of electricity (kW) used in the daytime: ");
float num1 = scan.nextFloat();
System.out.print("Enter amount of electricity (kW) used in the evening: ");
float num2 = scan.nextFloat();
System.out.print("Enter rate for daytime: ");
float num3 = scan.nextFloat();
System.out.print("Enter rate for evening: ");
float num4 = scan.nextFloat();
float day1 = num1 * num3;
float night2 = num2 * num4;
float total = day1 + night2;
System.out.println("Electricity Bill: $" + total);
System.out.println("");
System.out.print("Would you like to continue? Press 1 continue or 0 to exit.");
int answer = scan.nextInt();
if(answer == 0) {
keepLooping = false;
} else {
keepLooping = true;
}
}
}
}
The program is not quitting when choice 2 is entered instead it's asking to enter a positive value. It should only ask that if the choice was 1 and then the number of rooms entered was less than one. It should immediately quit the program but it's not. What can I do to fix this? Is it because of braces missing or extra ones.
import java.util.Scanner;
import java.text.DecimalFormat;
public class Paint {
public static void main(String[] args) {
DecimalFormat formatter = new DecimalFormat("###0.00");
Scanner keyboard = new Scanner(System.in);
double numbGallons;
double costPerGallon;
double totalSquareFeet = 0;
double numbHours;
double costPerHour;
double paintCost1;
double squareFeet;
int choice;
int numRooms = 0;
double laborCost1;
double totalEstimate;
do {
displayMenu();
choice = keyboard.nextInt();
if (choice == 1) {
System.out.println("How many rooms do you want to paint?");
numRooms = keyboard.nextInt();
}
while (numRooms < 1) {
System.out.println("Please enter a positive value");
numRooms = keyboard.nextInt();
}
for (int counter = 1; counter <= numRooms; counter++) {
System.out.println("How many square feet of room " + counter +
" do you want to paint?");
squareFeet = keyboard.nextDouble();
totalSquareFeet = totalSquareFeet + squareFeet;
}
System.out.println("The total square feet is " + totalSquareFeet);
numbGallons = numGallons(totalSquareFeet);
numbHours = numHours(totalSquareFeet);
System.out.println("How much is the price per hour?");
costPerHour = keyboard.nextDouble();
System.out.println("How much is the price per gallon?");
costPerGallon = keyboard.nextDouble();
laborCost1 = laborCost(costPerHour, numbHours);
paintCost1 = paintCost(numbGallons, costPerGallon);
System.out.println("The number of Gallons is " + numbGallons);
System.out.println("The number of Hours is " + numbHours);
System.out.println("The labor cost is " + laborCost1);
System.out.println("The paint cost is " + paintCost1);
totalEstimate = laborCost1 + paintCost1;
System.out.println("The total estimate is " + totalEstimate);
} while (choice != 2);
}
public static void displayMenu() {
System.out.println("1)Calculate Estimate");
System.out.println("2)Quit the program");
System.out.println("Please make a selection");
}
public static double numGallons(double sqr) {
return sqr / 115;
}
public static double numHours(double sqr) {
return (sqr / 115) * 8;
}
public static double laborCost(double cph, double nh) {
return cph * nh;
}
public static double paintCost(double ng, double cpg) {
return ng * cpg;
}
}
You should show the menu and get the choice before entering the loop, and at the end of the loop.
public static void main(String[] args) {
DecimalFormat formatter = new DecimalFormat("###0.00");
Scanner keyboard = new Scanner(System.in);
double numbGallons;
double costPerGallon;
double totalSquareFeet = 0;
double numbHours;
double costPerHour;
double paintCost1;
double squareFeet;
int choice;
int numRooms = 0;
double laborCost1;
double totalEstimate;
displayMenu();
choice = keyboard.nextInt();
while (choice != 2) {
//if (choice ==1)
//{
System.out.println("How many rooms do you want to paint?");
numRooms = keyboard.nextInt();
//}
while (numRooms < 1) {
System.out.println("Please enter a positive value");
numRooms = keyboard.nextInt();
}
for (int counter = 1; counter <= numRooms; counter++) {
System.out.println("How many square feet of room " + counter +
" do you want to paint?");
squareFeet = keyboard.nextDouble();
totalSquareFeet = totalSquareFeet + squareFeet;
}
System.out.println("The total square feet is " + totalSquareFeet);
numbGallons = numGallons(totalSquareFeet);
numbHours = numHours(totalSquareFeet);
System.out.println("How much is the price per hour?");
costPerHour = keyboard.nextDouble();
System.out.println("How much is the price per gallon?");
costPerGallon = keyboard.nextDouble();
laborCost1 = laborCost(costPerHour, numbHours);
paintCost1 = paintCost(numbGallons, costPerGallon);
System.out.println("The number of Gallons is " + numbGallons);
System.out.println("The number of Hours is " + numbHours);
System.out.println("The labor cost is " + laborCost1);
System.out.println("The paint cost is " + paintCost1);
totalEstimate = laborCost1 + paintCost1;
System.out.println("The total estimate is " + totalEstimate);
displayMenu();
choice = keyboard.nextInt();
}
}
I just recently finished the following program. Now we were asked to make the following code in the snipet that I have presented into a class that calls from the driver program, but I don't know as to how that would look, how it would work, or the terminology needed to do this.
/**
* Will Calculate the Area of Given Shapes.
*
* #author Adrian Miranda
* #version (a version number or a date)
*/
import java.util.Scanner;
public class Area_Shapes
{
public static void main(String[] args)
{
Scanner stdIn = new Scanner(System.in);
int Shape;
String A = "The Area is ";
double Area;
double Base;
double Height;
double q1;
double q2;
double radius;
double Length;
char response;
do
{
System.out.println(" Enter A Shape 1 = triangle 2 = square 3 = rhombus 4 = circle 5 = rectangle: ");
Shape = stdIn.nextInt();
if (Shape == 1)
{
System.out.println("Enter Base: ");
Base = stdIn.nextDouble();
System.out.println("Enter Height: ");
Height = stdIn.nextDouble();
Area = (Base * Height)/ 2 ;
System.out.println( A + Area);
System.out.println(" Enter Another Shape? (y/n): ");
response = stdIn.next() .charAt(0);
}
else if (Shape == 2)
{
System.out.println("Enter length ");
Length = stdIn.nextDouble();
Area = Length * Length;
System.out.println( A + Area);
System.out.println(" Enter Another Shape? (y/n): ");
response = stdIn.next() .charAt(0);
}
else if (Shape == 3)
{
System.out.println("Enter q1: ");
q1 = stdIn.nextDouble();
System.out.println("Enter q2: ");
q2 = stdIn.nextDouble();
Area = q1 * q2 * 0.5 ;
System.out.println( A + Area);
System.out.println(" Enter Another Shape? (y/n): ");
response = stdIn.next() .charAt(0);;
}
else if (Shape == 4)
{
System.out.println("Enter radius ");
radius = stdIn.nextDouble();
Area = radius * Math.PI * radius;
System.out.println( A + Area);
System.out.println(" Enter Another Shape? (y/n): ");
response = stdIn.next() .charAt(0);
}
else if (Shape == 5)
{
System.out.println("Enter Base: ");
Base = stdIn.nextDouble();
System.out.println("Enter Height: ");
Height = stdIn.nextDouble();
Area = (Base * Height) ;
System.out.println( A + Area);
System.out.println(" Enter Another Shape? (y/n): ");
response = stdIn.next() .charAt(0);
}
else
{
System.out.println("error, invalid shape, please enter a square triangle or rhombus.");
System.out.println(" Enter Another Shape? (y/n}: ");
response = stdIn.next() .charAt(0);;
}
}while (response == 'y');
}
}
Conceptually, you should remove the main(...) method from the Area_Shapes class. Create a constructor in Area_Shapes that accepts the necessary parameters. Create a new class (e.g., ShapesDriver) that has a main(...) method. After collecting the information in the driver, instantiate the Area_Shapes class.
I would actually create multiple Shape classes rather than a single class that lumps everything together, but that is larger refactoring (but more OO-like). I would also make a method to calculate and display the results rather than doing the work in the constructor.
Nonetheless, the basic conceptual approach (edit: added an example loop to the driver class)
public class Area_Shapes {
public Area_Shapes(int shape, double l1, double l2)
{
double area;
switch (shape) {
case 1:
area = (l1 * l2) / 2;
System.out.println("A triangle has an area of: " + area);
break;
...
}
}
}
Driver Class
public class Driver {
public static void main(String args[]) {
boolean keepGoing = true;
do {
//collect shape information
System.out.println("Enter your shape (1 = triangle ...");
shape = stdIn.nextInt();
// based upon the shape, collect the inputs
double inp1, inp2;
switch (shape) {
case 1:
// inp1 is the base, inp2 is the height
System.out.println("Enter Base: ");
inp1 = stdIn.nextDouble();
System.out.println("Enter Height: ");
inp2 = stdIn.nextDouble();
break;
} //switch shape
// create a shape area instance; this calculates the
// area and outputs the answer
Shape_Area sa = new Shape_Area(shape, inp2, inp2);
// prompt the user to enter another shape
if (user_wants_to_stop) {
keepGoing = false;
}
} while (keepGoing)
} // main()
}
I am sorry to post again so soon, but I ran into another error in my Tax program. My program is only supposed to work if someone enters only 's,' 'S,' 'm,' 'M,' 'c,' or 'C' for the marital status. When I entered anything that does not start with one of those letters, it prints Invalid Entry, like it is supposed to, but when I enter something that starts with an upper/lowercase s, m, or c, it proceeds as if I only entered that first letter. How do I make it so that the program only proceeds if you enter the one letter?
Thanks!!
Here is my code:
import java.util.Scanner;
public class TaxPrep
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
char maritalStatus;
double grossIncome = 0;
double numberOfExemptions = 0;
double taxRate = 0;
double taxableIncome = 0;
double taxesOwed = 0;
String anotherCustomer = "y";
System.out.print("A A R O N ' S T A X P R E P A R E R\n\n");
do{
System.out.print("Are you (s)ingle, (m)arried, or (c)ohabiting?\n");
System.out.print("Enter s, m, or c ==> ");
maritalStatus = sc.next().charAt(0);
switch (maritalStatus)
{
case 's': case 'S':
System.out.print("Gross income ==> ");
grossIncome = sc.nextDouble();
System.out.print("Number of exemptions ==> ");
numberOfExemptions = sc.nextInt();
taxableIncome = grossIncome - (1000 * numberOfExemptions);
taxRate = 20;
break;
case 'm': case 'M':
System.out.print("Gross income ==> ");
grossIncome = sc.nextDouble();
System.out.print("Number of exemptions ==> ");
numberOfExemptions = sc.nextInt();
taxableIncome = grossIncome - (1000 * numberOfExemptions);
taxRate = 25;
break;
case 'c': case 'C': //tax rate for cohabiting depends on taxable income
System.out.print("Gross income ==> ");
grossIncome = sc.nextDouble();
System.out.print("Number of exemptions ==> ");
numberOfExemptions = sc.nextInt();
taxableIncome = grossIncome - (1000 * numberOfExemptions);
if (taxableIncome <= 20_000)
{
taxRate = 10;
break;
}
else if (taxableIncome <= 50_000)
{
taxRate = 15;
break;
}
else
{
taxRate = 30;
break;
}
default: //if input for marital status is invalid
System.out.print("\nInvalid entry.\n");
continue;
}
taxesOwed = taxableIncome * (taxRate / 100);
//taxable income and taxes owed cannot be negative
if (taxableIncome < 0)
{
taxableIncome = 0;
}
if (taxesOwed < 0)
{
taxesOwed = 0;
}
//tax summary
System.out.print("\nINCOME TAX SUMMARY");
System.out.print("\ntax rate: " + taxRate + "%");
System.out.print("\ntaxable income: $" + taxableIncome);
System.out.print("\ntaxes owed: $" + taxesOwed);
//would you like to process another customer?
System.out.print("\n\nProcess another customer? (y/n): ");
anotherCustomer = sc.next();
System.out.print("\n");
} while (anotherCustomer.equalsIgnoreCase("y")); //as long as user enters 'y' or 'Y', the program will continue to calculate the income tax summary
}
}
You are testing only the first character, even if the entered word is longer:
maritalStatus = sc.next().charAt(0);
sc.next() returns a String, and charAt(0) returns just its first character. So if you entered "sFoo", maritalStatus would just be 's' and the "Foo" would be ignored.
You should get the whole entered String (and possibly convert it to upper case for easier comparison in the switch). The variable maritalStatus should be declared as String in this case:
maritalStatus = sc.next().toUpperCase();
switch (maritalStatus) {
case "S":
//...
}
Switch statement works with Strings, unless you are using Java 6 or older. In that case you would use:
maritalStatus = sc.next().toUpperCase();
if (maritalStatus.equals("S")) {
//...
} else if...