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.
Related
Hey everyone very new to coding!
So I was trying to make a calculator program using object oriented programming in Java however when I try to call my method for addition it doesn't do the job entirely so what am I doing wrong here ?
Thanks in advance :)
import java.util.Scanner;
public class CalculatorOOP {
Scanner input = new Scanner(System.in);
public static double currentValue;
public double valueInput;
public CalculatorOOP(double valueTyped){
valueTyped = currentValue;
}
public double addToValue(){
System.out.println("Type the value you want to add:");
double valueToAdd = input.nextDouble();
double valueAfterAddition = CalculatorOOP.currentValue + valueToAdd;
return valueAfterAddition;
}
public double substractToValue(){
System.out.println("Type the value you want to substract:");
double valueToSubstract = input.nextDouble();
double valueAfterSubstraction =
CalculatorOOP.currentValue - valueToSubstract;
return valueAfterSubstraction;
}
public double multiplyValue(){
System.out.println("Type the factor value:");
double factor = input.nextDouble();
double valueAfterMultiplication = CalculatorOOP.currentValue * factor;
return valueAfterMultiplication;
}
public double divideValue(){
System.out.println("Type the divisor value:");
double divisor = input.nextDouble();
double valueAfterDivision = CalculatorOOP.currentValue / divisor;
return valueAfterDivision;
}
}
import java.util.Scanner;
public class Main {
public static void main(String[]args){
Scanner input = new Scanner(System.in);
System.out.println("Type a value:");
double valueInput = input.nextDouble();
CalculatorOOP obj = new CalculatorOOP(valueInput);
System.out.println("Enter the calculation option (1, 2, 3, or 4):");
int optionEntered = input.nextInt();
switch (optionEntered){
case 1 : obj.addToValue();
}
}}
Here this is what I get when running the code however it is not performing the addition it is just asking for values
Type a value:
2
Enter the calculation option (1, 2, 3, or 4):
1
Type the value you want to add:
4
Process finished with exit code 0
Your addToValue method seems to perform the addition correctly and return the calculated sum. Where you call the method, you are not picking up the return value — so it just disappears, is discarded. I believe you want to assign it back into CalculatorOOP.currentValue and/or print it. Either from inside the method or from where you called it.
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.
)
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);
}
}
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);
}
}
I'm trying to code a loan calculator. I seem to be having issues. I am trying to get an input from the user and validate the input. I know I am doing it wrong the problem is I'm scratching my head wondering how to do it right.
I get a red line on the d = getDouble(sc, prompt); and the i = getInt(sc, prompt); which I understand I don't have that coded correctly. I'm just unsure how to go about fixing it.
I also have to validate the continue statement which I wasn't to sure the best way to go about that and finally the instructor expects the code to be 80 lines or less which I am right about 80 lines. I guess I'm looking for a better way to do this but being new I'm scratching my head and I'm hoping someone can lend a hand.
As always I really appreciate the help.
import java.util.Scanner;
import java.text.NumberFormat;
public class LoanCalculator
{
public static double getDoubleWithinRange(Scanner sc, String prompt, double min, double max)
{
double d = 0.0;
boolean isValid = false;
while(isValid == false);
{
d = getDouble(sc, prompt);
if (d <= min)
{
System.out.println("Error! Number must be greater tha 0.0");
}
else if (d >= max)
{
System.out.println("Error number must be less than 1000000.0");
}
else
isValid = true;
}
return d;
}
public static int getIntWithinRange(Scanner sc, String prompt, int min, int max)
{
int i = 0;
boolean isvalid = false;
while(isvalid == false)
{
i = getInt(sc, prompt);
if (i <= min)
System.out.println("Error! Number must be more than 0");
else if (i >= max)
System.out.println("Error! Number must be less than 100");
else
isvalid = true;
}
}
public static void main(String[] args)
{
System.out.println("Welcome to the loan calculator");
Scanner sc = new Scanner(System.in);
String choice = "y";
while (choice.equalsIgnoreCase("y"))
{
System.out.println("DATA ENTRY");
double loanAmount = getDoubleWithinRange(sc, "Enter loan amount: ", 0.0, 1000000.0);
double interestRate = getDoubleWithinRange(sc, "Enter yearly interest rate: ", 0, 20);
int years = getIntWithinRange(sc, "Enter number of years: ", 0, 100);
int months = years * 12;
double monthlyPayment = loanAmount * interestRate/
(1 - 1/Math.pow(1 + interestRate, months));
NumberFormat currency = NumberFormat.getCurrencyInstance();
NumberFormat percent = NumberFormat.getPercentInstance();
percent.setMaximumFractionDigits(3);
System.out.println("RESULST");
System.out.println("Loan Amount" + currency.format(loanAmount));
System.out.println("Yearly interest rate: " + percent.format(interestRate));
System.out.println("Number of years: " + years);
System.out.println("Monthly payment: " + currency.format(monthlyPayment));
System.out.println();
System.out.println("Continue? (y/n): ");
choice =sc.next();
System.out.println();
}
}
}
You haven't made the implementation of your getDouble(Scanner,String) and getInt(Scanner,String) that's why you're getting the red line.
since you already have a scanner, and prompt string change it to this
System.out.print(prompt);
d = sc.nextDouble();
and for the integer
System.out.print(prompt);
i = sc.nextInt();
I think getDouble and getInt are string functions so you would have to get a string first then call those methods. However, since you have a scanner, I assume you want to use that with the nextXXX methods:
Scanner sc = new Scanner (System.in);
double d = sc.nextDouble();
You can use this complete snippet for educational purposes:
import java.util.Scanner;
class Test {
public static void main (String args[]) {
Scanner sc = new Scanner (System.in);
System.out.print("Enter your double: ");
double d = sc.nextDouble();
System.out.print("Enter your integer: ");
int i = sc.nextInt();
System.out.println("You entered: " + d + " and " + i);
}
}
Transcript:
Enter your double: 3.14159
Enter your integer: 42
You entered: 3.14159 and 42
Basically, the process is:
Instantiate a scanner, using the standard input stream.
Use print for your prompts.
Use the scanner nextXXX methods for getting the input values.
A little more assistance here, based on your comments.
In your main function, you have:
double loanAmount = getDoubleWithinRange(sc, "Enter loan amount: ", 0.0, 1000000.0)
and that function has the prototype:
public static double getDoubleWithinRange(
Scanner sc, String prompt, double min, double max)
That means those variables in the prototype will be set to the values from the call. So, to prompt for the information, you could use something like (and this is to replace the d = getDouble(sc, prompt); line):
System.out.print(prompt);
double d = sc.nextDouble();
And there you have it, you've prompted the user and input the double from them. The first line prints out the prompt, the second uses the scanner to get the input from the user.
As an aside, your checks for the minimum and maximum are good but your error messages have hard-coded values of 0 and 100K. I would suggest that you use the parameters to tailor these messages, such as changing:
System.out.println("Error! Number must be greater tha 0.0");
into:
System.out.println("Error! Number must be greater than " + min);
That way, if min or max change in future , your users won't get confused :-)
I'll leave it up to you to do a similar thing for the integer input. It is your homework, after all :-)