recursive method multiplying without using operator - java

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));
}

Related

Little coding challenge (Fermat’s Last Theorem)

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!

Method not getting invoked

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.

Fraction adding java program not working right

Having trouble with this final program for my Java class. We have to only use concepts we have learned so far so I cannot use other classes. Basically just loops and arrays and methods.
So for this program we have to add any five sets of fractions entered and give the GCD and the results in the lowest form. I have to show all data in the first table and then a second table with the original data and the GCD and the results in the lowest form. It has to be tested with this data:
1/4 + 1/2
2/3 + 1/3
7/8 + 1/8
2/9 + 4/27
7/25 + 2/5
Here is the code I have so far. (Be gentle, I'm still new at this)
import java.util.Scanner;
public class HelloWorld{
public static void main(String[] args) throws Exception{
int[] num1Array = new int[5];
int[] num2Array = new int[5];
int[] deno1Array = new int[5];
int[] deno2Array = new int[5];
Scanner input = new Scanner(System.in);
for(int x=0;x<5;x++) { //Get all data from user
System.out.println("Enter data for problem " + (x+1));
System.out.println("Enter numberator for fraction 1");
num1Array[x] = input.nextInt();
System.out.println("Enter denominator for fraction 1");
deno1Array[x] = input.nextInt();
System.out.println("Enter numberator for fraction 2");
num2Array[x] = input.nextInt();
System.out.println("Enter denominator for fraction 2");
deno2Array[x] = input.nextInt();
System.out.println("********************");
}
System.out.println("*****ORIGINIAL DATA ******"); //Output all entered data
System.out.println("First Fraction \t Second Fraction");
for(int y=0;y<5;y++) {
System.out.printf("%1d/%1d \t\t %1d/%1d\n", num1Array[y], deno1Array[y], num2Array[y], deno2Array[y]);
}
System.out.println("*******FRACTIONS SHOWING ADDED RESULTS*********"); //Display results
System.out.println("First Fraction \t Second Fraction GCD Results");
for(int z=0;z<5;z++){
int finalgcd = gcdfinal(num1Array[z], num2Array[z], deno1Array[z], deno2Array[z]);
int addFrac = fracAdd(num1Array[z], num2Array[z], deno1Array[z], deno2Array[z]);
System.out.printf("%1d/%1d \t\t %1d/%1d\t\t %1d \t %1d", num1Array[z], deno1Array[z], num2Array[z], deno2Array[z], finalgcd, addFrac);
System.out.println();
}
}
public static int fracAdd(int num1, int num2, int deno1, int deno2)
{
int e = lcm(deno1, deno2); //denominator
int f1 = e / deno1;
int f2 = e / deno2;
int g1 = num1 * f1;
int g2 = num2 * f2;
int adding = g1 + g2;
int k = gcd(adding, e);
int final_num = adding / k;
int final_deno = e / k;
if(final_num == final_deno){
return 1;
}
else {
return (final_num, final_deno);
}
}
public static int gcd(int a, int b) //Calculate GCD
{
while (b > 0)
{
int temp = b;
b = a % b;
a = temp;
}
return a;
}
public static int gcdfinal(int num1, int num2, int deno1, int deno2)
{
int e = lcm(deno1, deno2); //Calculate the GCD for display
int f1 = e / deno1;
int f2 = e / deno2;
int g1 = num1 * f1;
int g2 = num2 * f2;
int end = g1 + g2;
int k = gcd(end, e);
return k;
}
public static int lcm(int a, int b) //Calculate LCM
{
return a * (b / gcd(a, b));
}
}
How can I approach doing this? Am I on the right track?
Try with this, hopefully it helps you. :)
import java.util.Scanner;
public class AddingFraction {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
System.out.println("please enter a fraction number in a/b format: ");
String fraction1 = sc.nextLine();
System.out.println("please enter another fraction number in a/b format: ");
String fraction2 = sc.nextLine();
addFractions(fraction1, fraction2);
}
public static void addFractions(String fractionNum1, String fractionNum2) {
int numResult = 0;
String resultFraction;
String[] frcNum1 = fractionNum1.split("/");
int numerator1 = Integer.parseInt(frcNum1[0]);
int Denomenator1 = Integer.parseInt(frcNum1[1]);
String[] frcNum2 = fractionNum2.split("/");
int numerator2 = Integer.parseInt(frcNum2[0]);
int Denomenator2 = Integer.parseInt(frcNum2[1]);
if (Denomenator1 == Denomenator2) {
numResult = numerator1 + numerator2;
resultFraction = numResult + "/" + Denomenator1;
System.out.println("Resultant Fraction is : "+resultFraction);
} else {
int denLcm = Denomenator1 * (Denomenator2 / gcd(Denomenator1, Denomenator2));;
numResult = numerator1 * (denLcm / Denomenator1) + numerator2
* (denLcm / Denomenator2);
resultFraction = numResult + "/" + denLcm;
System.out.println("Resultant Fraction is : "+resultFraction);
}
}
private static int gcd(int a, int b) {
while (b > 0) {
int temp = b;
b = a % b; // % is remainder
a = temp;
}
return a;
}
}

Runtime error. Java. Create a class, Sort that displays four integer numbers in increasing order

