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!
Related
I have been working on these programs.
They don't have any errors but I need to make them return a result in order for them to work properly. More specifically to add a method that returns a result.
The instructions were the following:
Write a program that is split in to methods at least one of which returns a result
This is the first program:
import java.util.Scanner; // Needed to make Scanner available
public class onlineCalculator {
public static void main(String[] args) {
Calculator();
} //END of main method
// Inserting your loan at the start of the year and the amount paid off
// and calculates the amount yet to pay with interest
//
public static void Calculator(){
int a;
int b;
Scanner scanner = new Scanner(System.in);
System.out.print("Amount of loan at start of year? ");
a = scanner.nextInt();
System.out.print("Amount paid off this year? ");
b = scanner.nextInt();
int c;
c= a - b;
double d;
final double e;
d = c * 1.07 * 10.0;
e = (int)d / 10.0;
System.out.println("The new amount owed is (in pounds): " + e);
} //END of Calculator
}
This is the second program:
import java.util.Scanner; // Needed to make Scanner available
public class BodyAge {
public static void main(String[] args) {
CalculateAge();
} // END of main method
// Inserting age and heart rate and stretch distance
//and calculates the body age based on conditions
public static void CalculateAge() {
int age;
int heartRate;
int stretch;
Scanner input = new Scanner(System.in);
System.out.print("What is your age? ");
age = input.nextInt();
System.out.print("What is your heart rate? ");
heartRate = input.nextInt();
if (heartRate <= 62) {
age -= 5; // block of code to be executed if condition1 is true
} else if (62 <= heartRate && heartRate <= 64) {
age--; // block of code to be executed if the condition1 is false and condition2 is
// true
} else if (65 <= heartRate && heartRate <= 70) {
age++; // block of code to be executed if the condition1 and condition2 are false and
// condition3 is true
} else {
age += 2; // block of code to be executed if the condition1 and condition2 and condition3
// are false and condition4 is true
}
System.out.print("How far can you stretch? ");
stretch = input.nextInt();
if (stretch <= 20) {
age += 4; // block of code to be executed if condition1 is true
} else if (20 <= stretch && stretch <= 32) {
age++; // block of code to be executed if the condition1 is false and condition2 is
// true
} else if (33 <= stretch && stretch <= 37) {
age = age + 0; // block of code to be executed if the condition1 and condition2 are false and
// condition3 is true
} else {
age = age + 3; // block of code to be executed if the condition1 and condition2 and condition3
// are false and condition4 is true
}
System.out.println("Your body's age is " + age);
} //END of CalculateAge
}
Here's an example of one possible way you might consider breaking up a class into using some methods with returns. Let's take your first class for this example. You frequently are taking input from your user.
Scanner scanner = new Scanner(System.in);
System.out.print("Amount of loan at start of year? ");
a = scanner.nextInt();
System.out.print("Amount paid off this year? ");
b = scanner.nextInt();
This could potentially be broken out into another method for condensed reusability.
public static int askForInt(Scanner scanner, String message) {
System.out.print(message);
return scanner.nextInt();
}
From there you can replace your calls for information with this method. Full example:
import java.util.Scanner; // Needed to make Scanner available
public class OnlineCalculator {
public static void main(String[] args) {
calculator();
} //END of main method
// Inserting your loan at the start of the year and the amount paid off
// and calculates the amount yet to pay with interest
//
public static void calculator(){
int a;
int b;
Scanner scanner = new Scanner(System.in);
a = askForInt(scanner, "Amount of loan at start of year? ");
b = askForInt(scanner, "Amount paid off this year? ");
scanner.close();
int c;
c= a - b;
double d;
final double e;
d = c * 1.07 * 10.0;
e = (int)d / 10.0;
System.out.println("The new amount owed is (in pounds): " + e);
} //END of Calculator
public static int askForInt(Scanner scanner, String message) {
System.out.print(message);
return scanner.nextInt();
}
}
First program,
You could for example split your calculate() method into 2 method and move your int variable "a" and "b" in the main() method
1ST method:
void getInput(){
...
}
2nd method:
int calculateAndreturnResult(int a, int b) {
...
}
Finally use those method in the main() and print the result :
getInput();
int result = calculateAndreturnResult(){
}
system.out.println(result);
So how Java will work is the compiler will only read commands from the "main" method. So in the case of the calculator, Java will see that you want to run the calculator method, which has a return type of "void" It goes PUBLIC (meaning other classes can see and interact with it) STATIC (basically meaning that the method belongs to the class itself, not instances of the class) VOID ( this is your return type, meaning after the method is done, what is being put back into main) so if you want a method to return something, you need to change the return type. In the case of your calculator project something like this would split it up into 2 methods one of which returns something:
public class OnlineCalculator {
public static void main(String[] args) {
Calculator();
} //END of main method
// Inserting your loan at the start of the year and the amount paid off
// and calculates the amount yet to pay with interest
//
//this will return an int type
public static int loanDifference(int amountOwed, int amountPaid) {
int c = amountOwed - amountPaid;
return c;
}
// this will return a double type
public static double newAmountOwed(double d) {
double e = (int)d / 10.0;
return e;
}
public static void Calculator(){
int a;
int b;
Scanner scanner = new Scanner(System.in);
System.out.print("Amount of loan at start of year? ");
a = scanner.nextInt();
System.out.print("Amount paid off this year? ");
b = scanner.nextInt();
scanner.close();
int c = loanDifference (a, b);
double d;
d = c * 1.07 * 10.0;
final double e = newAmountOwed(d);
System.out.println("The new amount owed is (in pounds): " + e);
} //END of Calculator
}
seems like they want you to put more code in, but the idea is that they want you to know how to use methods that work together to make something at the end!
use the same idea with the other one!
import java.util.Scanner;
public class LAB1201 {
static int multi(int a, int b){
int c = 0;
if (b == 0) {
c = 0;
}
if (b < 0) {
c = (-multi(a, -b));
}
if (b > 0) {
c = (a + multi(a, b-1));
}
return c;
}
public static void main(String[]args){
int aa;
int bb;
Scanner scanner = new Scanner(System.in);
System.out.println("Type in a integer");
aa = scanner.nextInt();
System.out.println("Type in another integer");
bb = scanner.nextInt();
multi(aa,bb);
}
}
I am coding
(Write a recursive function that multiplies two numbers x and y using recursion (do not
use the multiplication operator). Your main method should prompt the user for the two
numbers, call your function, and print the result)
It allows me to type in values but I am not sure why it is not returning any values
it returns nothing..
You forgot to output the value.
System.out.println(aa + " x " + bb + " = " + multi(aa,bb));
Output example:
Type in a integer
4
Type in another integer
8
4 x 8 = 32
Your code is fine. You just forgot to print the result returned by method static int multi(int a, int b). You can find working code here
You are missing a printing statement. Here is the code, please have a look.
import java.util.Scanner;
public class so {
static int multi(int a, int b){
int c = 0;
if(b<0){
return c=(-multi(a, -b));
}
if(b>0){
return c=(a+multi(a, b-1));
}
return c;
}
public static void main(String[]args){
int aa;
int bb;
Scanner scanner = new Scanner(System.in);
System.out.println("Type in a integer");
aa = scanner.nextInt();
System.out.println("Type in another integer");
bb = scanner.nextInt();
System.out.println(multi(aa,bb));
}
I have some experience using Python so I've been trying to learn Java by writing the same programs I write in Python for school in Java.
I have this function where I enter two integers and it returns the sum. If the integers are the same, then it returns double the sum. For example, 5 + 5 = 20.
I have the following code for this function.
public class sumDouble
{
public int sumDouble(int a, int b) {
int sum = a + b;
if (a == b) {
sum = sum * 2;
}
return sum;
}
}
Next, I want to write a script where I ask the user to input two integers and the main class calls this function. I have the following code for this. Where did I go wrong?
import java.util.Scanner;
public class GetSumFromUser
{
public static void main (String[] args){
Scanner in = new Scanner(System.in);
int a;
int b;
int sumDouble;
sumDouble sum = new sumDouble();
System.out.println("Please enter an integer.");
a = in.nextInt();
System.out.println("You entered "+a);
System.out.println("Please enter another integer.");
b = in.nextInt();
System.out.println("You entered "+b);
System.out.println("Your sum is "+sum);
}
}
At the last line, the output reads "Your sum is sumDouble#1777aec".
You never actually invoked the sumDouble() method. Rather than print out sum (which is an Object), you should print like this:
System.out.println("Your sum is "+sum.sumDouble(a,b));
Try this:
public class SumDouble
{
public static int sumDouble(int a, int b) {
int sum = a + b;
if (a == b) {
sum = sum * 2;
}
return sum;
}
}
...
System.out.println("Your sum is "+SumDouble.sumDouble(a, b));
If you do print(sum) then you are printing the object...
do instead
System.out.println("Your sum is "+sum.sumDouble(a,b));
You get an object from sumDouble class, but you never invoke it's sumDouble method:
sumDouble sum = new sumDouble();
change this to:
sumDouble sd = new sumDouble();
int sum = sd.sumDouble(a,b);
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package test;
import java.util.Scanner;
class sumDouble
{
public int sumDouble(int a,int b)
{
int sum=a+b; //add the numbers
if(a==b) //check if both numbers are same
sum=sum*2; //double th value if same
return sum; //return sum
}
}
public class GetSumFromUser
{
public static void main (String[] args){
Scanner in = new Scanner(System.in);
sumDouble s=new sumDouble();
int a;
int b;
int sum;
System.out.println("Please enter an integer.");
a = in.nextInt();
System.out.println("You entered "+a);
System.out.println("Please enter another integer.");
b = in.nextInt();
System.out.println("You entered "+b);
sum= s.sumDouble(a, b) ; //call the sum double function
System.out.println("Your sum is "+sum);
}
}
System.out.println("Your sum is "+sum);
Change this to:
System.out.println("Your sum is "+sum.sumDouble(a,b));
You haven't called the method. "Your sum is "+sum -this will call the toString method of sum which is sumDouble#1777aec.
I'm writing a program that calculates the hypotenuse of a triangle, and I'm supposed to call up a method into the main.
Is it better to have them in 2 separate files, or to have the method I'm calling up in the program I'm running?
In the program, I keep getting error messages about the last line of code, with the JOptionPane output.
What am I getting wrong?
import javax.swing.JOptionPane;
import java.util.Scanner;
public class A2
{
public static double Hypo(double a,double b,double c);
double a,b,c;
{
hyp=((a*a)+(b*b));
c=Math.sqrt(hyp);
}
int x,y;
double c;
String text1=JOptionPane.showInputDialog("How long is side A? ");
int x=Integer.parseInt(text1);
String text2=JOptionPanes.howInputDialog("How long is side B? ");
int y=Integer.parseInt(text2);
double c=A2.Hypo(x,y);
JOptionPane.showMessageDialog(null, "The hypotenuse of the triangle is " +c);
}
This code has so many problems it's hard to know where to begin.
Here's some advice:
Good names matter. You can and must do better than A2 for a class.
Learn and follow the Sun Java coding standards.
Style and readability matter. Learn a good code layout and stick to it.
Start with this. It runs and gives correct results:
import javax.swing.*;
/**
* A2
* #author Michael
* #link https://stackoverflow.com/questions/30965862/calling-method-to-a-main-in-java
* #since 6/21/2015 11:00 AM
*/
public class SimpleMathDemo {
public static double hypotenuse(double a,double b) {
return Math.sqrt(a*a+b*b);
}
public static void main(String[] args) {
String text1= JOptionPane.showInputDialog("How long is side A? ");
int x=Integer.parseInt(text1);
String text2=JOptionPane.showInputDialog("How long is side B? ");
int y=Integer.parseInt(text2);
double c= SimpleMathDemo.hypotenuse(x,y);
JOptionPane.showMessageDialog(null, "The hypotenuse of the triangle is " +c);
}
}
Code analysis
public class A2 {
//Missing method body no return values ..Is this an abstact function?/
public static double Hypo(double a, double b, double c);
double a, b, c;
//Whats this part doing hanging in the middle??
{
//where is the variable declaration of hyp
hyp = ((a * a) + (b * b));
c = Math.sqrt(hyp);
}
int x, y;
//variable c is already declared
double c;
String text1 = JOptionPane.showInputDialog("How long is side A? ");
//variable x is already declared
int x = Integer.parseInt(text1);
//JOptionPane not JOptionPanes
String text2 = JOptionPanes.howInputDialog("How long is side B? ");
//variable y is already declared
int y = Integer.parseInt(text2);
//variable c is already declared and Hypo function has three arguements in the declaration
double c = A2.Hypo(x, y);
//wont work because the whole code is buggy
JOptionPane.showMessageDialog (null, "The hypotenuse of the triangle is " +c);
}
}
To elaborate more:
import javax.swing.JOptionPane;
public class A2 {
public static double Hypo(int a, int b) {
double hyp=((a*a)+(b*b));
double c=Math.sqrt(hyp);
return c;
}
public static void main(String[] args) {
int x, y;
double c;
String text1=JOptionPane.showInputDialog("How long is side A? ");
x=Integer.parseInt(text1);
String text2=JOptionPane.showInputDialog("How long is side B? ");
y=Integer.parseInt(text2);
JOptionPane.showMessageDialog(null, "The hypotenuse of the triangle is " + Hypo(x,y));
}
}
You need to choose a correct return type, whether it be void, int, double, etc, and each method with a return type should return a value with the set type.
You also always need at least one main method in a program. There can be multiple in different classes.
You will need to use a more specific variable names, and follow oracle convention for brackets {}.
DO not declare a variable twice as in:
int x, y;
int x = 1; // WRONG
x = 1; // Correct
Currently I am creating (trying) a program for Newton's Method and its suppose to allow you to guess the initial root and give you the roots. But I can't figure out how to put the
x1=x0-f(x0)/f(x0) also needs a loop
Here's my code currently :
import java.util.Scanner;
public class NewtonsMethod {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter your guess for the root:");
double x = keyboard.nextDouble();
double guessRootAnswer =Math.pow(6*x,4)-Math.pow(13*x,3)-Math.pow(18*x,2)+7*x+6;
for(x=x-f(x)/f(x));
System.out.println("Your answer is:" + guessRootAnswer);
}
}
You've misstated how newton's method works:
The correct formula is:
xn+1 <= xn-f(xn)/f '(xn)
Note that the second function is the first order derivative of the first one.
How the first order derivative looks depends on the exact nature of the function.
If you know what f(x) looks like, when you code the program, you can also fill in the code for the first derivative. If you have to figure it out at runtime, it looks like much more or a massive undertaking.
The following code from: http://www.ugrad.math.ubc.ca/Flat/newton-code.html
demonstrates the concept:
class Newton {
//our functio f(x)
static double f(double x) {
return Math.sin(x);
}
//f'(x) /*first derivative*/
static double fprime(double x) {
return Math.cos(x);
}
public static void main(String argv[]) {
double tolerance = .000000001; // Stop if you're close enough
int max_count = 200; // Maximum number of Newton's method iterations
/* x is our current guess. If no command line guess is given,
we take 0 as our starting point. */
double x = 0;
if(argv.length==1) {
x= Double.valueOf(argv[0]).doubleValue();
}
for( int count=1;
//Carry on till we're close, or we've run it 200 times.
(Math.abs(f(x)) > tolerance) && ( count < max_count);
count ++) {
x= x - f(x)/fprime(x); //Newtons method.
System.out.println("Step: "+count+" x:"+x+" Value:"+f(x));
}
//OK, done let's report on the outcomes.
if( Math.abs(f(x)) <= tolerance) {
System.out.println("Zero found at x="+x);
} else {
System.out.println("Failed to find a zero");
}
}
}