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);
}
}
Related
I'm self learning Java for a few weeks and started testing my (basic) knowledge. I was trying to create something like some formula calculator, with an index selector. I want to know if it's possible to, after using a formula, go back to the first question. I tried to use a while loop, but I couldn't figure it out.
public class formulas {
public static void main(String[] args) {
// TODO Auto-generated method stub
// first question
// constant values definition
final double PI = 3.141592653589793238;
//index
ArrayList<String> index = new ArrayList<>();
index.add("1. Pythagorean Theorem");
index.add("2. Square Area");
index.add("2. Triangle Area");
System.out.println("Formulas Index:");
System.out.println("");
for(int i=0; i<index.size(); i++) {
System.out.println(index.get(i));
}
System.out.println("");
System.out.print("Write the formulas number you want to use: ");
Scanner scanner = new Scanner(System.in);
String firstQuestion = scanner.nextLine();
System.out.println();
// methods selection
if (firstQuestion.equals("1")) {
System.out.println("Pythagoras Theorem");
System.out.print("Insert side a: ");
double a = scanner.nextDouble();
System.out.print("Insert side b: ");
double b = scanner.nextDouble();
double c = pitagoras(a,b);
System.out.println("Hypotenuse c: "+ c);
}
else if (firstQuestion.equals("2")) {
System.out.println("Square area");
System.out.print("Insert side a: ");
double arestaA = scanner.nextDouble();
System.out.print("Insert side b: ");
double arestaB = scanner.nextDouble();
double squareArea = squarearea(arestaA,arestaB);
System.out.println("The square area is: "+ squareArea);
}
else System.out.println("Please insert a valid formula number.");
}
// methods parameters
static double pitagoras(double a, double b) {
double c = Math.sqrt((a*a)+(b*b));
return c;
}
static double squarearea(double a, double b) {
double area = a*b;
return area;
}
}
I'm always surprised that people don't make more use of do-while loops, it's a severely underrated construct.
Think about it, you MUST do at least one iteration of the loop before you know if you want to continue or exit the loop. You also want to re-print the menu on each iteration, so it's easier to just put it in a do-while (IMHO)
You can take a look at Control Flow Statements and The while and do-while Statements for more details
import java.util.ArrayList;
import java.util.Scanner;
public final class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
// first question
// constant values definition
final double PI = 3.141592653589793238;
//index
ArrayList<String> index = new ArrayList<>();
index.add("1. Pythagorean Theorem");
index.add("2. Square Area");
index.add("3. Triangle Area");
index.add("4. Quit");
Scanner scanner = new Scanner(System.in);
boolean printMenu = true;
boolean exit = false;
do {
if (printMenu) {
System.out.println("");
System.out.println("Formulas Index:");
System.out.println("");
for (int i = 0; i < index.size(); i++) {
System.out.println(index.get(i));
}
System.out.println("");
System.out.print("Write the formulas number you want to use: ");
}
printMenu = true;
String firstQuestion = scanner.nextLine();
System.out.println();
// methods selection
if (firstQuestion.equals("1")) {
System.out.println("Pythagoras Theorem");
System.out.print("Insert side a: ");
double a = scanner.nextDouble();
System.out.print("Insert side b: ");
double b = scanner.nextDouble();
double c = pitagoras(a, b);
System.out.println("Hypotenuse c: " + c);
} else if (firstQuestion.equals("2")) {
System.out.println("Square area");
System.out.print("Insert side a: ");
double arestaA = scanner.nextDouble();
System.out.print("Insert side b: ");
double arestaB = scanner.nextDouble();
double squareArea = squarearea(arestaA, arestaB);
System.out.println("The square area is: " + squareArea);
} else if (firstQuestion.equals("3")) {
// Triangle area
} else if (firstQuestion.equals("4")) {
exit = true;
} else {
printMenu = false;
System.out.println("Please insert a valid formula number.");
}
} while (!exit);
}
// methods parameters
static double pitagoras(double a, double b) {
double c = Math.sqrt((a * a) + (b * b));
return c;
}
static double squarearea(double a, double b) {
double area = a * b;
return area;
}
}
You can simply wrap your code starting from firstQuestion variable declaration till the end of the if condition in a while loop which is always set to true.
public class Formulas {
public static void main(String[] args) {
// first question
// constant values definition
final double PI = 3.141592653589793238;
// index
ArrayList<String> index = new ArrayList<>();
index.add("1. Pythagorean Theorem");
index.add("2. Square Area");
index.add("2. Triangle Area");
System.out.println("Formulas Index:");
System.out.println("");
for (int i = 0; i < index.size(); i++) {
System.out.println(index.get(i));
}
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("");
System.out.print("Write the formulas number you want to use: ");
String firstQuestion = scanner.nextLine();
System.out.println();
// methods selection
if (firstQuestion.equals("1")) {
System.out.println("Pythagoras Theorem");
System.out.print("Insert side a: ");
double a = scanner.nextDouble();
System.out.print("Insert side b: ");
double b = scanner.nextDouble();
double c = pitagoras(a, b);
System.out.println("Hypotenuse c: " + c);
} else if (firstQuestion.equals("2")) {
System.out.println("Square area");
System.out.print("Insert side a: ");
double arestaA = scanner.nextDouble();
System.out.print("Insert side b: ");
double arestaB = scanner.nextDouble();
double squareArea = squarearea(arestaA, arestaB);
System.out.println("The square area is: " + squareArea);
} else
System.out.println("Please insert a valid formula number.");
}
}
// methods parameters
static double pitagoras(double a, double b) {
double c = Math.sqrt((a * a) + (b * b));
return c;
}
static double squarearea(double a, double b) {
double area = a * b;
return area;
}
}
I am trying to write a code which receives three different combinations of mass and volume and then stores each value into two different arrays: mass and volume.
It is also required that I create a method in order to calculate the density.
However, when I try to call the method in order to calculate with the inputted masses and volumes, I receive an error.
This is the error:
Density.java:19: error: incompatible types: double cannot be converted
to double[]
System.out.printf("%.2f",calculateDensity(mass[0],volume[0]));
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output
1 error
Here's my code:
import java.util.Scanner;
public class Density {
public static void main (String [] args) {
double [] mass = new double[3];
double [] volume = new double[3];
Scanner scan = new Scanner(System.in);
System.out.println("Enter the mass and volume for your three compounds.");
for (int i = 0; i < 3;i++) {
System.out.print("Enter mass in grams: ");
mass[i] = scan.nextDouble();
System.out.print("Enter volume in millimeters: ");
volume[i] = scan.nextDouble();
}
System.out.print("The density for mass = ");
System.out.printf("%.2f", mass[0]);
System.out.print("g and volume = ");
System.out.printf("%.2f", volume[0]);
System.out.print("ml is: ");
System.out.printf("%.2f",calculateDensity(mass[0],volume[0]));
}
public static void calculateDensity (double[] mass, double[] volume) {
double [] density = new double [3];
density[0] = mass[0] / volume[0];
}
}
I would love some help trying to figure out what is wrong. I am not entirely sure how to define methods with arrays or call methods using arrays.
Any help is appreciated.
Thank you!
calculateDensity needs double as parameters not double[].
You also need to return a double from density otherwise you can't print something out.
public static double calculateDensity (double mass, double volume){
//your code
return density;
}
calculateDensity parameters are arrays (double[]) but you pass (mass[0],volume[0]), which is primitive type double.
Change your method paameters to:
public static void calculateDensity (double mass, double volume)
import java.util.Scanner;
public class Density {
public static void main (String [] args) {
double [] mass = new double[3];
double [] volume = new double[3];
Scanner scan = new Scanner(System.in);
System.out.println("Enter the mass and volume for your three compounds.");
for (int i = 0; i < 3;i++) {
System.out.print("Enter mass in grams: ");
mass[i] = scan.nextDouble();
System.out.print("Enter volume in millimeters: ");
volume[i] = scan.nextDouble();
}
System.out.print("The density for mass = ");
System.out.printf("%.2f", mass[0]);
System.out.print("g and volume = ");
System.out.printf("%.2f", volume[0]);
System.out.print("ml is: ");
System.out.printf("%.2f",calculateDensity(mass[0],volume[0]));
}
public static double calculateDensity (double mass, double volume) {
return mass / volume;
}
}
Considering you have the requirement to print all three outputs and not just the first one and you need to have the method exactly as public static void calculateDensity (double[] mass, double[] volume)
Try this:
public static void main(String[] args) {
double [] mass = new double [3];
double [] volume = new double [3];
Scanner s = new Scanner(System.in);
System.out.println("Enter the mass and volume for your 3 compounds.\n");
for (int i = 0; i < 3; i++) {
System.out.print("Enter mass in grams: ");
mass [i] = s.nextDouble();
System.out.println();
System.out.printf("Enter volume in milliliters: ");
volume [i] = s.nextDouble();
System.out.println();
}
s.close();
calculateDensity(mass, volume);
}
public static void calculateDensity(double[] mass, double[] volume) {
System.out.printf("The density for mass = %.2f g and volume = %.2f ml is: %.2f g/ml\n\n", mass[0], volume[0], (mass[0] / volume[0]));
System.out.printf("The density for mass = %.2f g and volume = %.2f ml is: %.2f g/ml\n\n", mass[1], volume[1], (mass[1] / volume[1]));
System.out.printf("The density for mass = %.2f g and volume = %.2f ml is: %.2f g/ml\n\n", mass[2], volume[2], (mass[2] / volume[2]));
}
This may not be the best, but it works as prescribed.
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.
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'm trying to build an app which computes the area of a triangle, as per my homework assignment. Not quite sure where I'm going wrong, but I input the lengths of the triangle and would like the proper area displayed according to Heron's formula: sqrt (s(s-a) (s-b) (s-c)). All I'm getting for output is -0.0. Here is the code:
import java.lang.Math;
public class Formula
{
double area; double s;
public double findArea(double sideA, double sideB, double sideC)
{
s = 1/2 * (sideA + sideB + sideC);
area = Math.sqrt(s*(s-sideA)*(s-sideB)*(s-sideC));
System.out.println("The area of the triangle is " + area);
return area;
}
}
And then I have another file for the main args
import java.util.Scanner;
public class findTriangleArea {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Formula triangle = new Formula();
double a,b,c;
// input triangle lengths a, b, c
Scanner inputTriangle = new Scanner(System.in);
System.out.println("Please enter triangle side a");
a = inputTriangle.nextDouble();
System.out.println("Please enter triangle side b");
b = inputTriangle.nextDouble();
System.out.println("Please enter triangle side c");
c = inputTriangle.nextDouble();
triangle.findArea(a, b, c);
}
}
1/2 is being computed in integer arithmetic, so like with all integer division, it's truncated -- in this case, to 0. Just write 0.5 and you'll be fine.
public class AreaOfTriangle {
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
System.out.print("Enter the height: ");
double height=scanner.nextDouble();
System.out.print("Enter the base: ");
double base=scanner.nextDouble();
scanner.close();
double area=(base*height)/2;
System.out.println("---------------------------");
System.out.println("Area of Triangle is: "+area);
}
}
Heron's Formula:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double a, b, c;
a = sc.nextDouble();
b = sc.nextDouble();
c = sc.nextDouble();
double p = (a + b + c) / 2;
System.out.println(Math.sqrt(p * (p - a) * (p - b) * (p - c)));
}