Adding a 'While' Loop To My Program [duplicate] - java

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

Related

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

how to enable my code to skip over certain code when the input by the user is a specific option

Hi I was wondering if someone could help me make it so when I choose an option in my code when the program runs, it skips all the other options that weren't chosen and only uses the code inputted by the user. So only the specific parts in the code should be printed but I don't know how to skip over code. There is probably things I should remove and then things I should add but I need help.
package test;
import java.util.Scanner;
import java.text.NumberFormat;
public class Test
{
static Scanner input = new Scanner( System.in );
public static void main(String[] args)
{
//Variables
String Option;
int a;
int Base;
int Height;
int Length;
int Width;
int Radius;
int r;
int b;
double Area;
//Menu
System.out.println("Welcome to the Area Calculator");
System.out.println("");
System.out.println("1. Square");
System.out.println("2. Rectangle");
System.out.println("3. Circle");
System.out.println("4. Triangle");
System.out.println("5. Quit");
System.out.println("Please enter the number of the shape you would like to calculate the area for.");
Option=input.next();
}
public static void Sqaure(String[] args)
{
System.out.println("Please enter the length of one side.");
int a=input.nextInt();
System.out.println("Please enter the length of one side.");
double area = a*a;
System.out.println("The area of the given shape is " + area + " square units.");
}
public static void Rectangle(String[] args)
{
System.out.println("Please enter the length.");
int Length=input.nextInt();
System.out.println("Please enter the width.");
int Width=input.nextInt();
double area = Length*Width;
System.out.println("The area of the given shape is " + area + " square units.");
}
public static void Circle(String[] args)
{
System.out.println("Please enter the radius.");
int r=input.nextInt();
double Radius = r*r;
double area = Math.PI * Radius;
System.out.println("The area of the given shape is " + area + " square units.");
}
{
System.out.println("Please enter the base length.");
int b=input.nextInt();
double Base = b * .5;
System.out.println("Please enter the height lenth.");
int Height=input.nextInt();
double area = Base * Height;
System.out.println("The area of the given shape is " + area + " square units.");
}
}
So, it is clear to me you're very new with Java and you're learning! So I went ahead and made a complete working version of what you are trying to do.
Although it is a simple program Ill go through what each section does.
Prompt Method
Asks the user which area they want to find, this method has the direct answer to your question in the form of a series of if/if else statements. It gets the input from the user and then goes through the series of if/if else statements, seeing if the value entered matches any of them, if it does then it runs that section of code and skips the rest. If a number other then 1-4 is entered, it quits the program (see the else statement), see this page for more info on if statements. I opted for a bunch of if statements but there is a better, cleaner way, but it is a little confusing if you are brand new, see here to learn about those.
Area Methods
These are all pretty much the same except for he way they calculate the areas. They first prompt the user for the required measurements for that shape and assign those entered values to variables, then it prints out the resulting area after running the values through a calculation, then the program stops.
Main Method
All the main method is doing is calling prompt, that keeps it clean, you don't really ever want to do anything but call other methods or create objects in the main method, so most people put the nitty gritty somewhere else and call it.
Below is the working code
Go ahead and paste into a doc and run it, just be aware that I did not bother to add any error catching to keep it simple so keep it to whole numbers without decimals (also called ints, eg. 1, 2, 4, not 4.3, 5.4, etc.)
Side note:
In your methods you have (String args[]) in the brackets, this is not needed, in fact it will cause trouble, that is only used in the main method and is a relatively advanced way of providing input to the program, for now you can keep to leaving the brackets empty.
import java.util.*;
public class Area
{
public static void main(String args[])
{
prompt(); //Calls prompt method
}
//Prompt Method
public static void prompt()
{
int option;
Scanner input = new Scanner(System.in);
//Ask the user which shape they want to find the area of
System.out.println("Select from the following shapes to calulate the area:");
System.out.println("Rectangle -- 1\nCircle -- 2\nTriangle -- 3\nQuit -- 4\n");
System.out.print("Your option: ");
option = input.nextInt();
System.out.println();
//THIS IS THE PART THAT DIRECTLY PERTAINS TO YOUR QUESTION
if(option == 1)
{
rectangle();
}
else if(option == 2)
{
circle();
}
else if(option == 3)
{
triangle();
}
else
{
System.out.println("Program stopped by user"); //For stopping the program when they want to quit instead
System.exit(0);
}
}
//Rectangle Method
public static void rectangle()
{
double h;
double b;
Scanner input = new Scanner(System.in);
System.out.println("RECTANGLE");
System.out.print("Enter Height: ");
h = input.nextDouble();
System.out.print("Enter Base: ");
b = input.nextDouble();
System.out.print("\nArea of Rectangle = " + (h*b) + "\n");
}
//Circle Method
public static void circle()
{
double pi = 3.14;
double radius;
Scanner input = new Scanner(System.in);
System.out.println("CIRCLE");
System.out.print("Enter radius: ");
radius = input.nextDouble();
System.out.print("\nArea of Circle = " + (pi*(radius*radius)) + "\n");
}
//Triangle Method
public static void triangle()
{
double h;
double b;
Scanner input = new Scanner(System.in);
System.out.println("TRIANGLE");
System.out.print("Enter Height: ");
h = input.nextDouble();
System.out.print("Enter Base: ");
b = input.nextDouble();
System.out.print("\nArea of Triangle = " + ((h*b)/2) + "\n");
}
}
package test;
import java.util.Scanner;
import java.text.NumberFormat;
public class Test
{
static Scanner input = new Scanner( System.in );
public static void main(String[] args)
{
//Variables
String Option;
int a;
int Base;
int Height;
int Length;
int Width;
int Radius;
int r;
int b;
double Area;
String [] inputString = new String [50];
//Menu
System.out.println("Welcome to the Area Calculator");
System.out.println("");
System.out.println("1. Square");
System.out.println("2. Rectangle");
System.out.println("3. Circle");
System.out.println("4. Triangle");
System.out.println("5. Quit");
System.out.println("Please enter the number of the shape you would like to calculate the area for.");
Option=input.next();
switch (Option) {
case "1": Sqaure(inputString);
break;
case "2": Rectangle(inputString);
break;
case "3": Circle(inputString);
break;
default: someExtraFig(inputString);
break;
}
}
public static void Sqaure(String[] args)
{
System.out.println("Please enter the length of one side.");
int a=input.nextInt();
System.out.println("Please enter the length of one side.");
double area = a*a;
System.out.println("The area of the given shape is " + area + " square units.");
}
public static void Rectangle(String[] args)
{
System.out.println("Please enter the length.");
int Length=input.nextInt();
System.out.println("Please enter the width.");
int Width=input.nextInt();
double area = Length*Width;
System.out.println("The area of the given shape is " + area + " square units.");
}
public static void Circle(String[] args)
{
System.out.println("Please enter the radius.");
int r=input.nextInt();
double Radius = r*r;
double area = Math.PI * Radius;
System.out.println("The area of the given shape is " + area + " square units.");
}
public static void someExtraFig(String ...s)
{
System.out.println("Please enter the base length.");
int b=input.nextInt();
double Base = b * .5;
System.out.println("Please enter the height lenth.");
int Height=input.nextInt();
double area = Base * Height;
System.out.println("The area of the given shape is " + area + " square units.");
}
}

