Compile error in my do/while statements? - java

I created 3 classes Circle, Rectangle, and RightTriangle using my FigureGeometry interface. This program is supposed to take input run calculation using the different classes.
I'm getting a couple of errors with my do/while statement. The do statement says "Illegal start of type". My while statement say the same and "can't find variable option".
I've tried searching for other questions on here/google, but I can't find anything that has helped with my code. It is always something like an extra bracket but as far as I can tell there isn't anything extra here.
I've double checked that all my open/close brackets match up. I've tried having my option variable in the do statement (which I was certain wasn't correct, but I was just trying some different things). I'm just not sure what the issue is?
package figuregeometry;
import java.util.Scanner;
public class FigGeometryCalculator
{
//========================MAIN==============================================
public static void main(String[] args)
{
float height;
float width;
float length;
float radius;
float degrees;
String menu = "Would you like to figure the geometry for a: " + "\n"
+ "1. Circle" + "\n"
+ "2. Rectangle" + "\n"
+ "3. Right Triangle" + "\n"
+ "0. Exit";
do
{
Scanner in = new Scanner(System.in);
int option = in.nextInt();
switch(option)
{
case 1: System.out.println("Enter radius: ");
radius = in.nextFloat();
System.out.println("Enter Degrees of sector: ");
degrees = in.nextFloat();
Circle newCircle = new Circle(radius, degrees);
System.out.println("Set Scale: ");
newCircle.setScale(in.nextInt());
newCircle.toString();
break;
case 2: System.out.println("Enter length: ");
length = in.nextFloat();
System.out.println("Enter width: ");
width = in.nextFloat();
Rectangle newRectangle = new Rectangle(length, width);
System.out.println("Set Scale: ");
newRectangle.setScale(in.nextInt());
newRectangle.toString();
break;
case 3: System.out.println("Enter Length: ");
length = in.nextFloat();
System.out.println("Enter Height: ");
height = in.nextFloat();
RightTriangle newTriangle = new RightTriangle(length, width);
System.out.println("Set Scale: ");
newTriangle.setScale(in.nextInt());
newTriangle.toString();
break;
case 0:
System.out.println("Exit");
break;
default: System.out.println("Not an a valid option. Please try again.");
}
}while(option != 0);
}
}

Problems:
Remove all invalid modifiers. That is, change:
public float height;
public float width;
public float length;
public float radius;
public float degrees;
To:
float height;
float width;
float length;
float radius;
float degrees;
Maybe not a direct answer to your question but you need to put your input received option = in.nextInt(); inside the loop. Otherwise you will end up with an infinite loop.
For example, if the user chooses '1', option becomes 1 and is never updated inside the loop so your loop will run forever.
EDIT:
Just to clarify since I see you didn't understand.
You don't put int option = in.nextInt(); inside the loop, you put everything but the int. (so option = in.nextInt(); inside the loop). You say int option; outside the loop.
So:
int option; // created outside the loop
do {
System.out.print(menu);
option = in.nextInt(); // used inside the loop
switch(option)
{
// CASES AND CODE
}
} while(option != 0);
That is why you are getting an error because your variable option isn't visible to the while loop so the loop cannot compare something with 0 if it cannot find it.
In general, try not to create anything inside loops, and create outside of them to prevent unnecessary object creation. Another example, your Scanner object should be created outside of your loop.
Put the statement Scanner in = new Scanner(System.in); outside the loop then use it with option = in.nextInt(); the way I described above.

Related

Trying to create a menu in java to calculate and display information about a circle

I'm pretty new to java and I've been working through some questions and have been mostly okay but I've had a lot of trouble with this question which asks me to create a menu to find out and display various information about a circle. My code is as follows:
import java.util.Scanner;
public class Circle2 {
public static void main(String[] args) {
final double pi = 3.1416;
Scanner values = new Scanner(System.in);
char response;
double area, perimeter, radius;
do // put code in loop
{
// offer menu of options
System.out.println();
System.out.println("*** CIRCLE MENU ***"); // create a blank line
System.out.println("[1] Set radius");
System.out.println("[2] Display radius");
System.out.println("[3] Display area");
System.out.println("[4] Display perimeter");
System.out.println("[5] Quit");
System.out.println("Enter choice [1,2,3,4,5}: ");
response = values.next().charAt(0); // get response
System.out.println(); // create a blank line
switch(response) // process response
{
case '1': System.out.println("Enter a value for the radius: ");
radius = values.nextDouble();
while(radius < 0)
{
System.out.println("Please enter a non-negative radius: ");
radius = values.nextDouble();
}
break;
case '2': System.out.println("The radius is " + radius);
break;
case '3': System.out.println("The area is " + (pi * radius * radius));
break;
case '4': System.out.println("The perimeter is " + (2 * pi * radius));
break;
case '5': System.out.println("Goodbye!");
break;
default: System.out.println("Options 1-5 only!");
}
} while (response != '5'); // test for Quit option
}
}
The errors I keep getting are in the switch case, I've tried putting the first case into an if statement and other approaches but nothing is working. I'm trying to allow the user to input the radius in case 1 and then I wanted to use that value in the rest of the cases but it won't work at all. This could be me making a very stupid mistake but any help is appreciated, and sorry if I've done this post wrong this was my last resort because I've been stuck for hours.
I pasted your code into Eclipse.
The only thing that was not working was that
the following variables needed to be initialized:
double area, perimeter, radius = 0;
If you are getting this error :
error: variable radius might not have been initialized
case '2': System.out.println("The radius is " + radius);
Then this is because you are printing the radius value before initializing it, so you need to give a default value before printing it.

how to store a calculation from an input to memory, input repeats, first calculation from input is added to second calculation from input and so on?

I need some help with a program I'm trying to make using Java.
I'm currently a freshman in Information Technology and for finals, we have to do an electrical billing program of some sort I've already done some code but it won't work the way I want it to. Can anyone help me fix it?
flow of program:
1)user inputs multiple numbers to be calculated
2)program calculates it
3)the result of the calculation from step 2 is stored somewhere
4)program asks user if they want to input again
5)if user chooses input again the process repeats from step 1 to 2 and is added to the first calculation and so on and so forth
static Scanner console = new Scanner (System.in);
Double loopFor=0.0;
Double w,h,kwh,t;
System.out.print("\nHello and welcome to Pikabill. The electricity bill estimate calculator.");
while(true) {
do {
System.out.print("\nEnter what is being asked. You might have to refer to labels on your appliances");
System.out.print("\nWATTAGE (W): ");
w=console.nextDouble();
System.out.print("\nUSAGE (in HOURS): ");
h=console.nextDouble();
System.out.print("\nELECTRICITY RATE (kWh): ");
kwh=console.nextDouble();
t=(w*h)/1000*kwh;
System.out.print("\nCOST: " + t);
loopFor += t;
System.out.print("\nWould you like to continue? YES [y] No [n]");
String c= console.nextLine();
if(c.equalsIgnoreCase("n")){
break;
}
}
while (loopFor !=0);
}
}
}
somehow, when I run this the calculation works fine, but when it comes to displaying the t (the calculation), it shows the "do you want to continue" just fine but the "Hello and welcome to Pikabill...." shows on the next line even though i havent pressed y. It also doesn't add the previous calculations to the newer ones as well.
This piece of code will work.
import java.util.Scanner;
public class ElectricalBillingProgram
{
public static void main(String[] args)
{
Scanner console = new Scanner(System.in);
Double loopFor = 0.0;
Double w, h, kwh, t;
for (int i = 0;; i++)
{
System.out.print("\nEnter what is being asked. You might have to refer to labels on your appliances");
System.out.print("\nWATTAGE (W): ");
w = console.nextDouble();
System.out.print("\nUSAGE (in HOURS): ");
h = console.nextDouble();
System.out.print("\nELECTRICITY RATE (kWh): ");
kwh = console.nextDouble();
t = (w * h) / 1000 * kwh;
System.out.print("\nCOST: " + t);
loopFor += t;
System.out.print("\nWould you like to continue? YES [y] No [n]");
String c = console.next();
if (c.equalsIgnoreCase("n"))
{
break;
}
}
}
}
Observations from your code:
Never mixup "while" and "doWhile", if it confuses you, use "for" loop.
use console.next() instead of console.nextLine().
Happy learning!
This should be your code -
Scanner console = new Scanner(System.in);
Double loopFor = 0.0;
Double w, h, kwh, t;
System.out.println("Hello and welcome to Pikabill. The electricity bill estimate calculator.");
while (true) {
System.out.println("Enter what is being asked. You might have to refer to labels on your appliances");
System.out.println("WATTAGE (W): ");
w = console.nextDouble();
System.out.println("USAGE (in HOURS): ");
h = console.nextDouble();
System.out.println("ELECTRICITY RATE (kWh): ");
kwh = console.nextDouble();
t = (w * h) / 1000 * kwh;
loopFor += t;
System.out.println("COST:\t" + t);
System.out.println("loopFor:\t" + loopFor);
System.out.println("Would you like to continue? YES [y] No [n]");
String c = console.next();
if (c.equals("n")) {
break;
}
}