I am new in programming, just 1 month. I should create a class, Sort that displays four integer numbers in increasing order. I learned something from here. Unfortunately, this program doesn't run, when compiling there is no error. The error message looks like this:
stderr
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:907)
at java.util.Scanner.next(Scanner.java:1530)
at java.util.Scanner.nextInt(Scanner.java:2160)
at java.util.Scanner.nextInt(Scanner.java:2119)
at Sort.main(Main.java:9)
Here is program:
import java.util.Scanner;
class Sort
{
public static void main (String[] args) {
int a,b,c,d;
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter four numbers: ");
a = keyboard.nextInt();
b = keyboard.nextInt();
c = keyboard.nextInt();
d = keyboard.nextInt();
if (a>b) {
int temp = a;
a = b;
b = temp;;
}
if (b>c) {
int temp = b;
b = c;
c = temp;
}
if (c>d) {
int temp = c;
c = d;
d = temp;
}
if (a>b) {
int temp = a;
a = b;
b = temp;
}
if (b>c) {
int temp = b;
b = c;
c = temp;
}
if (a>b) {
int temp = a;
a = b;
b = temp;
}
System.out.println("The numbers :" + a + " " + b + " " + c + " " + d);
}
}
NoSuchElementException will be thrown if input is exhausted, i.e. the nextInt() method has no int to return. To fix this you can check if the scanner has more ints with hasNextint() before you call nextInt(). This should get rid of the error, I believe however that this is due to the program not reading all input so maybe should rewrite the input part.

How can I return a statement in this program correctly?

I want my program to execute the first return statement if the conditions are true otherwise return it as normal.
import java.util.Scanner;
public class Untitled {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int x = input.nextInt();
int y = input.nextInt();
int answer = x + y;
if (x == y) {
System.out.println("These two numbers are the same and they equal: " + answer);
return answer;
}
System.print.ln("These two numbers are not the same, but they equal: " + answer);
return answer;
}
}
Well, in your code you don't need to return anything.
But, if you want to return something you are in the wrong method.
main is a "special" method, it cannot return anything (well, in other languages it might return an int which is the exit status, but ignore it here) and is where your code starts.
If you want to return something you should write a method.
A method is a block of code which is execute when you call it and can return value back to who called it. In this case your method will be static because you will call it from the main method which is static
public static int methodName()
{
int X, Y;
int answer;
if (x == y)
{
// Do something
return returnSomethingBackTomain;
}
else
{
return returnSomethingOfDifferentTomain;
}
}
Well.. it could be your method
public static int methodName()
{
Scanner input = new Scanner(System.in);
int x = input.nextInt();
int y = input.nextInt();
int answer = x + y;
if (x == y) {
System.out.println("These two numbers are the same and they equal: " + answer);
}
else {
System.out.println("These two numbers are not the same, but they equal: " + answer);
}
return answer;
}
But please be more specific on what you want to do.
Because i dont see any reason to write a such method.
If your main function is void, you don't have to return anything, you can just use
return;
That gives:
import java.util.Scanner;
public class Untitled {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int x = input.nextInt();
int y = input.nextInt();
int answer = x + y;
if (x == y) {
System.out.println("These two numbers are the same and they equal: " + answer);
return;
}
System.print.ln("These two numbers are not the same, but they equal: " + answer);
}
}
But you can also do:
...
if (x == y) {
System.out.println("These two numbers are the same and they equal: " + answer);
} else {
System.print.ln("These two numbers are not the same, but they equal: " + answer);
}
}
}
import java.util.Scanner;
public class Untitled {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int x = input.nextInt();
int y = input.nextInt();
int answer = x + y;
if (x == y)
System.out.println("These two numbers are the same and they equal: " + answer);
else
System.print.ln("These two numbers are not the same, but they equal: " + answer);
}
}
main has a void return type, so no need to return anything.
By the way, try to fit CQS principle.
Indeed, printing something is a side-effect operation, so no need to return anything but void.
You're making a few mistakes.
The main method should never be used to return a value.
The main method is the entry point to your program.
Here you declare methods to be run at the start of the program. In GUI-projects, this is used to load the inital GUI (Forms).
Also, a void method cannot return something.
When initalising a method, you have to declare what type the returned value will have.
Void means that there is no data returned.
You will have to write a method which you can call to receive your data.
import java.util.Scanner;
public class Untitled {
public int scanForEqualNumbers() {
Scanner input = new Scanner(System.in);
int x = input.nextInt();
int y = input.nextInt();
int answer = x + y;
if (x == y) {
System.out.println("These two numbers are the same and they equal: " + answer);
return answer;
}
return answer;
}
Now you can initalize your class (e.g. Scanner) and call the method scanForEqualNumbers.
Scanner scanner = new Scanner();
int result = scanner.scanForEqualNumbers();
If you don't want to have to initialize a class to call the method, you can declare the scanForEqualNumbers as static.
public static int scanForEqualNumbers() { ...
Then you can call this method directly as this:
int result = Scanner.scanForEqualNumbers();
1 more note.
You don't need the return in the IF-statement.
As you return the answer anyway, you can keep the print the the IF-statement and use the return after it.
You could also return -1 as answer in an ELSE-statement so you can use this answer in further methods. This way you can check the result of the method without having to read the console output.
I even suggest to make a seperate class for this.
You'll need your Main-method to run your program. This'll also be the location of your method class.
public class MyApp {
public static void main(String[] args) {
MyScanner myScanner = new MyScanner();
int result = myScanner.scanForEqualNumbers();
System.out.format("The scanned numbers %s equal", result > 0 ? "ARE" : "are NOT");
}
}
public class MyScanner {
import java.util.Scanner;
public class Untitled {
public int scanForEqualNumbers() {
Scanner input = new Scanner(System.in);
int x = input.nextInt();
int y = input.nextInt();
/* This can be replaced, see below
int answer = x + y;
if (x != y) {
answer = -1;
}
return answer;
*/
// IF X equals Y ? return X + Y : ELSE return -1
return (x == y ? x + y : -1);
}
}

Categories

Resources