JAVA Greatest common divisor recursion - java

I can't get this to run.There is a tester program and a method below. it says error identifier expected.Thanks in advance
public class 121tester{
public static void main(String[]args){
Scanner input= new Scanner(System.in)
System.out.println("Enter first number");
int num1=input.nextInt();
System.out.println("Enter second number");
int num2=input.nextInt();
System.out.println("The Greatest common factor of "+num1+" "+num2+" is "+GCD(num1,num2));
}
}
private static int GCD(int num1, int num2){
if(num2==0){
return num1;
}
return(GCD(num2, num1%num2);
}

Class name can't start with number. Change from
class 121tester
to
class Tester121
Another thing your GCD method should declare into inside class. It is better to use some IDE at initial stage of programming to remove compiler error.

Try the following:
import java.util.Scanner;
public class GCDTester{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.println("Enter first number");
int num1 = input.nextInt();
System.out.println("Enter second number");
int num2 = input.nextInt();
System.out.println("The greatest common factor of " + num1 + " " + num2 + " is " + gcd(num1,num2));
}
private static int gcd(int num1, int num2){
if (num2 == 0) {
return num1;
}
return gcd(num2, num1 % num2);
}
}
But #Masud is correct, you should place the gcd method in a class of its own so that it can be used as an object in its own right.

Related

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.

How do I use a function involving integers?

