I understand that this may be a simple question with a simple answer but for some reason it is beyond me. My class is working in BlueJ right now and we are plotting points on a graph that we are creating with squares, right now I need to make the following prompt loop until a certain condition (x=-1) continue for as many inputs as the user sees fit.
public void plotPoints(Scanner keyboard)
{
System.out.print("Enter an x and y coordinate: ");
//Read x from user
int x = keyboard.nextInt();
//Read y from user
int y = keyboard.nextInt();
//Plot the point
new Circle(x,y);
}
it is recommended that we use a while loop for this.
This code does the work.
public class PlotPoints {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
PlotPoints pp = new PlotPoints();
pp.plotPoints(sc);
}
public void plotPoints(Scanner keyboard)
{
int x=1;
while (x != -1) {
System.out.print("Enter an x and y coordinate: ");
//Read x from user
x = keyboard.nextInt();
//Read y from user
int y = keyboard.nextInt();
//Plot the point
new Circle(x, y);
}
}
}
You can use an infinite while or for loop with a break condition as below:
public List<Circle> plotPoints(Scanner keyboard){
List<Circle> arrList = new ArrayList<>();
while(true){ // for(;;) {
System.out.println("Enter an x and y coordinate: ");
System.out.println("Enter value for x: (x=-1 to exit)");
//Read x from user
int x = keyboard.nextInt();
System.out.println("x =" + x);
if(x == -1){
System.out.println("Good bye!");
break;
}
//Read y from user
System.out.println("Enter value for y: ");
int y = keyboard.nextInt();
System.out.println("y = " + y);
System.out.println("Plotting point (" + x + "," + y + ")");
//Plot the point
arrList.add(new Circle(x,y));
}
return arrList;
}
The code above gives the logic to get as many parameters as the user wishes to input. The method is suppose to return a collection of the plotted points so the array list arrList is there to collect all the plotted point. At first I thought you were trying to draw circles but that is not possible as you are not getting the value for the radius.
Related
I have the code below:
package Main; import java.util.*;
public class Generator {
List <List<String>>masterList = new ArrayList<List<String>>();
ArrayList memberList = new ArrayList<String>();
String leaderName, memberName;
int numLeaders, numMembers;
double x;
Scanner scanner = new Scanner(System.in);
// This program takes in total number of people first
// Then takes in number of leaders to assign peoples to
// Then takes in people to be assigned
// And then assigns people to given leaders randomly
public int getNumLeader() {
System.out.println("How many leaders are there??");
numLeaders = scanner.nextInt();
return numLeaders;
}
public void setNumLeader(int numLeaders) {
this.numLeaders = numLeaders;
}
public int getNumMembers() {
System.out.println("How many members are there?");
numMembers = scanner.nextInt();
return numMembers;
}
public void setNumMembers(int numMembers) {
this.numMembers = numMembers;
}
public void genLeaders() {
System.out.println("Please type the name of the leader on the following:");
for (int i = 1; i <= numLeaders; i++) {
if (i == numLeaders) {
System.out.println("What is the last leader's name?");
leaderName = scanner.next();
List <String> leaderList = new ArrayList<String>();
masterList.add(leaderList);
} else {
System.out.println("What is the leader" + i + "'s name?");
leaderName = scanner.next();
List <String> leaderList = new ArrayList<String>();
masterList.add(leaderList);
}
}
}
public void genMembers() {
System.out.println("Please enter the members on the following:");
for (int i = 1; i <= numMembers; i++) {
if (i == numMembers) {
System.out.println("What is the last member's name?");
memberName = scanner.next();
memberList.add(memberName);
} else {
System.out.println("What is the member" + i + "'s name?");
memberName = scanner.next();
memberList.add(memberName);
}
}
}
public void /*should return arraylist*/ brackets() {
double y = 1.0/numLeaders;
for (double j = 0.0; j <= 1.0; y++) {
//Generate Linked list with initial element of 0.0
//then 0.0 + y, then 0.0 + y + y ... till 1.0
}
}
public void assignMembers() {
System.out.println("Shuffling members..");
Collections.shuffle(memberList);
System.out.println("Assigning members to leaders now..");
int cellSize = memberList.size()/numLeaders;
for (int i = 0; i <= memberList.size(); i++) {
double x = Math.random();
double y = 1.0/numLeaders;
if (x <= y) {
masterList.get(0).add((String) memberList.get(i));
}
else if (y < x && x <= y + y) {
masterList.get(1).add((String) memberList.get(i));
}
else if (y < x && y + y < x && x <= y + y + y) {
masterList.get(2).add((String) memberList.get(i));
}
// assign given element's name from the big linkedList to the first leader's
// arrayList
}
}
public static void main(String[] args) {
Generator x = new Generator();
x.getNumLeader();
x.getNumMembers();
x.genLeaders();
x.genMembers();
System.out.println(x.memberList);
System.out.println(x.masterList);
System.out.println(x.masterList.get(0));
System.out.println(x.masterList.get(1));
System.out.println(x.masterList.get(2));
}
}
And I made lists within an arraylist, called masterList. I try to assign people in a list within that arraylist, in this manner: masterList.get(0).add((String) memberList.get(i)); Nothing's being added to the list within the arrayList.. what would be the 'correct' way to do this, and is there a way to pinpoint the list within the arraylist, other than 'masterList.get(0)'? Thanks in advance.
You are calling 4 methods, 2 to get numbers of leader and member, and another 2 to generate them. In your generateLeader method, you read name from console but never used it within this method. You are just adding emptylist to master list in this method. The other method generateMembers looks fine as you are adding this in the expected list. I dont see anywhere else that main method calls to populate the emptylist inside the masterlist you added in generateLeaders method.
Also, use nextln to read input, there are scenarios where the linebreak character will still be in buffer when you use just "next" and that linebreak will be read read as next input.
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.");
}
}
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
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);
}
}
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'.