I have received four error messages in my code. It states that in modes 2 and 4, dArea cannot be resolved to a variable. Later in the code, the same variable is said to be duplicated even though it has only been assigned value, used, and returned. How can I fix these issues?
import javax.swing.JOptionPane;
public class Lab7
{
public static void main(String args [])
{
// Created by Makayla Scull, period 4B
String sMode;
int iMode = 0;
sMode = JOptionPane.showInputDialog("Menu: \n [Square: Press 1] \n [Rectangle: Press 2] \n [Circle: Press 3] \n [Triangle: Press 4] \n [Trapezoid: Press 5] \n [To Exit: Press 6]");
iMode = Integer.parseInt(sMode);
while(iMode == 0);
{
if (iMode == 1)
{
Geometry.methodSquare();
}
if (iMode == 2)
{
Geometry.methodRectangle(dArea);
}
if (iMode == 3)
{
Geometry.methodCircle();
}
if (iMode == 4)
{
Geometry.methodTriangle(dArea);
}
if (iMode == 5)
{
Geometry.methodTrapezoid();
}
if (iMode == 6)
{
break;
}
}
}
}
class Geometry
{
public static void methodSquare()
{
String sLength;
double dLength;
double dArea;
int exp = 2;
JOptionPane.showMessageDialog(null, "You chose the square.");
sLength = JOptionPane.showInputDialog("Enter the side length of the square.");
dLength = Double.parseDouble(sLength);
dArea = Math.pow(dLength, exp);
JOptionPane.showMessageDialog(null, "The area of the square is " + dArea);
}
public static double methodRectangle(double dArea)
{
String sLength;
String sWidth;
double dLength;
double dWidth;
JOptionPane.showMessageDialog(null, "You chose the rectangle.");
sLength = JOptionPane.showInputDialog("Enter the length of the rectangle.");
sWidth = JOptionPane.showInputDialog("Enter the width of the rectangle.");
dLength = Double.parseDouble(sLength);
dWidth = Double.parseDouble(sWidth);
double dArea = (dLength * dWidth);
JOptionPane.showMessageDialog(null, "The area of the rectangle is " + dArea);
return dArea;
}
public static double methodCircle()
{
String sRadius;
double dRadius;
int exp = 2;
JOptionPane.showMessageDialog(null, "You chose the circle.");
sRadius = JOptionPane.showInputDialog("Enter the radius of the circle.");
dRadius = Double.parseDouble(sRadius);
double dArea = Math.pow(dRadius, exp) * Math.PI;
JOptionPane.showMessageDialog(null, "The area of the circle is " + dArea);
return dArea;
}
public static double methodTriangle(double dArea)
{
String sBase;
String sHeight;
double dBase;
double dHeight;
JOptionPane.showMessageDialog(null, "You chose the triangle.");
sBase = JOptionPane.showInputDialog("Enter the base length of the triangle.");
dBase = Double.parseDouble(sBase);
sHeight = JOptionPane.showInputDialog("Enter the height of the triangle.");
dHeight = Double.parseDouble(sHeight);
double dArea = (dBase * dHeight) / 2;
JOptionPane.showMessageDialog(null, "The area of the triangle is " + dArea);
return dArea;
}
public static void methodTrapezoid()
{
String sHeight;
String sBase1;
String sBase2;
double dHeight;
double dBase1;
double dBase2;
JOptionPane.showMessageDialog(null, "You chose the trapezoid.");
sHeight = JOptionPane.showInputDialog("Enter the height of the trapezoid.");
dHeight = Double.parseDouble(sHeight);
sBase1 = JOptionPane.showInputDialog("Enter the length of the first base of the trapezoid.");
dBase1 = Double.parseDouble(sBase1);
sBase2 = JOptionPane.showInputDialog("Enter the length of the second base of the trapezoid.");
dBase2 = Double.parseDouble(sBase2);
double dArea = ((dBase1 + dBase2) * dHeight) / 2;
JOptionPane.showMessageDialog(null, "The area of the trapezoid is " + dArea);
}
}
in modes 2 and 4, dArea cannot be resolved to a variable
That's because you never defined that variable. You try to use it:
Geometry.methodRectangle(dArea);
But nowhere in that scope have you defined it. A value has to exist before it can be used.
the same variable is said to be duplicated
Your methods define a variable as a parameter to the method:
public static double methodRectangle(double dArea)
But then also try to declare it again within the method:
double dArea = (dLength * dWidth);
Just as the error is telling you, a variable can only be declared once in any given scope. If you try to have two variables by the same name in the same scope then the compiler would have no way of knowing which one you're referring to.
Related
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.
)
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);
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.
I have a problem with my java application when i compile my codes it says that it cannot find symbol roomLength.
what the application supposed to do is prompt the user to input a room name then if it is "quit" then it has to close the program. otherwise it will prompt for the length, width and height of the room. if any of these dimensions is zero or lesser, it will reprompt for the dimensions again.
class Room
{
private String name;
private double length;
private double width;
private double height;
public Room(String r, double l, double w, double h)
{
name = r;
length = l;
width = w;
height = h;
}
public String getName()
{
return name;
}
public double getLength()
{
return length;
}
public double getWidth()
{
return width;
}
public double getHeight()
{
return height;
}
public double getArea()
{
double area = length*width;
return area;
}
public double getVolume()
{
double volume = length*width*height;
return volume;
}
public void setName(String s)
{
name = s;
}
}
And here's my main method.
import java.util.Scanner;
class TestRoom
{
public static void main(String [] args)
{
Scanner userInput = new Scanner(System.in);
System.out.println("Please enter the name of room");
String roomName = userInput.next();
if(roomName.equals("quit"))
{
userInput.close();
} else
{
do
{
Scanner dimensionsInput = new Scanner(System.in);
System.out.print("Please enter the dimensions of the room, length, width and height accordingly");
double roomLength = dimensionsInput.nextDouble();
double roomWidth = dimensionsInput.nextDouble();
double roomHeight = dimensionsInput.nextDouble();
Room r = new Room(roomName, roomLength, roomWidth, roomHeight);
}
while (roomLength > 0 || roomWidth > 0 || roomHeight > 0);
System.out.println("The name of room: " + r.getName() + " Dimensions: L= " + r.getLength() +
"X " + "W= " + r.getWidth() + "X " + "H= " + r.getHeight());
System.out.println("Area of room= " + r.getArea());
System.out.println("Volume of room= " + r.getVolume());
}
}
}
Thanks in advance! ;)
There's another question almost similar to this question except it supposed to loop back to the first prompt allowing the user to input another room's name and its dimensions.
Java do while loop back to the beginning of application
Cheers!
You're trying to access variables outside the scope they're declared in. You have to declare the variables outside the do so you can access them in the while:
double roomLength;
double roomWidth;
double roomHeight;
do
{
Scanner dimensionsInput = new Scanner(System.in);
System.out.print("Please enter the dimensions of the room, length, width and height accordingly");
roomLength = dimensionsInput.nextDouble();
roomWidth = dimensionsInput.nextDouble();
roomHeight = dimensionsInput.nextDouble();
Room r = new Room(roomName, roomLength, roomWidth, roomHeight);
}
while (roomLength > 0 || roomWidth > 0 || roomHeight > 0);
But I see now that Room is also declared with the wrong scope. You have to declare it before the loop if you want to access it afterwards. So a simpler solution might be:
Room r;
do
{
Scanner dimensionsInput = new Scanner(System.in);
System.out.print("Please enter the dimensions of the room, length, width and height accordingly");
double roomLength = dimensionsInput.nextDouble();
double roomWidth = dimensionsInput.nextDouble();
double roomHeight = dimensionsInput.nextDouble();
r = new Room(roomName, roomLength, roomWidth, roomHeight);
}
while (r.getLength() > 0 || r.getWidth() > 0 || r.getHeight() > 0);
Incidentally, it doesn't seem right that you're looping until all dimensions are 0. I suspect you mean to check == 0.
You have to declare the variables roomLength, roomWidth and roomHeight in front of the do-while loop.
Like this:
double roomLength = 0;
double roomWidth = 0;
double roomHeight = 0;
do {
dimensionsInput = new Scanner(System.in);
System.out.print("Please enter the dimensions of the room, length, width and height accordingly");
roomLength = dimensionsInput.nextDouble();
roomWidth = dimensionsInput.nextDouble();
roomHeight = dimensionsInput.nextDouble();
Room r = new Room(roomName, roomLength, roomWidth, roomHeight);
} while (roomLength > 0 || roomWidth > 0 || roomHeight > 0);
The problem is the scope of your variables. roomLength, roomWidth and roomHeight are only visible inside the do-block. But the statements inside the while are outside of the do-block. Thats why the variables could not be found.
import java.util.Scanner;
public class Hw4Part4 {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
//Ask for the diners’ satisfaction level using these ratings: 1 = Totally satisfied, 2 = Satisfied,
//3 = Dissatisfied.
System.out.println("Satisfacion leve: ");
int satisfactionNumber= sc.nextInt();
//Ask for the bill subtotal (not including the tip)
System.out.println("What is the bill subtotal: ");
double subtotal= sc.nextInt();
//Report the satisfaction level and bill total.
System.out.println("The satisfaction level is: "+ satisfactionLevel(satisfactionNumber));
System.out.println("The bill total is: " + getBillTotal(tipPercentage, subtotal));
}
public static String satisfactionLevel(int satisfactionNumber){
String satisfactionL = "";
if (satisfactionNumber == 1){
satisfactionL ="Totally-satisfied";
}
if (satisfactionNumber == 2){
satisfactionL = "Satisfied";
}
if (satisfactionNumber == 3){
satisfactionL = "Dissatisfied";
}
return satisfactionL;
}
//This method takes the satisfaction number and returns the percentage of tip to be
//calculated based on the number.
//This method will return a value of 0.20, 0.15, or 0.10
public static double getPercentage(int satisfactionNumber){
double getPercentage = 0;
if (satisfactionNumber ==1){
getPercentage = 0.20;
}
if (satisfactionNumber ==2){
getPercentage = 0.15;
}
if (satisfactionNumber ==3){
getPercentage = 0.10;
}
return getPercentage;
}
public static double getBillTotal(double tipPercentage, double subtotal){
double totalWithTip= (subtotal + ( getPercentage(satisfactionNumber) * subtotal));
return totalWithTip;
}
}
I am having issues on the last method, the whole code is shown above.
It says there is error with the part where I am trying to use the previous method.
I need to get the percentage which was computed on the previous method.
At this part of the code:
public static double getBillTotal(double tipPercentage, double subtotal){
double totalWithTip= (subtotal + ( getPercentage(satisfactionNumber) * subtotal));
return totalWithTip;
}
You call this method:
getPercentage(satisfactionNumber)
However, this variable:
satisfactionNumber
Doesn't exist in this method's scope. You should pass this variable to the method as so:
public static double getBillTotal(double tipPercentage, double subtotal, int satisfactionNumber){
double totalWithTip= (subtotal + ( getPercentage(satisfactionNumber) * subtotal));
return totalWithTip;
}
So when you call the method in the main, you pass it in:
System.out.println("The bill total is: " + getBillTotal(tipPercentage, subtotal, satisfactionNumber));
tipPercentage cannot be resolved to a varible
Pretty much any variable you pass in, you must create. So when you do the above line, make sure you have all variables delcared:
double tipPercentage, subtotal, satisfactionNumber;
//now set these three variables with a value before passing it to the method
System.out.println("The bill total is: " + getBillTotal(tipPercentage, subtotal, satisfactionNumber));
It's hard to tell, but I think you need to remove whitespace:
double totalWithTip = subtotal + (getPercentage(satisfactionNumber) * subtotal);
return totalWithTip;
This code assumes a variable:
int satisfactionNumber;
and a method:
double getPercentage(int satisfactionNumber) {
// some impl
}