Compile error in my do/while statements?

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.

Multiple inputs from the same line in java

I am in need of assistance with my Java program assignment. The assignment is to calculate the distance between two points using java. I completed part one as followed:
import java.util.Scanner;
public class DistanceCalcEasy
{
public static void main(String[] args)
{
// Creating a new scanner object
System.out.println("Distance Calculator");
Scanner input = new Scanner(System.in);
// Getting all of the coordinates
System.out.print("Enter the X coordinate of the first point: ");
double x1 = input.nextDouble();
System.out.print("Enter the Y coordinate of the first point: ");
double y1 = input.nextDouble();
System.out.print("Enter the X coordinate of the second point: ");
double x2 = input.nextDouble();
System.out.print("Enter the Y coordinate of the second point: ");
double y2 = input.nextDouble();
// Calculating the distance between the points
double distance = Math.sqrt( Math.pow((x2-x1),2) + Math.pow((y2-y1),2) );
// Printing the distance to the User
System.out.println("The distance between the points is " + distance);
}
}
Now the problem is I need to do this same program again but the "hard way" by allowing the user to input a coordinate like 1,2 instead of each x and y on their own line. This is what I have started to come up with after a little bit of research:
import java.util.Scanner;
public class DistanceCalcHard
{
public static void main(String[] args)
{
// Creating a new Scanner Object
System.out.println("Distance Calculator");
Scanner input = new Scanner(System.in);
// Getting the data points
System.out.print("Enter the first point x,y: ");
String firstPoint = input.nextLine();
System.out.print("Enter the second point x,y: ");
String secondPoint = input.nextLine();
Scanner scan = new Scanner(firstPoint).useDelimiter("\\s*,\\s*");
while (scan.hasNextDouble() )
{
}
// Calculating the distance
// Displaying the distance to the user
}
}
Does that seem like a good start? I was thinking I could make two array's, one for each point, and then do my distance calculation that way. Is there a simpler way to do this or can someone point me in a better direction? Thank You
An easier way to go about splitting the string into two values (ie. x,y -> x and y) would be by using the split() operator for a String object.
String[] pointA = firstPoint.split(",");
And the same can be done for the second point. Now you have your two points in arrays where pointA[0] is the x value and pointA[1] is the y value.
More documentation about the method can be found here
How about something like this:
import java.util.Scanner;
public class DistanceCalcEasy
{
public static void main(String[] args)
{
// Creating a new scanner object
System.out.println("Distance Calculator");
Scanner input = new Scanner(System.in);
// Getting all of the coordinates
System.out.print("Enter the X,Y coordinate of the first point: ");
String xy1in = input.nextLine();
System.out.print("Enter the X,Y coordinate of the second point: ");
String xy2in = input.nextLine();
String[] xy1 = xy1in.split(",");
String[] xy2 = xy2in.split(",");
double x1 = Double.parseDouble(xy1[0]);
double y1 = Double.parseDouble(xy1[1]);
double x2 = Double.parseDouble(xy2[0]);
double y2 = Double.parseDouble(xy2[1]);
// Calculating the distance between the points
double distance = Math.sqrt( Math.pow((x2-x1),2) + Math.pow((y2-y1),2) );
// Printing the distance to the User
System.out.println("The distance between the points is " + distance);
}
}

