Java SE do while loop issues - java

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.

Related

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.
)

Simulating the rise and fall of the Stock Market java

So I'm trying to write a program that stimulates the rise and fall of the Stock market 5 times.The user inputs a value to create a new Stock Market Object then with the value from the user, the stock market either is a bust(decrease) or a boom( increase). The issue I'm having is passing the value to each if statement with the change within the loop.When I run the program, It uses the same value I entered instead of using the value that was created after calling boom or bust. I'm thinking I should create a value outside the loop that holds it but I'm not sure how to do that with the user input.
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a Starting Market Value:");
double mv = in.nextDouble();
StockMarket u = new StockMarket(mv);
for (int i = 0; i < 5; i++) {
System.out.println("Boom (1) or Bust(2)? ");
int t = in.nextInt();
if (t == 1) {
System.out.println("Enter a percentage of increase as a decimal ( eg .5 ):");
double r = in.nextDouble();
if (t == 1) {
double e = u.boom(r);
System.out.println("The Stock Market is now at: " + e);
}
} else if (t == 2) {
System.out.println("Enter number of points lost:");
double l = in.nextDouble();
if (t == 2) {
double f = u.bust(l);
System.out.println("The Stock Market is now at: " + f);
}
}
}
}
}
Below is the class
public class StockMarket {
//Instance Variable Points
private double Points;
// Default no Argument Constructor
public StockMarket(){
this(0.0);
}
// Constructor #2
public StockMarket(double Points){
this.Points = Points;
}
//
public double getPoint(){
return Points;
}
public double boom(double x){
x = Points * (1 + x);
return x;
}
public double bust( double h){
h = Points - h;
return h;
}
}

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);

How to Calculate BMI in Java

I'm writing a program that takes the users input for height and weight then calculates the Body Mass Index from this. It uses separate methods for height, weight and BMI, these methods are called from main. The problem I'm having is I have absolutely no clue how to put the input from weight and height methods into the BMI method. This is what the code looks like:
public class BMIProj {
static Scanner input = new Scanner(System.in);
public static int heightInInches()
{
System.out.println("Input feet: ");
int x;
x = input.nextInt();
System.out.println("Input Inches: ");
int y;
y = input.nextInt();
int height = x * 12 + y;
return height;
}
public static int weightInPounds()
{
System.out.println("Input stone: ");
int x;
x = input.nextInt();
System.out.println("Input pounds ");
int y;
y = input.nextInt();
int weight = x * 14 + y;
return weight;
}
public static void outputBMI()
{
}
public static void main(String[] args) {
heightInInches();
weightInPounds();
outputBMI();
}
Thanks in advance.
I advise you to do a little bit more learning in java, specifically variables, declaring, initializing, etc.. Also learn class, constructors, etc..
You need fields for the class to save the inputed variables
I created a constructor to initialize the variables
You don't need to return anything in the methods if all you are doing is assigning values to your class fields and outputting info.
I did the curtsy of calculating the bmi for you
Anyway
public class BMIProj {
static Scanner input = new Scanner(System.in);
// Class vars
int height;
int weight;
double bmi;
//Constructor
public BMIPrj(){
//Initialize vars
height = 0;
weight = 0;
bmi = 0;
}
public static void heightInInches()
{
System.out.println("Input feet: ");
int x;
x = input.nextInt();
System.out.println("Input Inches: ");
int y;
y = input.nextInt();
int height = x * 12 + y;
return height;
}
public static void weightInPounds()
{
System.out.println("Input stone: ");
int x;
x = input.nextInt();
System.out.println("Input pounds ");
int y;
y = input.nextInt();
int weight = x * 14 + y;
return weight;
}
public static void outputBMI()
{
System.out.println("BMI: " + (( weight / height ) x 703));
}
public static void main(String[] args) {
heightInInches();
weightInPounds();
outputBMI();
}
You can assign the output of a method to a parameter like so:
int weight = weightInPounds();
When calling a method, you can pass in parameters:
outputBMI(weight);
The rest is up to you.

How to fix these issues?

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.

Categories

Resources