We have an assignment in class to create a greatest common divider (gcd) program using functions. I missed out on the lesson where we learned how to properly use them. I finished the part that actually does the division but I don't know how to separate it into a function and have it work. I'd like to have the input in the main class and the process in function.
This is what I have, it does not work when I run it
package gcd.function.java.program;
import java.util.Scanner;
/**
*
* #author sarah_000
*/
public class GCDFunctionJavaProgram {
public static void main(String[] args) {
int num1;
int num2;
int div;
Scanner input = new Scanner(System.in);
System.out.print("Enter your first number: ");
num1 = input.nextInt();
System.out.print("Enter your second number: ");
num2 = input.nextInt();
System.out.printf("The GCD is %d ", div);
}
public static void GCDFunction() {
if(num1 > num2)
div = num2;
else div = num1;
while((num1 % div!= 0)||(num2 % div != 0))
{
div --;
}//end of while loop
}
}
Any tips or help you can give to me will be greatly appreciated, I'm very new
You declare two parameters and modify the return type in your GCDFunction like this:
public static int GCDFunction(int num1, int num2)
You are currently trying to access the variables in the main method but are out of scope.
Also, you never actually call your GCDFunction
Think of it like passing functions in math. The GCDFunction() has to receive the numbers into the function so we do
public static void GCDFunction(int num1, int num2)
That also lets Java know the type it is, type int. And your java variables are scoped inside of the functions so you have to print the output in the function that created the variable in your scenario.
So once you have that function set up to receive the variables and output after processing, you call the function in the main with a
GCDFunction(num1, num2);
Where num1 and num2 are the variables that have your integers stored in.
The end result after a little rearranging looks like this.
import java.util.Scanner;
public class GCDFunctionJavaProgram {
public static void main(String[] args) {
int num1;
int num2;
Scanner input = new Scanner(System.in);
System.out.print("Enter your first number: ");
num1 = input.nextInt();
System.out.print("Enter your second number: ");
num2 = input.nextInt();
GCDFunction(num1, num2);
}
public static void GCDFunction(int num1, int num2) {
int div;
if(num1 > num2){
div = num2;
}
else{ div = num1;}
while((num1 % div!= 0)||(num2 % div != 0))
{
div --;
}//end of while loop
System.out.printf("The GCD is %d ", div);
}
Trying to give you a example of how the code should be to take in variable number of parameters.
public int gcd(Integer... numbers) {
int gcd = 1;
int miNNumber=Collections.min(Arrays.asList(numbers));
boolean isDivisible;
for(int i=2; i<=miNNumber;i++) {
isDivisible=true;
for(Integer eachNumber : numbers) {
if(eachNumber%i!=0) {
isDivisible=false;
break;
}
}
if(isDivisible) {
gcd=i;
}
}
return gcd;
}
You can call it
gcd(10, 200, 400);
or
gcd(10, 200, 400, 4000, 40);

Method returning max Value not working

I'm confused on what I'm doing wrong here. Anyone care to explain? It compiles and runs but I keep getting an error at line 50 which is the return line.
Also if I change the code below to "int max = (number1, number2) " i get the can not find symbol error. Any help will be greatly appreciated.
int max = max(num1, num2);
import java.io.*;
import java.util.Scanner;
public class MethodLab {
public static void main(String[] args) {
// variable declarations for part 1
String title;
String firstName;
String lastName;
Scanner in = new Scanner(System.in);
// prompt for input for part 1
System.out.print("Enter a title:");
title = in.next();
System.out.print("Enter your first name:");
firstName = in.next();
System.out.print("Enter a your last name:");
lastName = in.next();
// call the method for part 1
greeting(title, firstName, lastName);
// variable declarations for part 2
int number1;
int number2;
// user prompts for part 2
System.out.print("Enter first number:");
number1 = in.nextInt();
System.out.print("Enter second number:");
number2 = in.nextInt();
// call the method for part 2 inside the println statement
System.out.println("The largest number is " + max(number1, number2));
}
/******************** greeting method goes here*********************/
public static void greeting(String proper, String fname, String lname){
System.out.println();
System.out.printf("Dear " + proper +" "+ fname + " "+ lname);
System.out.println();
}
/***********************end of method*************************/
/******************** max method goes here*********************/
public static int max(int num1,int num2){
int max = max(num1, num2);
return max;
}
Use int max = Math.max(num1, num2) this will return the max number.
public static int max(int num1,int num2){
int max = max(num1, num2);
return max;
}
This method would never complete. This is going to call max again and again until you run out of stack space. And when you do, it throws a stack overflow error. You should change it to
public static int max(int num1,int num2){
int max = num1>num2?num1:numb2; // return the highest number.
return max;
}
EDIT: Since you mentioned that you are new to programming, let me add few more detail. If you are in a method A and you call a method B, some amount of space in the stack segment is reserved so that the control knows the line location in method A to resume execution after completing method B. In your case, the max method calls max method again and again. This directly means that more and more space in stack segment gets reserved for each method call. And at some point, it runs out of available space in stack memory and you would end up with such StackOverflow problem.
In general, any method calling itself without modifying the inputs is a red flag in most scenario. This is the case with your max method.
In your max(int num1, int num2) there is no logic, it's just calling itself so will never end:
use like below:
import java.io.*;
import java.util.Scanner;
public class MethodLab {
public static void main(String[] args) {
// variable declarations for part 1
String title;
String firstName;
String lastName;
Scanner in = new Scanner(System.in);
// prompt for input for part 1
System.out.print("Enter a title:");
title = in.next();
System.out.print("Enter your first name:");
firstName = in.next();
System.out.print("Enter a your last name:");
lastName = in.next();
// call the method for part 1
greeting(title, firstName, lastName);
// variable declarations for part 2
int number1;
int number2;
// user prompts for part 2
System.out.print("Enter first number:");
number1 = in.nextInt();
System.out.print("Enter second number:");
number2 = in.nextInt();
// call the method for part 2 inside the println statement
System.out.println("The largest number is " + max(number1, number2));
}
/******************** greeting method goes here*********************/
public static void greeting(String proper, String fname, String lname){
System.out.println();
System.out.printf("Dear " + proper +" "+ fname + " "+ lname);
System.out.println();
}
/***********************end of method*************************/
/******************** max method goes here*********************/
public static int max(int num1,int num2){
return num1 > num2 ? num1 : num2;
}

javax.swing.JComponent cannot be resolved

I'm a beginner at Java programming. I encountered an error -
javax.swing.JComponent cannot be resolved whenever I execute the following program.
import javax.swing.JOptionPane;
class apples
{
public static void main(String args[])
{
String a = JOptionPane .showInputDialog("Enter a number");
String b = JOptionPane.showInputDialog("Enter another number");
int num1 = Integer.parseInt(a);
int num2 = Integer.parseInt(b);
int sum = num1 + num2;
JOptionPane.showMessageDialog(null,"Sum is "+sum, Answer,JOptionPane.PLANE_MESSAGE);
}
}
Can anyone please suggest a solution?
public static void main(String[] args) {
String a = JOptionPane .showInputDialog("Enter a number");
String b = JOptionPane.showInputDialog("Enter another number");
int num1 = Integer.parseInt(a);
int num2 = Integer.parseInt(b);
int sum = num1 + num2;
JOptionPane.showMessageDialog(null,"Sum is "+sum, "Answer",JOptionPane.PLAIN_MESSAGE);
}
You were using incorrect JOptionPane. You need to use PLAIN_MESSAGE instead of PLANE_MESSAGE. Also the Answer field which is the title needs to be a string
I suggest using an IDE like eclipse or netbeans so that you can avoid such issues.

Why do I get a DivideByZeroException in my Java code?

import java.io.IOException;
import java.util.*;
public class calling {
public static String s;
public static String t;
public static int y;
public static int x;
public static int num1() {
int x;
Scanner scanner = new Scanner (System.in);
System.out.println("Please enter a number called x: ");
x=scanner.nextInt();
return x;
}
public static int num2() {
int y;
Scanner scanner = new Scanner (System.in);
System.out.println("Please enter a second number called y: ");
y=scanner.nextInt();
return y;
}
public static void calculation() {
Scanner input = new Scanner(System.in);
System.out.println("What process would you like to do? *, /, + or - ?");
s=input.next();
if (s.equals("*")) {
System.out.println("\nThe product of these numbers is:" + (x*y));}
else
if (s.equals("+")) {
System.out.println("\nThe sum of these numbers is: " + (x+y));}
System.out.println("\nDo you want x or y to be the dividor/subtractor?: ");
t=input.next();
if (t.equals("y") || t.equals("Y") ) {
if (s.equals("/")) {
System.out.println("\nThe quotient of these numbers is: " + (x/y));}
else
if (s.equals("-")) {
System.out.println("\nThe difference of these numbers is: " + (x-y));}}
else
if (t.equals("x") || t.equals("X")){
if (s.equals("/")) {
System.out.println("\nThe quotient of these numbers is: " + (y/x));}
else
if (s.equals("-")) {
System.out.println("\nThe difference of these numbers is: " + ((y-x)));}}
}
public static void main (String [] args) throws IOException {
num1();
num2();
calculation();
}
}
i keep getting this error in what should be my final result which is simply the result of the calculations being performed
this is the error:" Exception in thread "main" java.lang.ArithmeticException: / by zero
at calling.calculation(calling.java:44)
at calling.main(calling.java:64)"
Since this is likely homework, I'll give you a hint to point you in the right direction.
When you run your program, you execute num1 and num2 to collect the values of x and y from the user. Within num2, y is declared as a local variable. What happens to that variable when num2 returns? And what does that imply for the class field (variable) y declared on line 7?
This is also a good time to learn how to use a debugger. Put a breakpoint on line 44, and see what the values of x and y are.
You need to make sure that the:
int x;
int y;
are the ones you want. Integer's default to zero when static.

Categories

Resources