I need to generate a program that generates the Fibonacci Sequence
Here is what I have so far:
import java.util.Scanner;
public class FibonacciRunner
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.println("Enter n:");
int n = in.nextInt();
EP64 fg = new EP64();
for (int i = 1; i <= n; i++)
System.out.println(fg.nextNumber());
}
}
public class EP64
{
public static void nextNumber(int n)
{
int fold1 = 1;
int fold2 = 1;
int fnew = fold1 + fold2;
fold1 = fnew;
}
}
I get an error on:
System.out.println(fg.nextNumber());
saying:
method nextNumber in class EP64 cannot be applied to given types:
required: int
found: no arguments
reason: actual and formal argument lists differ in length
and can someone also tell me if I am doing this program right? If not, help! I looked at other similar questions but I cannot make much sense of them
Thank you all!
method nextNumber in class EP64 cannot be applied to given types: required: int found: no arguments reason: actual and formal argument lists differ in length
Your
public static void nextNumber(int n)
^^^^^^^
says that any call to the method must provide an integer as argument. But here:
System.out.println(fg.nextNumber());
^^ you need to add an integer argument
you violate this by providing no argument.
As your code reads now, I'd probably drop the int n argument.
and can someone also tell me if I am doing this program right?
Naah, not really...
fold1 and fold2 should probably be member variables (so they don't get reset in every call to the method),
You're forgetting to update fold2 (you only update fold1),
Also, you probably want to return an int from the nextNumber method.
Read up on
Official Java Tutorial: Defining Methods
You are calling a static method to a object reference instead of the class itself.
And
Not passing any argument at all for nextNumber() method.
Make the method non-static as :
public void nextNumber(int n) {}
Pass arg to the method as :
for (int i = 1; i <= n; i++)
System.out.println(fg.nextNumber(n));
And also don't forget to return the processed number from your nextNumber method,which you collecting in System.out.println.
Your declaration of nextNumber says it takes an int argument, but you are calling it with no arguments.
Also, your code isn't going to do what you want. You probably should make fold1 and fold2 members of class EP64 and make the method an instance method rather than a static method. You also need to do fold2 = fold1; before you update fold1.
Finally, you need to declare nextNumber to return an int value, and then actually have it return an int value.
You have two problems. Firstly, your method doesn't return anything, i.e. it is void. You need to make it int and add a return fnew; at the end. The other problem is you are starting from scratch every time, it will return 2 each time. You need to make fold1 and fold2 fields by moving them above the nextNumber line. Oh, and drop the int n argument as it doesn't do anything.
I agree on the diagnostics of the other posts, but don't suggest a member variable, but a rename and local variables.
You can ask for the 5th Fibonacci-Number with 5 calls to
fib.next ();
or with a single call to
fib (5);
Since the fibonacci-sequence increases very rapidly, you have very few calls (54) before hitting the overflow boundary. So if you repeatedly recalc the same sequence, to print the sequence, it's not a big problem. A recursive solution would be fine.
Btw.: EP64 is a very bad name.
I think this is enough:
import java.util.Scanner;
public class Fibnocci
{
public static void main(String []abc)
{
int a=0,b=1,c;
Scanner in=new Scanner(System.in);
System.out.print("Enter the Range: ");
int n= in.nextInt();
System.out.print(a+" "+b);
for(int i=0;i<n-2;i++) //n-2 because we are showing 0,1 initially.
{
c=a+b;
System.out.print(" "+c);
a=b;
b=c;
}
}
}
If you want to call this as a method then:
import java.util.Scanner;
public class Fibnocci
{
public static void main(String []abc)
{
Scanner in=new Scanner(System.in);
System.out.print("Enter the Range: ");
int n= in.nextInt();
callFibonocci(n);
}
public static void callFibonocci(int n)
{
int a=0,b=1,c;
System.out.print(a+" "+b);
for(int i=0;i<n-2;i++) //n-2 because we are showing 0,1 initially.
{
c=a+b;
System.out.print(" "+c);
a=b;
b=c;
}
}
}
You can call this method out of the class;
// Fibnocci Using c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CodeProject
{
class FibnocciSeries
{
public int[] FibonacciArray(int length)
{
int[] fseries = new int[length];
fseries[0] = 0;
fseries[1] = 1;
if (length == 0)
return null;
//Iterating through the loup to add adjacent numbers and create the memeber of series
for (int i = 2; i < length; i++)
{
fseries[i] = fseries[i - 1] + fseries[i - 2];
}
return fseries;
}
}
}
////////////////////
class Program
{
static void Main(string[] args)
{
FibnocciSeries fb = new FibnocciSeries();
Console.WriteLine("Please Enter Integer Length of Fibnocci series");
int length = Convert.ToInt32(Console.ReadLine());
int[] result = fb.FibonacciArray(length);
foreach(int i in result)
Console.Write(i.ToString()+ " ");
Console.ReadLine();
}
}
|
Related
Im having a problem. when i write for example "18" in the console, it just prints "0". I also want to know how i am able to print all the instance variables when i create a new car object. Thanks a lot.
public class mad {
public static void main(String[] args) {
java.util.Scanner tastatur = new java.util.Scanner(System.in);
int answer = tastatur.nextInt();
car carA = new car();
carA.createCar(answer);
System.out.println(carA.number);
}
}
class car {
int number;
void createCar(int n) {
n = number;
}
}
You wrote "n = number" instead of "number = n"
Should be this:
void createCar(int n) {
this.number = n;
}
For printing all instance variables, see this: printing all variables
Your assignment in the class car is the opposite of what you wanted to do. You're assigning the field number (which is always 0) to the parameter n. What you wanted to do is assigning the parameter n to the field number.
So the solution is to replace
n = number;
with
number = n;
By the way: By convention class names should start with a capital letter.
In your car class, you're currently doing this:
int number;
void createCar(int n) {
n = number; // you're assigning n to the value of number
}
Switch those around so it reads:
int number;
void createCar(int n) {
this.number = n; // now you're assigning number to the value of n
}
In constructor line n = number; should be number = n;.
You are getting 0 because instance variables are initialized bt 0 or equivalent by default.
To print all variables you must have to define a function to do so. Best way is to override toString() method of Object class.
I'm getting a compile error when I try to get matrix Size. I know nothing is wrong with the main method as my instructor told us not to change it. So I'm guessing something is wrong with getMatixSize method. Compiler computation of the program:
error: method getMatrixSize in class TesterProject cannot be applied
to given types;
import java.util*; is already inputted in the program.
public class TesterProject
{
public static void main(String [] args)
{
int n = getMatrixSize();
int[][] m = makeAndFillMatrix(n);
printMatrix(m);
}
public static int getMatrixSize(int n)
{
Scanner S = new Scanner(System.in);
System.out.println("give me a int to create the matrix");
int n = S.nextInt();
return n;
}
}
You are trying to call int n = getMatrixSize(); with no arguments, but your method public static int getMatrixSize(int n) accepts an integer as argument. That's the reason you are getting an error.
Remove int n from parameter of getMatrixSize() and your code will work fine.
This is because getMatrixSize takes an int as an argument, and you aren't giving it that.
int n = getMatrixSize(5); //pass some int
Also, in your getMatrixSize, n is already declared.
public static int getMatrixSize(int n)
{
Scanner S = new Scanner(System.in);
System.out.println("give me a int to create the matrix");
int n = S.nextInt(); //error, n is already declared in the arguments.
return n;
}
or remove the argument and fix it all:
public static int getMatrixSize() // removed argument
I have declared a default and a parameterize constructor. Using a single object I am calling both the constructor and an function. When I run the program I am getting the output as 0 instead of getting the factorial. I have initialize f=1 still the output is 0.
class Factorial
{
int num, f;
Factorial()
{
f = 1;
}
Factorial(int n)
{
num = n;
}
public int getFactorial()
{
for(int i = 1; i <= num; i++)
{
f = f * i;
}
System.out.println("Factorial= " + f);
return f;
}
public static void main(int m)
{
Factorial obj = new Factorial();
obj = new Factorial(m);
obj.getFactorial();
}
}
This is because the initial value of f remains zero when the class is initialized with the factorial(int n) constructor.
Set f to 1 in the initializer to fix this problem:
int n, f = 1;
Factorial() {
}
Factorial(int n) {
num = n;
}
This leaves your class with a big problem: calling getfactorial multiple times will change the state of the class, increasing the value of the factorial. You can fix this by creating a boolean variable that indicates whether the factorial has been computed or not, and returning f after the computation has been performed.
If you do not need "lazy" computation, make f a local variable in the method.
As a good practice, a variable should have the minimal possible scope (preferred local, then instance). Or in other words: state variables should be used just when you want to share some date between several methods of the same class. But what in your case? Factorial is an operation that may be computed in just one step, from one single parameter: No need to further processing.
So, I recommend you to refactorize your class to:
Drop off the state variables: Convert them to local variables or parameters to the method.
Set the factorial method as static (precisely because it does not need state variables).
Another small detail: Parameters are passed from command line to the main method through an array of Strings - always.
Leave all the inputs and outputs to/from the user in just one method, preferrably the main method.
So it will remain like this:
class Factorial
{
public static int getFactorial(int num)
{
int f=1;
for (int i = 1; i <= num; i++)
{
f = f * i;
}
return f;
}
public static void main(String[] args)
{
int m=Integer.parseInt(args[0]);
int factorial=Factorial.getFactorial(m);
System.out.printf("factorial of %d is %d\n", m, factorial);
}
}
Much simplier, isn't it?
The code given below is giving the following error:- non-static method compute(int) cannot be referenced from a static context
If i cannot create a method inside main(), what should i do.
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
Scanner key = new Scanner(System.in);
int t = key.nextInt();
for(int i=0;i<t;i++){
int a = key.nextInt();
int b = key.nextInt();
a=compute(a);
b=compute(b);
System.out.println(a+b);
}
}
int compute(int a){
int basea=0, digit;
int temp=a;
while(temp>0){
digit = temp%10;
temp/=10;
if(digit>(basea-1))basea=digit+1;
}
temp=a;
a=0;
int count=0;
while(temp>0){
digit = temp%10;
temp/=10;
a+=digit*Math.pow(basea,count);
count++;
}
return a;
}
You have two options:
Declare compute() static:
static int compute(int a){
Create an instance of IdeOne and call compute() via that reference:
IdeOne ideOne = new IdeOne();
a = ideOne.compute(a);
I think it would be a good idea to read through the Java tutorials on classes and objects.
You're trying to call a non-static method (which is compute) from a static method (the main).
Change int compute(int a){ with static int compute(int a){
In your case make method compute static. Otherwise create an Ideone object and call your method on it.
You can not access non-static method from static method.
Method you are trying access is instance level method, you can not access instance method/variable without class instance.
You can't access something that doesn't exist. By default non-static method doesn't exist yet, until you create object of that class in which method exist. A static method always exists.
You can access your method by following way :
1. Make your compute() method static
int compute(int a){
///rest of your code
}
2. Create instance of your class Ideone and access method by class object.
IdeOne obj = new IdeOne();
obj.compute(a);
obj.compute(b);
The answers given here are mainly to make the method static, which is fine for a program this size. However, as projects get bigger not everything will be in your main anymore, and thus you get this static/non-static issue on a larger scale as your other classes won't be static.
The solution then becomes to make a class for your Main, as such:
public class Main {
public static void main( String[] args ) {
Ideone ideone = new Ideone();
Then another file which houses your class Ideone:
public class Ideone {
Scanner key;
public Ideone() {
key = new Scanner(System.in);
int t = key.nextInt();
for(int i=0;i<t;i++){
int a = key.nextInt();
int b = key.nextInt();
a=compute(a);
b=compute(b);
System.out.println(a+b);
} // end constructor
int compute(int a){
int basea=0, digit;
int temp=a;
while(temp>0){
digit = temp%10;
temp/=10;
if(digit>(basea-1))basea=digit+1;
}
temp=a;
a=0;
int count=0;
while(temp>0){
digit = temp%10;
temp/=10;
a+=digit*Math.pow(basea,count);
count++;
}
return a;
} // end compute
} // end class
As for your main file. What I do will work, but better practice is to follow the code example given here:
http://docs.oracle.com/javase/tutorial/uiswing/painting/step1.html
Applying this practice will ensure that you do not have static/non-static issues anywhere in your project, as the only thing that is static is the initialization of your actual code, which then handles all codes / further initilization of other classes (which is all non-static)
I have a problem with my code, in that it keeps saying that the constructor is undefined. I already read somewhere that I need to declare the constructor with no arguments. I just don't know how to do that.
If someone could help, I am new at java and programming. My code is below:
import java.util.*;//import library
class Input
{
public Input (int size,int startV,int endingV)
{
//declarations of variables
double difference;
double[] array= new double[size];
array[0]=startV;
//calculating the difference to add on each number in the array
difference=(endingV-startV)/size;
for (int counter=1;counter<size;counter++) //for loop to fill the array
{
array[counter]=array[counter-1] + difference;
}
}
public Input enter(int size,int startV,int endingV)
{
//declarations of variables
double difference;
double[] array= new double[size];
array[0]=startV;
//calculating the difference to add on each number in the array
difference=(endingV-startV)/size;
for (int counter=1;counter<size;counter++) //for loop to fill the array
{
array[counter]=array[counter-1] + difference;
}
return this;
}
}
class Show
{
public Show (int size,double[] array)
{
for (int i=0;i<size;i++) //for loop to print the array
System.out.println("This is the array " + i+ ": " + array[i]);
}
public Show print(int size,double[] array)
{
for (int i=0;i<size;i++) //for loop to print the array
System.out.println("This is the array " + i+ ": " + array[i]);
return this;
}
}
public class Assignment2
{
public static void main(String[] args)
{
//declaring variables
int startV,endingV;
int size=0;
System.out.print("Give the size of the array:");//Print message on screen
size = new Scanner(System.in).nextInt();//asking for the size of array
double[] array= new double[size]; //creation of array
System.out.print("Give the starting value of the array:");
startV = new Scanner(System.in).nextInt();//asking for the starting value of array
System.out.print("Give the ending value of the array:");
endingV = new Scanner(System.in).nextInt();//asking for the last value of array
//calling the functions from the other classes
Input enter= new Input(size,startV,endingV);
Show print= new Show(size,array);
}
}
You're close:
You have a method:
public Method enter(int size,int startV,int endingV) {
to make it a constructor it's signature must be
public Method (int size,int startV,int endingV) {
and you then have to delete the return this; statement.
Remember, constructors don't have a return type and their name is identical to the name of the class. With this information, you'll also be able to fix the Method1 constructor.
Also, please respect the Java naming conventions and have variables start with a lower-case letter to improve the readability of your code.
You need to create a
public Method(size,startV,endingV)
not
public Method enter = (size, startV, endingV)
The first is a constructor the second is a method
For class Method
the default constructor will be
public Method(){}
For class Method1
the default constructor will be
public Method1(){}
in your classes there are no constructors as the
constructor name must be will the same as class name.
enter(int size,int startV,int endingV)
and
print(int size,double[] array)
can be two methods in your classes.
also your two constructor can be -
public Method(int size,int startV,int endingV){ /..../}
and
public Method1(int size,double[] array){ /..../}
Your constructor must have the same name than your class and has no return type. So for your class Method, your constructor will simply be :
public Method(int size, int startV, int endingV)
{
// code...
}
Please also note that constructors exist to initialize your instances of objects, if you want to create a method that does a specific calcul, then yes, you'll have to do :
public int enter(int size, int startV, int endingV)
{
int result = 0;
// code to calculate, for example result = size + startV + endingV ...
return result;
}