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);
Related
I have written the following Java program:
Tab1:
package base;
import java.util.Scanner;
public class Main {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner obj = new Scanner(System.in);
System.out.println("Enter first number: ");
int num1 = obj.nextInt();
System.out.println("Enter the second number: ");
int num2 = obj.nextInt();
Add obj1 = new Add();
Mul obj2 = new Mul();
obj1.getData(num1, num2);
int add = obj1.addition();
int mul = obj2.multiplication();
System.out.println("The addition of the two numbers is: " +add);
System.out.println("The multiplication of the two numbers is: " +mul);
}
}
Tab2:
package base;
public class Parent {
int num1, num2;
void getData(int x, int y){
num1 = x;
num2 = y;
}
}
Tab3:
package base;
public class Add extends Parent {
int addition(){
int x;
x = num1 + num2;
return x;
}
}
Tab4:
package base;
public class Mul extends Parent {
int multiplication(){
int x;
x = num1*num2;
return x;
}
}
When I run the code it gives me a result like this:
Enter first number:
5
Enter second number:
4
The addition of the two numbers is: 9
The multiplication of the two numbers is: 0
I have got the same type of result with all kind of different inputs.
The result of the multiplication is always 0
I have cross checked my code several times but apparently I cannot find any mistake.
Where am I going wrong?
Any help will be greatly appreciated.
You should pass argument to Mul instance before calling its method
obj2.getData(num1, num2);
int mul = obj2.multiplication();
There is no call to getData() on obj2:
obj2.getData(num1, num2);
Add obj1 = new Add();
Mul obj2 = new Mul();
obj1.getData(num1, num2);
You created two distinct objects, obj1 and obj2 but put non-zero values only into obj1. The values in obj2 are still zero.
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 trying to show the results from GCD and LCM using the display method. I try accessing the numbers object in the display method and it cannot resolve the symbol. Everything works with the code I'm just not sure how else I can access the numbers object inside the display method. Any help is greatly appreciated! Thanks
public static void main(String[] args) {
TwoNumbers numbers = getNumbers();
System.out.println(numbers.getNum1());
System.out.println(+numbers.getNum2());
GCD(numbers.getNum1(), numbers.getNum2());
System.out.println(GCD(numbers.getNum1(), numbers.getNum2()));
LCM(numbers.getNum1(), numbers.getNum2());
System.out.println(LCM(numbers.getNum1(), numbers.getNum2()));
}
public static TwoNumbers getNumbers(){
int num1;
int num2;
Scanner input = new Scanner(System.in);
System.out.println("Enter your first number: ");
num1 = input.nextInt();
System.out.println("Enter your second number");
num2 = input.nextInt();
return new TwoNumbers(num1, num2);
}
public static int GCD(int a, int b) {
if (b==0) return a;
return GCD(b,a%b);
}
public static long LCM(int a, int b) {
return a * (b / GCD(a, b));
}
public static void display(){
}
TwoNumbers numbers = getNumbers();
If you are trying to access numbers of main method. Then you can not do that, scope of numbers is only inside main method. You can not access it directly from other method.
Either you pass the numbers as parameter to display method or you can declare numbers as class level static variable.
public static void display(TwoNumbers numbers){
//Now you have numbers inside display
}
Moreover, you do not need to call the GCD and LCM method again from the display. You can simply pass result of both methods to display method from main.
TwoNumbers gcdNumbers = GCD(numbers.getNum1(), numbers.getNum2());
display(gcdNumbers);
TwoNumbers lcmNumbers = LCM(numbers.getNum1(), numbers.getNum2());
display(lcmNumbers);
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.
I'm trying to create a program that includes a menu and will execute whatever choice the user chooses. I completed the methods and got them to compile, but am lost on how to call the classes. Here is the code in screenshots so they're easier to read:
Geek Class: (Contains all the methods)
public class Geek{
private String name;
private int numberofQuestions=0;
public Geek (String name){
this.name = name;
numberofQuestions = 0;
}
public String getName(){
return name;
}
public int getnumberofQuestions(){
return numberofQuestions;
}
public boolean allTheSame(int num1, int num2, int num3){
numberofQuestions++;
if(num1 == num2 && num2 == num3 && num1 == num3){
return true;}
else return false;
}
public int sum (int num1, int num2){
numberofQuestions++;
int largest = Math.max(num1, num2);
int smallest = Math.min(num1, num2);
int result =0;
for (int i=smallest; i <= largest;i++){
result = result + i;}
return result;
}
public String repeat(String str, int n){
numberofQuestions++;
String repetition = "";
for (int j=0; j < n; j++){
repetition = repetition + str;}
return repetition;
}
public boolean isPalindrome(String str){
numberofQuestions++;
int n = str.length();
for( int i = 0; i < n/2; i++ )
if (str.charAt(i) != str.charAt(n-i-1)) return false;
return true;
}
}
Main:
http://i.imgur.com/DvJ0LU5.png
EDIT: Im getting a cannot find symbol error in this section of code:
case "d":
myGeek.sum(num1, num2, num3);
System.out.println("Enter the first number");
int num1 = scan.nextInt();
System.out.println("Enter the second number");
int num2 = scan.nextInt();
System.out.println("Enter the third number");
int num3 = scan.nextInt();
break;
Classes aren't called, they are blueprints for creating objects.
You need a program entry point, in this case inside your class like so
public static void main(String[] args)
{
Geek myGeekObject = new Geek("Your name");
}
you can then call the methods on your created object
public static void main(String[] args)
{
Geek myGeekObject = new Geek("Your name");
String geekName = myGeekObject.getName();
}
In Java (and any other languages I know), you can only call methods/functions, but not classes (except you count <clinit>). So you could write:
Geek geek = new Geek("Me");
int i = geek.sum(1, 2);
System.out.println(String.valueOf(i));
Assuming the file Geek.java, you can then call/run the class using:
javac Geek.java
java Geek
from the commandline.
Note that this will only succeed if Geek.java contains a main method. Read about them here.
You need to create instance of object and then you can use it
For example:
Geek g = new Geek("Geek");
g.getName();
You need to instantiate an instance of the class in order to use it.
For example, in your main method you may want to define an instance of the object like so:
Geek myGeek = new Geek("user2943817");
You can than access all instance methods on the object using the variable name like so:
myGeek.getName();
I hope this helps!
EDIT :
As for your new issue, simply call the method after you obtain the values from the user. Like this:
case "d":
System.out.println("Enter the first number");
int num1 = scan.nextInt();
System.out.println("Enter the second number");
int num2 = scan.nextInt();
System.out.println("Enter the third number");
int num3 = scan.nextInt();
myGeek.sum(num1, num2, num3);
break;
You cant use non-static class like that.
Imagine that Geek is definition of Geek. You want to create several geeks, each one is standalone instance.
Geek g1 = new Geek("Andrew");
Geek g2 = new Geek("John");
These lines create two instances g1 and g2 of type Geek with name Andrew and John
Then you access them like this :
g1.repeat("myString", 10)