cant get code for calculation of area - java

I've started a few demos which all have worked fine. I've recently stepped up the complexity and put together a paint program working out the area in metric and imperial. Although I don't get any compilation errors, When I try and run the program in Eclipse it misses out the calculation part. Hope somebody can help:
//program begin
package paintCalculation;
import java.util.Scanner;
public class PaintCoverageV1
{
public static void main(String[] args)
{
//Variables
double roomArea = 0, roomHeightSq = 0, roomWidthSq = 0, coverage = 172.22, wastage = 1.10;
double roomHeightRec, roomWidthRec, roomLengthRec;
double totalpaintgallons = (roomArea / coverage) * wastage;
double totalpaintlitres = totalpaintgallons * (4.54);
double metresconversion = 10.7;
char areaKnown, Y = 0, N = 0;
char con, I = 0, M = 0;
char roomType, S = 0, R = 0;
//Heading
System.out.println("Paint Coverage Calculator");
Scanner keyboard = new Scanner(System.in);
//areaKnown
System.out.println("Do you know wall area? (Y for YES, N for NO) ");
areaKnown = keyboard.next().charAt(0);
if (areaKnown == Y)
{
System.out.println("Enter room area ");
roomArea = keyboard.nextDouble();
}
else if (areaKnown == N)
{
//roomType
System.out.println("Enter room shape (S for Square, R for Rectangle) ");
roomType = keyboard.next().charAt(0);
if (roomType == S)
{
System.out.println("Enter wall height ");
roomHeightSq = keyboard.nextDouble();
System.out.println("Enter wall width ");
roomWidthSq = keyboard.nextDouble();
roomArea = (roomHeightSq * roomWidthSq) * 4;
}
else if (roomType == R)
{
System.out.println("Enter wall height ");
roomHeightRec = keyboard.nextDouble();
System.out.println("Enter wall length ");
roomLengthRec = keyboard.nextDouble();
System.out.println("Enter wall width ");
roomWidthRec = keyboard.nextDouble();
roomArea = ((roomHeightRec * roomWidthRec) + (roomLengthRec * roomHeightRec)) * 2;
}
}
{
//metricConversion
System.out.println("Which conversion is required? (M = Metric, I = Imperial)");
con = keyboard.next().charAt(0);
keyboard.close();
if (con == I)
{
System.out.print("Total amount of paint in gallon(s) required is " + totalpaintgallons);
System.out.print("Total amount of paint in litre(s) required is " + totalpaintlitres);
}
else if (con == M)
{
coverage = coverage / metresconversion;
System.out.print("Total amount of paint in gallon(s) required is " + totalpaintgallons);
System.out.print("Total amount of paint in litre(s) required is " + totalpaintlitres);
}
}
}
}
//program end

You need to change
if (areaKnown == Y)
to
if (areaKnown == 'Y')
and so on.
You current code compares areaKnown to the value of variable Y, which is zero, instead of comparing it to the character 'Y'.

Related

Returm to a specific line or place

