I am making a Pythagorean theorem program to solve for a missing side, and if the user enters 0 as the value that means that that is the missing side to solve for. My program is not getting the correct answer. Your help is greatly appreciated.
import java.util.Scanner;
import java.lang.Math;
public class pythagTheorem {
static double a;
static double b;
static double c;
static double newa;
static double newb;
static double newc;
public static void main(String[] args) {
Scanner scan= new Scanner(System.in);
System.out.println("Enter the value of a");
a=scan.nextDouble();
scan.nextLine();
System.out.println("Enter the value of b");
b=scan.nextDouble();
scan.nextLine();
System.out.println("Enter the value of c");
c=scan.nextDouble();
scan.nextLine();
if(a==0)
{
newb=Math.pow(b, b);
newc=Math.pow(c, c);
double result=newc-newb;
newa=Math.sqrt(result);
}
System.out.println("The value of a is " + newa);
}
}
Okay! So the problem I see with this Java code would be that it doesn't necessarily follow the actual pythagorean theorem. I see that if (A==0) then execute the actual equation, but you must remember that variable A isn't the hypotenuse of the triangle!
A^2 + B^2 = C^2 (C being the hypotenuse) If you want to make it so that it finds any part of the triangle you must remember to derive the equation so that you can find the missing side! Such as, you have side A and C but you want to find side B, the equation would then be B^2 = C^2-A^2.
Last of all, I see you have newb=Math.pow(b, b); that would power your variable to itself! Even the the powers are only 2, so it would be newb=Math.pow(b, 2);
TIP! Remember to capitalize the second word in a variable name like numa to numA
/* REMEMBER THAT A NUMBER MUST NEVER BE GREAT THAN C UNLESS IT IS THE UNKNOWN OR YOU WILL ENCOUNTER A NONREAL NUMBER BECAUSE YOU CAN'T SQUARE ROOT A NEGATIVE NUMBER*/
import java.util.Scanner;
import java.lang.Math;
public class pythagTheorem {
static double a;
static double b;
static double c;
static double newa;
static double newb;
static double newc;
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter a ZERO for the unknown side!");
System.out.println("Enter the value of side A :: ");
a = scan.nextDouble();
System.out.println("Enter the value of B :: ");
b = scan.nextDouble();
System.out.println("Enter the value of C :: ");
c = scan.nextDouble();
if (a == 0) {
newc = Math.pow(c, 2);
newb = Math.pow(b, 2);
newa = Math.sqrt(newc - newb);
System.out.println("Your missing side is :: " + newa);
}
else if(b == 0){
newc = Math.pow(c, 2);
newa = Math.pow(a, 2);
newb = Math.sqrt(newc - newa);
System.out.println("Your missing side is :: " + newb);
}
else if(c == 0){
newa = Math.pow(a, 2);
newb = Math.pow(b, 2);
newc = Math.sqrt(newa + newb);
System.out.println("Your missing side is :: " + newc);
}
else
System.out.println("Sorry! There is an error!");
}
}
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;
}
}
Hello I'm working on a project for my java class, I'm supposed to write a code for a Algebra tutor that goes like this:
Write a program with a that displays a randomly generated problem that asks the user to solve for the y variable, takes input from the user, and prints "correct" if the user answered correctly and prints "incorrect" if not. Your main should give one problem and then exit. Use one or more methods to produce this behavior.
This is regarding the formula mx + b. So here is what I have so far, and works!
import java.util.Random;
import java.lang.Math;
import java.util.Scanner;
class Main {
public static void main(String[] arg){
double min_value = -100;
double max_value = 100;
double m_value = (int)(Math.random()*((max_value-min_value)+1))+min_value;
double x_value = (int)(Math.random()*((max_value-min_value)+1))+min_value;
double b_value = (int)(Math.random()*((max_value-min_value)+1))+min_value;
System.out.println("Given: ");
System.out.println("m = " + m_value);
System.out.println("x = " + x_value);
System.out.println("b = " + b_value);
System.out.print("What is the value of y? ");
Scanner user_input = new Scanner(System.in);
String user_answer = "";
user_answer = user_input.next();
int correct_answer = (int)m_value * (int)x_value + (int)b_value;
if (user_answer.equals(correct_answer))
System.out.println("You are correct!");
else
System.out.print("Sorry, that is incorrect. ");
System.out.println("The answer is " + correct_answer);
}
}
so even tho the output is correct, I need to break down the code into smaller methods, this is where Im getting confused on how to take a piece of that code and put it in another method that once it runs it calls for that method too and gives me the same output. I been ready the material given but the more I read it the more confuse I get. If anybody has any ideas or suggestions please let me know any info will be really appreciate. Thank you
Here's a quick rundown on methods, so it's not completely done yet. Ask, if you need more help! Good luck on your homework and on becoming one of the beast developers!
public class Main {
public static void main(String[] args) {
int a = 1; // give a value of 1
methodTwo(a); // sending the int a into another method
}
// Here's method number two
static void methodTwo (int a) { // it gives a's type and value
System.out.println(a); //Gives out a's value, which is 1
}
}
Technically you've solved the problem correctly, you are using one or more methods, but perhaps what you trying to do is a common code refactor called the extract method / extract function refactor Executing this type of refactor leads to much more readable and maintainable code, and is easy to do.
As a starter, identify code that repeats or looks similar, in your case, the following lines look ripe for extract method:
double m_value = (int)(Math.random()*((max_value-min_value)+1))+min_value;
double x_value = (int)(Math.random()*((max_value-min_value)+1))+min_value;
double b_value = (int)(Math.random()*((max_value-min_value)+1))+min_value;
Notice that the RHS of each line is identicial, so we can replace the explicit code with a method call like this:
double m_value = getRandomDoubleBetween(max_value, min_value);
double x_value = getRandomDoubleBetween(max_value, min_value);
double b_value = getRandomDoubleBetween(max_value, min_value);
private double getRandomDoubleBetween(double max_value, double min_value) {
return (int)(Math.random()*((max_value-min_value)+1))+min_value;
}
You can identify other areas of code that either contain repetition or perhaps some hard to understand code that would be more understandable if it was extracted into a method that had a name that reveals what the code is doing.
Please review this, you are comparing string with integer,
if (user_answer.equals(correct_answer))
This may help you:
import java.util.Scanner;
class Main {
public static void main(String[] arg) {
double min_value = -100;
double max_value = 100;
double m_value = generateRandom(max_value, min_value);
double x_value = generateRandom(max_value, min_value);
double b_value = generateRandom(max_value, min_value);
System.out.println("Given: ");
System.out.println("m = " + m_value);
System.out.println("x = " + x_value);
System.out.println("b = " + b_value);
checkAnswer(m_value, x_value, b_value);
}
private static void checkAnswer(double m_value, double x_value, double b_value) {
System.out.print("What is the value of y? ");
Scanner user_input = new Scanner(System.in);
String user_answer = "";
user_answer = user_input.next();
int correct_answer = (int) m_value * (int) x_value + (int) b_value;
if (user_answer.equals(String.valueOf(correct_answer))) {
System.out.println("You are correct!");
} else {
System.out.print("Sorry, that is incorrect. ");
System.out.println("The answer is " + correct_answer);
user_input.close();
}
}
static int generateRandom(double max_value, double min_value) {
return (int) ((int) (Math.random() * ((max_value - min_value)
+ 1)) + min_value);
}
}
I am trying to learn Java; here is the exercise I am struggling with:
Fermat’s Last Theorem says that there are no integers a, b, and c such that a^n + b^n = c^n except in the case when n = 2.
Write a method named checkFermat that takes four integers as parameters— a, b, c and n—and that checks to see if Fermat’s theorem holds. If n is greater than 2 and it turns out to be true that a^n + b^n = c^n, the program should print “Holy smokes, Fermat was wrong!” Otherwise the program should print “No, that doesn’t work.”
You should assume that there is a method named raiseToPow that takes two integers as arguments and that raises the first argument to the power of the second. For example:
int x = raiseToPow(2, 3);
would assign the value 8 to x, because 2^3 = 8.
I have encountered several problems, for example I can't seem to use Math.Pow(a, n) with an int, only with a double. If you are interested, here is what I have so far, feel free to skip it and just write your own version of the program in the answers.
(Please keep in mind I started this book only a few days back.)
package fermat.s_last_theorem;
import java.lang.Math;
import java.util.Scanner;
public class FermatS_Last_Theorem {
public static void main(String[] args) {
Scanner s = new Scanner (System.in);
System.out.println("Inster First Number");
double frst = s.nextDouble();
System.out.println("Insert Second Number");
double scnd = s.nextDouble();
System.out.println("Insert Exponent");
double expo = s.nextDouble();
double v = FLaw(frst,scnd,expo);
double k = FLawRes(v, expo);
System.out.println("The answer is " + v);
System.out.println("Your answer rooted by your exponent is " + k);
Law(v, Pow(k, expo));
}
public static double Pow(double a, double b) {
double res = Math.pow (a, b);
return (res);
}
public static double FLaw(double frst, double scnd, double expo) {
double D1 = Pow(frst, expo);
double D2 = Pow(scnd, expo);
return (D1 + D2);
}
public static double FLawRes(double res, double base) {
double D3 = Pow(res, 1/base);
return D3;
}
public static void Law(double v, double k) {
if (v==k) {
System.out.println("Pythagora works.");
} else {
System.out.println("Pythagora doesnt work");
}
}
}
The main problem is that I am not exactly sure how to answer the question the exercise asks, and the program listed above does not work as it should.
You should assume that there is a method named raiseToPow ...
That means you write your code using such a method, even though you don't have the method. Your code will be reviewed manually, or teacher may supply the method and run your code.
If you want to test your code, you can always implement it yourself. You should just remove the method before turning in the code.
But the intent here is that this is a write-on-paper exercise.
Now, how to implement int raiseToPow(int a, int b)?
Think about what it means. 34 means 3 * 3 * 3 * 3.
So, implement the method to multiply by a by itself b times.
I'll leave that as another exercise for you.
You can break it out like this :
public boolean checkFermat(int a, int b, int c, int n) {
if(n != 2 &&
(checkFermatCondition(a,b,c,n) ||
checkFermatCondition(a,c,b,n) ||
checkFermatCondition(b,c,a,n))) {
System.out.println("Holy smokes, Fermat was wrong!");
} else {
System.out.println("No, that doesn’t work.");
}
}
In this method you are just trying to reduce you check condition with all of the combinations by calling this method with different parameters
private boolean checkFermatCondition(int a, int b, int c, int n) {
return raiseToPow(a,n)+raiseToPow(b,n) == raiseToPow(c,n);
}
Your function raiseToPow()'s functionality can be achieved using Math.pow:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println( "Fermat's Last Theorem: a^n+b^n != c^n (n!=2)");
int a, b, c, n;
System.out.print("Enter value for a:");
a = s.nextInt();
System.out.print("Enter value for b:");
b = s.nextInt();
System.out.print("Enter value for c:");
c = s.nextInt();
while(true){
System.out.print("Enter value for n:");
n = s.nextInt();
if(n!=2)
break;
System.out.println("n cannot be 2");
}
checkFremat(a,b,c,n);
}
public static void checkFremat(int a, int b, int c, int n){
if ((int)Math.pow(a, n)+(int)Math.pow(b, n)!=(int)Math.pow(c, n))
System.out.println("Fermat was correct!");
else
System.out.println("Holy smokes, Fermat was wrong!");
}
}
Try it here!
The goal is to create a program that takes a quadratic equation in quadratic form and solve it. Is there a different way to go about doing so other than StringTokenizer? Or is it possible to isolate just ^2 in StringTokenizer rather than ^ and 2 like it is doing now? I realized that using the way I wrote it, it will not allow equations to use 2 at all.
This question requires me to not take individual coefficients, but rather the entire equation itself.
Sample run: ”java SolveEquation2 1.5625x∧2+2.5x+1=0”. For this input the output should be: ”x=-0.8”
import java.util.Scanner;
import java.util.StringTokenizer;
class SolveEquation2 {
public static void main(String args[]){
Scanner scan = new Scanner(System.in);
System.out.print("Input a quadratic");
String equation = scan.nextLine();
StringTokenizer st = new StringTokenizer(equation, "x^2+-");
String a,b,c;
a = st.nextToken();
b = st.nextToken();
c = st.nextToken();
double a1 = Double.parseDouble(a);
double b1 = Double.parseDouble(b);
double c1 = Double.parseDouble(c);
double x = (b1 * b1) - (4 * a1 * c1);
double var1 = (-b1 + Math.sqrt(x)) / (2*a1);
double var2 = (-b1 - Math.sqrt(x)) / (2*a1);
if (x == 0){
System.out.println("x = " + var1);
}
if (x > 0){
System.out.println("x1 = " + var1);
System.out.println("x2 = " + var2);
}
if (x < 0){
System.out.println("No Solution");
}
}
}
You want to use regular expressions to parse the command line input.
It seems that what you're trying to do has been done many times before.
See here
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)));
}