OOP advice - should I change how my program runs?

below I have a small program i wrote for working out the area of shapes....
My question is this the right way to do it, a friend did similar and had multiple shapes which inherited from main shape. OOP? is mine ok as i will only ask the area of a shape and no more? and how would i change this to make it more OO?
Main Prog /////
package areaprog;
import java.util.Scanner;
import java.util.InputMismatchException;
public class Mainprog {
public static void main (String [] args){
//Area Menu Selection
System.out.println("What shape do you need to know the area of?\n" +
"1: Square?\n" +
"2: Rectangle?\n" +
"3: Triangle?\n" +
"4: Circle? \n" +
"5: Exit\n"
);
//User input for menu
Scanner reader = new Scanner(System.in);
System.out.println("Number: ");
//Menu syntax checking
while (!reader.hasNextDouble())
{
System.out.println("Thats not a number you tool.\n");
System.out.println("Now pick again\n" +
"1: Square?\n" +
"2: Rectangle?\n" +
"3: Triangle?\n" +
"4: Circle? \n" +
"5: Exit\n"
);
reader.next(); //ask for next token
}
double input = reader.nextDouble();
reader.nextLine();
//Depending on user selection, depends on what method is called using switch.
Scanner scan = new Scanner(System.in);
//Square selection and InputMismatch Exception
try {
if (input == 1){
System.out.println("What is a length of 1 side of the Square?\n");
double s1 = scan.nextDouble();
double SqAns = AreaCalculator.getSquareArea(s1);
System.out.println("The area of you square is: " + SqAns);
}
}
catch (InputMismatchException e)
{
System.out.println("Why are you trying to be clever? use an interger");
}
//Rectangle selection
if (input == 2){
System.out.println("What is the width of your rectangle?.\n");
double r1 = scan.nextDouble();
System.out.println("What is the height of your rectangle?\n");
double r2 = scan.nextDouble();
double RecAns = AreaCalculator.getRectArea(r1, r2);
System.out.println("The area of your rectangle is: " + RecAns);
}
//Triangle selection
if (input == 3){
System.out.println("What is the base length of the triangle?.");
double t1 = scan.nextDouble();
System.out.println("What is the height of your triangle?");
double t2 = scan.nextDouble();
double TriAns = AreaCalculator.getTriArea(t1, t2);
System.out.println("The area of your triangle is " + TriAns);
}
//Circle selection
if (input == 4){
System.out.println("What is the radius of your circle?.");
double c1 = scan.nextDouble();
double CircAns = AreaCalculator.getCircleArea(c1);
System.out.println("The area of your circle is " + CircAns);
}
//Exit application
if (input == 5){
System.out.println("Goodbye.");
}
}
}
AreaCalculator.java ////
package areaprog;
public class AreaCalculator {
public static double getRectArea(double width, double height) {
double aValue = width * height;
return aValue;
}
public static double getCircleArea(double radius){
double PI = Math.PI;
double aValue = PI * Math.pow(radius, 2);
return aValue;
}
public static double getSquareArea(double side) {
double aValue = Math.pow(side, 2);
return aValue;
}
public static double getTriArea(double base , double height) {
double aValue = (base/2)* height;
return aValue;
}
}
Having multiple classes inheriting from a single base class or interface is definitely a better design here. Use classes to encapsulate given functionality or objects(in that case triangle, square etc. Also when you have multiple classes sharing some functionality better extract it as a common interface to achieve better level of abstraction.
The simple answer is to use an interface of 'shape' like this
interface Shape {
double[] dimensions;
double calcArea();
}
And have all your shapes implement this interface.
say
class Circle implements Shape {
...
}
and implement different calcArea() methods for each shape
In your runner, you init a Circle, box, etc...
When you need area, you don't have to care about which shape is actually behind it, just call the method shape.calcArea() and it will find the right one.

Categories

Resources