I'm self learning Java for a few weeks and started testing my (basic) knowledge. I was trying to create something like some formula calculator, with an index selector. I want to know if it's possible to, after using a formula, go back to the first question. I tried to use a while loop, but I couldn't figure it out.
public class formulas {
public static void main(String[] args) {
// TODO Auto-generated method stub
// first question
// constant values definition
final double PI = 3.141592653589793238;
//index
ArrayList<String> index = new ArrayList<>();
index.add("1. Pythagorean Theorem");
index.add("2. Square Area");
index.add("2. Triangle Area");
System.out.println("Formulas Index:");
System.out.println("");
for(int i=0; i<index.size(); i++) {
System.out.println(index.get(i));
}
System.out.println("");
System.out.print("Write the formulas number you want to use: ");
Scanner scanner = new Scanner(System.in);
String firstQuestion = scanner.nextLine();
System.out.println();
// methods selection
if (firstQuestion.equals("1")) {
System.out.println("Pythagoras Theorem");
System.out.print("Insert side a: ");
double a = scanner.nextDouble();
System.out.print("Insert side b: ");
double b = scanner.nextDouble();
double c = pitagoras(a,b);
System.out.println("Hypotenuse c: "+ c);
}
else if (firstQuestion.equals("2")) {
System.out.println("Square area");
System.out.print("Insert side a: ");
double arestaA = scanner.nextDouble();
System.out.print("Insert side b: ");
double arestaB = scanner.nextDouble();
double squareArea = squarearea(arestaA,arestaB);
System.out.println("The square area is: "+ squareArea);
}
else System.out.println("Please insert a valid formula number.");
}
// methods parameters
static double pitagoras(double a, double b) {
double c = Math.sqrt((a*a)+(b*b));
return c;
}
static double squarearea(double a, double b) {
double area = a*b;
return area;
}
}
I'm always surprised that people don't make more use of do-while loops, it's a severely underrated construct.
Think about it, you MUST do at least one iteration of the loop before you know if you want to continue or exit the loop. You also want to re-print the menu on each iteration, so it's easier to just put it in a do-while (IMHO)
You can take a look at Control Flow Statements and The while and do-while Statements for more details
import java.util.ArrayList;
import java.util.Scanner;
public final class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
// first question
// constant values definition
final double PI = 3.141592653589793238;
//index
ArrayList<String> index = new ArrayList<>();
index.add("1. Pythagorean Theorem");
index.add("2. Square Area");
index.add("3. Triangle Area");
index.add("4. Quit");
Scanner scanner = new Scanner(System.in);
boolean printMenu = true;
boolean exit = false;
do {
if (printMenu) {
System.out.println("");
System.out.println("Formulas Index:");
System.out.println("");
for (int i = 0; i < index.size(); i++) {
System.out.println(index.get(i));
}
System.out.println("");
System.out.print("Write the formulas number you want to use: ");
}
printMenu = true;
String firstQuestion = scanner.nextLine();
System.out.println();
// methods selection
if (firstQuestion.equals("1")) {
System.out.println("Pythagoras Theorem");
System.out.print("Insert side a: ");
double a = scanner.nextDouble();
System.out.print("Insert side b: ");
double b = scanner.nextDouble();
double c = pitagoras(a, b);
System.out.println("Hypotenuse c: " + c);
} else if (firstQuestion.equals("2")) {
System.out.println("Square area");
System.out.print("Insert side a: ");
double arestaA = scanner.nextDouble();
System.out.print("Insert side b: ");
double arestaB = scanner.nextDouble();
double squareArea = squarearea(arestaA, arestaB);
System.out.println("The square area is: " + squareArea);
} else if (firstQuestion.equals("3")) {
// Triangle area
} else if (firstQuestion.equals("4")) {
exit = true;
} else {
printMenu = false;
System.out.println("Please insert a valid formula number.");
}
} while (!exit);
}
// methods parameters
static double pitagoras(double a, double b) {
double c = Math.sqrt((a * a) + (b * b));
return c;
}
static double squarearea(double a, double b) {
double area = a * b;
return area;
}
}
You can simply wrap your code starting from firstQuestion variable declaration till the end of the if condition in a while loop which is always set to true.
public class Formulas {
public static void main(String[] args) {
// first question
// constant values definition
final double PI = 3.141592653589793238;
// index
ArrayList<String> index = new ArrayList<>();
index.add("1. Pythagorean Theorem");
index.add("2. Square Area");
index.add("2. Triangle Area");
System.out.println("Formulas Index:");
System.out.println("");
for (int i = 0; i < index.size(); i++) {
System.out.println(index.get(i));
}
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("");
System.out.print("Write the formulas number you want to use: ");
String firstQuestion = scanner.nextLine();
System.out.println();
// methods selection
if (firstQuestion.equals("1")) {
System.out.println("Pythagoras Theorem");
System.out.print("Insert side a: ");
double a = scanner.nextDouble();
System.out.print("Insert side b: ");
double b = scanner.nextDouble();
double c = pitagoras(a, b);
System.out.println("Hypotenuse c: " + c);
} else if (firstQuestion.equals("2")) {
System.out.println("Square area");
System.out.print("Insert side a: ");
double arestaA = scanner.nextDouble();
System.out.print("Insert side b: ");
double arestaB = scanner.nextDouble();
double squareArea = squarearea(arestaA, arestaB);
System.out.println("The square area is: " + squareArea);
} else
System.out.println("Please insert a valid formula number.");
}
}
// methods parameters
static double pitagoras(double a, double b) {
double c = Math.sqrt((a * a) + (b * b));
return c;
}
static double squarearea(double a, double b) {
double area = a * b;
return area;
}
}

