Multiple inputs from the same line in java - 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);
}
}

Related

Comparing return values from two overloaded methods in an if statement (in main method)

So i'm new to java, we just started this language in my programming class about a month ago. Anyhow, we're on overloading methods right now (just started methods last week) and I'm having trouble with comparing the values of the return statements in the overloaded methods. My intention is to compare them in an if statement in the main method. I'm sure the answer is simple, but i can't find information on it in my textbook or online. Sorry about the sloppy indentation, I'm having trouble with the features on this website and it's the first time i've used it. would appreciate any help! Here is the program:
import java.util.Scanner;
public class pizzaCalculation {
public static void main(String[] args){
//create scanner
Scanner i = new Scanner(System.in);
//create sentinel while loop, initiate priceperinch for both pizzas
int sentinel = 1;
//create while loop
while(sentinel != 0){
//create input for round pizza
System.out.println("What is the price of the round pizza?");
double priceRound = i.nextDouble();
System.out.println("What is the radius?");
double radius = i.nextDouble();
pizzaPrice(radius, priceRound);
System.out.println("What is the price of the rectangular pizza?");
double priceRect = i.nextDouble();
System.out.println("What is the width and length of the rectangular pizza?");
double width = i.nextDouble();
double length = i.nextDouble();
pizzaPrice();
//create if statement to determine best deal
if (pricePerInchRound > pricePerInchRect){
System.out.println("The best deal is the round pizza which is $"+pricePerInchRound);
}else{
System.out.println("The best deal is the rectangular pizza is $"+pricePerInchRect);
}
//ask if user would like to do again
System.out.println("Would you like to do another calculation? Enter 1 for yes and 0 for no.");
sentinel = i.nextInt();
}
}
public static double pizzaPrice(double num1, double priceRound){
Scanner i = new Scanner(System.in);
//this is for round pizza
double areaRound = Math.PI * num1 * num1;
double pricePerInchRound = priceRound / areaRound;
return pricePerInchRound;
}
public static double pizzaPrice(double num1, double num2, double priceRect){
//this is for rectangular pizza
//create scanner
Scanner i = new Scanner(System.in);
double areaRect = num1 * num2;
double pricePerInchRect = priceRect / areaRect;
return pricePerInchRect;
}
}
So there are several issues:
You need to pass parameters to the second call of pizzaPrice() like this
pizzaPrice(width, length, priceRect);
You need to store results of method calls in variables like
pricePerInchRound = pizzaPrice(a, b);
pricePerInchRect = pizzaPrice(a, b, c);
You are calling pizzaPrice() but you need to store the resulting value in a variable so you can use it later (and pass the right parameters).
double pricePerInchRound = pizzaPrice(radius, priceRound);
and ...
double pricePerInchRect = pizzaPrice(width, length, priceRect);
Also, take care to name your method parameters better - num1, num2 aren't very descriptive. You could have used width, length.

While loop for multiple inputs

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.

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

Cant seem to get my scanner working