Why doesn't the code work? [duplicate]

This question already has answers here:
What's the difference between next() and nextLine() methods from Scanner class?
(15 answers)
Closed 5 years ago.
import java.util.Scanner;
public class Formula {
public static void main(String[] args) {
Scanner numIn = new Scanner(System.in);
Scanner form = new Scanner(System.in);
double r, d, h, a;
String formula;
System.out.println("Please state which circle formula you want to use:");
System.out.println("Circumference");
System.out.println("Area");
System.out.println("Cylinder volume");
formula = form.next();
switch (formula) {
case "Circumference":
System.out.println("Please state the diameter: ");
d = numIn.nextDouble();
System.out.println("The circumference is:");
System.out.println(3.14 * d);
break;
case "Area":
System.out.println("Please state the radius: ");
r = numIn.nextDouble();
System.out.println("The area is:");
System.out.println(3.14 * (r * r));
break;
case "Cylinder volume":
System.out.println("State the area of the base: ");
a = numIn.nextDouble();
System.out.println("State the height of the cylinder: ");
h = numIn.nextDouble();
System.out.println("the volume is: ");
System.out.println(a * h);
break;
default:
System.out.println("Option not recognized");
break;
}
}
}
as you can see I am trying to create a formula calculator (note: I am only a begginer) and it all seemed to be working until the last 'case'. The last case "Cylinder volume" is not recognized when I type it in the console. All other cases work fine, and I do not see a difference between "Cylinder volume" and the other ones. Please help!
That is you used
formula = form.next();
This only reads until end of the word but not the space
so when you put "Cylinder volume" it reads Cylinder only.
It will work if you change it to
formula = form.nextLine();
Zircon has the solution. However, it may also be helpful to print in the default case what formula is set to:
default:
System.out.println("Option: " + formula + " not recognized");
break;
Doing this kind of stuff will help your sanity in the future.
Try
Scanner form = new Scanner(System.in, "UTF-8").useDelimiter("\n");
Remember that Scanner doesn't work with non-ascii character.
Another test could be printing 'formula' before the switch, and check its content.

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 to make Exception handling Loop (Unlimited amount of times)