Prompting user for only positive number

this basic JAVA program should prompt the user, and print "Negative numbers are not allowed" until user enters a positive number. This must be handled by using while loop. how does it work ? This is my first post in stack overflow.
public static void main(String[] args)
{
System.out.print("Welcome to Box Price Calculator");
System.out.print(System.lineSeparator());
System.out.print(System.lineSeparator());
int boxVol = 20 ;
double price_each_box = 2.99;
System.out.print("Bottles :");
Scanner input = new Scanner(System.in);
int numberOfbottles = 1;
numberOfbottles = input.nextInt();
boolean valid = false;
while (input.nextInt() < 0){
System.out.println("Negative numbers are not allowed");
numberOfbottles = input.nextInt();
}
int box = (numberOfbottles / boxVol);
System.out.println("Box Needed : " + box);
double totPrice = (box * price_each_box);
System.out.println("Total Cost : $" + totPrice);
int leftOver = (numberOfbottles -(box * boxVol));
System.out.println("Unboxed :" + leftOver);
}
}
The problem here is that you are reading and compare again with input.nextInt() and not with numberOfbottles, inside the while condition. What you should do is to use a do...while and compare it with your variable numberOfbottles:
public static void main(String[] args)
{
System.out.print("Welcome to Box Price Calculator");
System.out.print(System.lineSeparator());
System.out.print(System.lineSeparator());
int boxVol = 20 ;
double price_each_box = 2.99;
java.util.Scanner input = new java.util.Scanner(System.in);
int numberOfbottles;
do
{
System.out.println("Bottles (Negative numbers are not allowed):");
numberOfbottles = input.nextInt();
}
while (numberOfbottles < 0);
int box = (numberOfbottles / boxVol);
System.out.println("Box Needed : " + box);
double totPrice = (box * price_each_box);
System.out.println("Total Cost : $" + totPrice);
int leftOver = (numberOfbottles -(box * boxVol));
System.out.println("Unboxed :" + leftOver);
}