import java.util.*;
import java.util.Scanner;
import java.io.*;
class Point
{
/* Method to find the quadrant of both the points p and q*/
public String quadrant(double xp, double yp, double xq, double yq){
Scanner keyboard= new Scanner(System.in);
System.out.print("Enter the first value for Xp: ");
xp = keyboard.nextDouble();
Scanner keyboard1 = new Scanner(System.in);
System.out.print("Enter the first value for Yp: ");
yp = keyboard.nextDouble();
Scanner keyboard2= new Scanner(System.in);
System.out.print("Enter the first value for Xq: ");
xq = keyboard.nextDouble();
Scanner keyboard3= new Scanner(System.in);
System.out.print("Enter the first value for Yq: ");
yq = keyboard.nextDouble();
String p_quadrant=getQuadrant(xp,yp);
String q_quadrant=getQuadrant(xq,yq);
return "Point p is at "+p_quadrant+" and Point q is at "+q_quadrant;
}
/* Method to get the quadrant of each passed point*/
public String getQuadrant(double x, double y){
if(x==0 && y==0){
return "Origin";
}
else if(x==0){
return "Y-axis";
}
else if(y==0){
return "X-axis";
}
if (x >= 0) {
return (y >= 0 ? "1st Quadrant":"4th Quadrant");
} else {
return (y >= 0 ? "2nd Quadrant":"3rd Quadrant");
}
}
/* Method to get the euclidean distance between p and q */
public double euclidean(double xp, double yp, double xq, double yq){
double euc_distance = 0.0;
double x_square=Math.pow((xq-xp), 2);
double y_square=Math.pow((yq-yp), 2);
euc_distance= Math.sqrt(x_square+y_square);
return euc_distance;
}
/* Method to calculate the slope */
public double slope(double xp, double yp, double xq, double yq){
double x_diff= xp-xq;
double slope=0.0;
/* Check applied to avoid a divide by zero error */
if(x_diff == 0){
System.out.println("Slope is undefined");
System.exit(1);
}
else{
slope=(yp-yq)/x_diff;
}
return slope;
}
public static void main (String[] args) throws java.lang.Exception
{
/* Creating an object of Points and calling each method individually and printing the value*/
Points p = new Points();
double euc=p.euclidean(2.3, 5.6,0.5,9);
String quad=p.quadrant(0, -5.6,0,0);
double slop=p.slope(0,0.5,0.6,9);
System.out.print("Euclidean:"+euc+"\n Quadrant:"+quad+"\n Slope:"+slop);
}
}
I can't figure out why my scanner isn't working; I'm not getting errors either. My job is to ask the user for INPUTS for all the points. Really I am stuck and this is due in a few hours, and also I'm using the latest eclipse with new JDK. New to programming and this site XD.
When I run the program my I get this as a result; I'm not getting any errors either
Euclidean:3.847076812334269
Quadrant:Point p is at Y-axis and Point q is at Origin
Slope:14.166666666666668
You need to update your prompts and get rid of unnecessary Scanners to fix the problem. Your prompts all ask for the "first" value, and keyboard1 -keyboard3 are never used. This code works just as well:
Scanner keyboard= new Scanner(System.in);
System.out.print("Enter the first value for Xp: ");
xp = keyboard.nextDouble();
System.out.print("Enter the first value for Yp: ");
yp = keyboard.nextDouble();
System.out.print("Enter the first value for Xq: ");
xq = keyboard.nextDouble();
System.out.print("Enter the first value for Yq: ");
yq = keyboard.nextDouble();
String p_quadrant=getQuadrant(xp,yp);
String q_quadrant=getQuadrant(xq,yq);
return "Point p is at "+p_quadrant+" and Point q is at "+q_quadrant;
}
Also, in your main method, instead of creating a Point() object you create a Points() object. It does give me an error.

Cannot read the decimal point in Scanner

import java.util.Scanner;
public class Assignment3 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double pi = 3.142;
double T, v, a, x, r;
System.out.println("3.Centrifuge. The rotor of an ultracentrifuge rotates at x rev/s.");
System.out.println("A particle at the top of the test tube is r meter from the rotation axis.");
System.out.println("Calculate it’s centripetal acceleration.");
System.out.printf("Enter the number of rotation in rev/s : ");
x = input.nextInt();
System.out.printf("Enter the distance in meter : ");
r = input.nextInt();
T = 1/x;
v = (2*pi*r)/T;
a = (v*v)/r;
System.out.println("\n\nAnswer");
System.out.printf("The centripetal acceleration is : %.2f m/s^2\n", a);
}
}
Hi all. This is my coding and it cannot run when I put decimal point. how to fix it?
Replace input.nextInt(); with input.nextDouble();
x = input.nextInt(); // It will simply ignore decimal values
Hence you need to use nextDouble()
x = input.nextDouble(); // This will read the entire decimal value
You read a int with
input.nextInt();
Try
input.nextDouble();
Try it.
import java.util.Scanner;
public class JavaScannerDouble {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String data = input.next();
double decimalValue = Double.parseDouble(data);
System.out.println("Decimal value : " + decimalValue);
// test of decimal value
double response = decimalValue / 0.1;
System.out.println("response : " + response);
}
}

Categories

Resources