Responses to previous question , my initial answer to that question had been solved, but I had another problem when it came down to looping which was later solved by simply using a for loop.
However, my problem is I do not want the user to constantly have to restart the program after an exception is handled, rather I want it to loop the same beginning questions to the user. I've tried placing print statements after the return statements, and also tried completely copying the logic code after the try catch, however, realizing that that would not cause the user to loop unlimited times for the exception. Also, on a side note yes my previous question had good answers, however, no one managed to answer my more recurring problem, which is why no one got the check mark towards their answer.
import java.io.*;
import java.text.DecimalFormat;
public class Test
{
public static void main(String[] args) throws IOException
{
double x;
x = circlemethods(0.0, 0.0, 0.0, 1.0);
}
public static double circlemethods(double volume, double surfacearea,
double area, double radius) throws IOException
{
BufferedReader myInput = new BufferedReader(new InputStreamReader(System.in));
String numInput;
String reqInput;
String amountStr;
double numInt = 0;
double num = 0;
double answer = 0;
double amount = 0;
double answer2 = 0;
double answer3 = 0;
double answer4 = 0;
for (double i = 0; i < 999; i++)
;
try
{
// for (double i = 0; i < 999; i++);
// while (numInt != 999) {
System.out.println("This program will ask for a given user radius, then proceed to calculate the user input");
System.out.println("The program will use four methods to achieve this, all calling back to the main method");
System.out.println("Press any key to continue");
numInput = myInput.readLine();
System.out.println("First, what would you like to calculate?");
System.out.println("Enter '1' for Circumference, '2' for area, '3' for volume, or '4' for surface area");
reqInput = myInput.readLine();
numInt = Double.parseDouble(reqInput);
System.out.println("Now enter the radius of the required shape(Half of diameter)");
numInput = myInput.readLine();
num = Double.parseDouble(numInput);
DecimalFormat nextAmount = new DecimalFormat("0.00");
amountStr = nextAmount.format(amount);
if (numInt == 1)
{
System.out.println("You chose to calculate circumference, given the radius :" + num);
answer = (3.14) * (2) * (num);
System.out.print("The circumference of that sphere is :");
System.out.println(answer + "cm³");
return answer;
}
else if (numInt == 2)
{
System.out.println("You chose to calculate area, given the radius :" + num);
answer2 = (3.14) * 2;
System.out.print("The area of the circle is :");
System.out.println(answer2 + "cm²");
return answer2;
}
else if (numInt == 3)
{
System.out.println("You chose to calculate volume, given the radius :" + num);
answer3 = 4 / 3 * (3.14) * (num) * (3) * (3) * (3);
System.out.print("The volume of that sphere is : cm³");
System.out.println(answer3 + "cm³");
return answer3;
}
else
// if (numInt == 4)
{
System.out.println("You chose to calculate surface area, given the radius :" + num);
answer4 = 4 * (3.14) * (num) * (2) * (2);
System.out.print("The Surface area of that sphere is :");
System.out.println(answer4 + "cm²");
return answer4;
}
} catch (Exception e)
{
System.out.println("Please do not enter any string values, next time input enter a number ");
return 0;
// how to loop this untill the user inputs a number????
}
}
}
First, you use a while(true) loop instead of looping for 999 times. (That loop doesn't actually do anything considering there is a semicolon right after it.)
Then, you remove the return 0; from your catch block.
So it would be
while(true) {
try {
.... //your code
}
catch {...}
} //while loop end bracket
This way, the loop will only end if it reaches one of your return statements.
You need to loop until you get a valid value. One way to do that is loop until a boolean value is set to true. Try something similar to this:
boolean inputIsValid = false;
while (!inputIsValid) { ...
Then when you have determined you have a valid input, add the line:
inputIsValid = true;
Your loop will continue until inputIsValid becomes true.
You could also create an endless while loop. Then when you receive a valid input, break out of the loop:
while(true) {
//when valid input is received
break;
}

Categories

Resources