How can I make a choice loop and only exit when numer 9 is put? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
import java.util.Scanner;
public class Geometry {
private Scanner scanner;
public double getCircleArea( double radius ) {
System.out.print("Enter circle area");
radius = scanner.nextDouble();
double RadiusSquared = Math.pow(radius, 2);
double circleArea = RadiusSquared * Math.PI;
return circleArea;
}
public double getRectangleArea( double length, double width ) {
System.out.print("Enter rectangle Length");
length = scanner.nextDouble();
System.out.print("Enter rectangle width");
width = scanner.nextDouble();
double rectangleArea = length * width;
return rectangleArea;
}
public double getTriangleArea( double base, double height ) {
System.out.println("enter triangle base");
base = scanner.nextDouble();
System.out.println("enter triangle height");
height = scanner.nextDouble();
double triangleArea = (base* height)/2;
return triangleArea;
}
public static void main( String[] args ) {
new Geometry().go();
}
private void go() {
scanner = new Scanner(System.in);
// main processing logic including input and output goes here.
int userNum = 0;
int secNum = 0;
while (userNum <= 0) {
System.out.println("1. Area of circle\n" + "2. Area of rectangle\n" + "3. Area of triangle\n" + "9. Exit");
userNum = scanner.nextInt();
if (userNum == 1){
System.out.println(getCircleArea(userNum));
}
else if (userNum == 2){
System.out.println(getRectangleArea(userNum,secNum));
}
else if (userNum == 3){
System.out.println(getTriangleArea(userNum,secNum));
}
else if (userNum == 9){
}
}
}
}
So I wanted it to only be able to put these 4 numbers but I am not sure if this is better than just a while loop, which I think I know how to do. Also what do you think about the actual geometry?
You can try the below code and figure out what's problematic in your code.
import java.util.Scanner;
public class Geometry {
private Scanner scanner;
public double getCircleArea( double radius ) {
System.out.print("Enter radius of circle to find area: ");
radius = scanner.nextDouble();
double RadiusSquared = Math.pow(radius, 2);
return RadiusSquared * Math.PI;
}
public double getRectangleArea( double length, double width ) {
System.out.print("Enter rectangle Length: ");
length = scanner.nextDouble();
System.out.print("Enter rectangle width: ");
width = scanner.nextDouble();
return length * width;
}
public double getTriangleArea( double base, double height ) {
System.out.print("enter triangle base: ");
base = scanner.nextDouble();
System.out.print("enter triangle height: ");
height = scanner.nextDouble();
return (base*height)/2;
}
public static void main( String[] args ) {
new Geometry().go();
}
private void go() {
scanner = new Scanner(System.in);
// main processing logic including input and output goes here.
int userNum = 0;
int secNum = 0;
while (userNum <= 0) {
System.out.println("1. Area of circle\n" + "2. Area of rectangle\n" + "3. Area of triangle\n");
System.out.print("choose a number: ");
userNum = scanner.nextInt();
if (userNum == 1) { System.out.println("Area of circle is " + getCircleArea(userNum)); }
else if (userNum == 2){ System.out.println("Area of rectangle is " + getRectangleArea(userNum,secNum)); }
else if (userNum == 3){ System.out.println("Area of triangle is " + getTriangleArea(userNum,secNum)); }
else System.exit(0);
}
}
}
It's depending on what your needs.
If you want to always display the menu selection bar once after user got the area, while is a must.
If not, just use Map to map each user's selection as to avoid bunches of if else block
//THIS IS FOR OPTION2
//no need the parameter, radius is depending input in the method scope
public double getCircleArea() {//...}
//...
public static void main( String[] args ) {
Map<Integer, Func> map = new HashMap();
map.put(num1, () -> getCircleArea());
//map.put(num2, xxx()) etc
new Geometry().go();
}
private void go() {
//...
map.get(userNum)
}
interface Func{
void execute();
}
(ps, from the code, seen scanner.nextDouble(), scanner.nextInt() to get from input of scanner. I think it is an alert when using different API to maintain the same functionality.
Because it violates encapsulation principle. java.util.Scanner already has the javadoc to interpret these, thus you should check from your side.
)

How to get JOptionPane to calculate area?

I have created this code, the GUI pops up and works perfectly, but the area is not being calculated correctly. Any Clue why? I am very new to Java coding, so any help is appreciated. Thanks in advance.
package pkg4.pkg2.pkgnew.project;
import javax.swing.JOptionPane;
public class NewProject {
public static void main(String[] args) {
String inputStr = JOptionPane.showInputDialog("Type 1 for the area of Triangle, 2 for area of Circle, 3 for Rectangle, and 0 for area of none of these.");
int i = Integer.parseInt(inputStr);
if (i == 1) {
String input = JOptionPane.showInputDialog("Enter the first value to calculate the area of a triangle: ");
int n1 = Integer.parseInt(inputStr);
String inp = JOptionPane.showInputDialog("Enter the second value to calculate the area of a triangle: ");
int n2 = Integer.parseInt(inputStr);
areaTriangle(n1, n2);
}
if (i == 2) {
String inpu = JOptionPane.showInputDialog("Enter a value to calculate the area of a circle: ");
double radius = Integer.parseInt(inputStr);
areaCircle(radius);
}
if (i == 3) {
String inp = JOptionPane.showInputDialog("Enter the first value to calculate the area of a rectangle: ");
int m1 = Integer.parseInt(inputStr);
String inp2 = JOptionPane.showInputDialog("Enter the second value to calculate the area of a rectangle: ");
int m2 = Integer.parseInt(inputStr);
areaRectangle(m1, m2);
} else {
return;
}
}
public static void areaTriangle(int n1, int n2) {
int areat = (n1 * n2) / 2;
JOptionPane.showMessageDialog(null, "The area of a triangle with your values is: " + areat);
}
public static void areaCircle(double radius) {
double areac = Math.PI * (radius * radius);
JOptionPane.showMessageDialog(null, "The area of a circle with your value is: " + areac);
}
public static void areaRectangle(int m1, int m2) {
int arear = (m1 * m2);
JOptionPane.showMessageDialog(null, "The area of a rectangle with your values is: " + arear);
}
public static void calcArea(int x) {
}
}
The problem with your code is that every time you parse the input into a string you are always using the same value of the string. Everytime you call your functions you are using all 1, 2, or 3 for your parameters into your area function calls. So you need to change the Integer.parseInt() to contain the new strings you get from the user like so:
String input = JOptionPane.showInputDialog("Enter the first value to calculate the area of a triangle: ");
int n1 = Integer.parseInt(input); //not inputStr <----------
String inp = JOptionPane.showInputDialog("Enter the second value to calculate the area of a triangle: ");
int n2 = Integer.parseInt(inp);//not inputStr <---------
areaTriangle(n1, n2);

Converting double to int or even decimal place

I was wondering if someone could tell me
1. why, when i input weightNumber with a decimal place, weightConverted doesn't convert it to the whole number, even though I create variable for it?
2. how could i improve this "program" in any way, THANK YOU !!
here is the problem:
code:
import java.util.Scanner;
public class cofee {
public static void main (String []args){
double weightNumber = 0;
String packageType = "";
String serviceType ="";
double totalFee = 0;
double weightConverted = Math.round(weightNumber); // <- this is the problem, should i put it somewhere else?
final double LETTERCOSTP = 12.00;
final double LETTERCOSTS = 10.50;
final double BOXCOSTP = 15.75;
final double BOXCOSTS = 13.75;
final double BOXWEIGHTP = 1.25;
final double BOXWEIGHTS = 1.00;
// input
Scanner input = new Scanner(System.in);
System.out.print("Enter package type (letter/box): ");
packageType = input.nextLine().toLowerCase();
System.out.print("Enter type of service (standard/priority): ");
serviceType = input.nextLine().toLowerCase();
switch(packageType)
{
case "letter":
System.out.print("Enter the weight in ounces: ");
weightNumber = input.nextDouble();
break;
case "box":
System.out.print("Enter the weight in pounds: ");
weightNumber = input.nextDouble();
break;
default:
System.out.print("WRONG PACKAGE TYPE !!!");
}
// letter
if (packageType.equals("letter") && serviceType.equals("priority"))
{
totalFee = LETTERCOSTP;
}
if (packageType.equals("letter") && serviceType.equals("standard"))
{
totalFee = LETTERCOSTS;
}
// box
if (packageType.equals("box") && serviceType.equals("priority"))
{
totalFee = BOXCOSTP + ((weightConverted - 1.0) * BOXWEIGHTP);
}
if (packageType.equals("box") && serviceType.equals("standard"))
{
totalFee = BOXCOSTS + ((weightConverted - 1.0) * BOXWEIGHTS);
}
// display
System.out.println("The fee is € "+ totalFee + " for a package with");
System.out.println("\tType: "+packageType);
System.out.println("\tService: "+serviceType);
System.out.println("\tOunces: "+weightConverted);
}
}
The line double weightConverted = Math.round(weightNumber); will call round() with the value of weightNumber, which is 0, so it rounds 0 to... well... 0, and assigns it to weightConverted.

Categories

Resources