I am currently taking a Java Programming class and we are on the topic of dynamic arrays. We were asked to write a program using dynamic arrays that would print out the Fibonacci Sequence.
This is what I have:
public class Fibonacci {
private static int[] data;
public static void DynamicArray() {
data = new int[1];
}
public static int get(int position) {
if (position >= data.length){
return 0;
} else {
return data[position];
}
}
public static void put(int position, int value) {
if(position >= data.length) {
int newSize = 2 * position;
int[] newData = new int[newSize];
System.arraycopy(data, 0, newData, 0, data.length);
data = newData;
}
data[position] = value;
}
public static void main(String[] args) {
System.out.println("\nFibonacci Sequence:\n");
System.out.println(data[0]);
for(int i = 2; i< = 20; i++) {
data[i] = data[i-1] + data[i-2];
System.out.println(data[i]);
}
}
}
Thanks!
Array is static because you create it with size. For dynamic, use ArrayList. ArrayList is a Array too. ArrayList has default size of 10 and growth 25%(total size) when reaching 75% total size. But it's slow because of when ArrayList reach 75%size, java will create a new Array and copy data to new one in memory. You can use LinkedList, faster for read-write data than ArrayList-faster for read data.
Does it counts as dynamic array if you use the .push() method? If it's OK you can just count the next number in Fibonacci Sequence and use MyArray.push(currentFibonacci);
In Java, Arrays are static. Once they are initialised, they can not 'grow'.
There are several data structures for solving this problem (linked lists for example).
If you want to resize an array, you'll have to create a new one with the wanted size and then copy all entrys from the old array to the new one.
Java's implementation of this kind of "dynamic array" is the ArrayList. Yet this is not very fast
I had to do the same thing don't worry its a lot simpler then you are making it look at the code I have that does what you want
import java.util.Scanner;
public class DynamicArray
{
public static void
d main (String[] args){
System.out.println("How Long Do You Want To see the Fibonacci Series?");
Scanner scan = new Scanner (System.in);
int Length = scan.nextInt();
int[] Fibonacci = new int[Length];
Fibonacci[0] = 0;
Fibonacci[1] = 1;
System.out.println("Fibonacci Series");
System.out.println(Fibonacci[0]);
for (int i = 2; i<Length; i++){
Fibonacci[i]=Fibonacci[i-2]+Fibonacci[i-1];
System.out.println(Fibonacci[i]);
}
}
}
So what is happening here is that the length variable I declared is inputted by the user determining how far the array will print the Fibonacci series it is rather simple once you know what you are trying to do. So this is what you need since this is what your teacher wants hope it helps. :D
while (sequence<4000000)
{
i++;
sequence = fibonacciSequence[0]+fibonacciSequence[1];
System.out.println(sequence);
if (i%2!=0)
{
fibonacciSequence[0]=sequence;
}
else
{
fibonacciSequence[1]=sequence;
}
if (sequence%2==0)
{
sumEvenTerm = sumEvenTerm + sequence;
}
}
#Randy thanks for your answer here. In this case, we do know the length of the fibonnaci sequence. In some cases, we do not know the length. What we know is the value of the some fibonnaci number. We can't use the above program.
You can change the value in the while loop to suit your needs.
Related
This is my first time doing Java as a part of college assignment where I have to implement Stack data structure, but the challenge is to make the code work for pushes greater than the initial array size. I am not allowed to work with ArrayList in this assignment. I can only use static array and resize when needed by copying contents to a new array and reassigning the old array as new array.
I try to achieve this using if condition which determines if the counter (which initially is 0, increases as the number of push increases) is greater than the initially defined size of the array.
Then I created a new method called stackextender where I put exceeding values in a new array called extensionstack. Then on a method mystackmodifier, I create a temparray and put contents of original stack and extensionstack in the temparray. At last i do mystack = temparray to copy the contents to my original stack. I think the code is having problem in this function (mystackmodifier),where I am modifying the contents of initial stack. The code is posted below:
public class StackOperations{
int mystack[];
int global_size;
int counter = 0;
int newcounter = 0;
int extensionstack[] = new int[counter*2];
public StackOperations(int size){
this.mystack = new int[size]; //create a stack of size as mentioned while creating object
this.global_size = size; //update the global variable
}
//the below method will allow us to calculate the number of
public void push(int value){
if (counter<global_size){
mystack[counter] = value;
counter += 1;//we have to do this unless counter < stacksize
}
else{
/*so if I have to make my code work for user input greater than my initial stack size,
I am creating a new method called stackextender where I put new value in a new array called
extension stack. Then on the method, mystackmodifier I create a temparray and put contents of
original stack and extensionstack in the temparray. At last i do mystack = temparray to
copy the contents to my original stack*/
stackextender(value);
counter ++;
}
}
//This method puts exceeding values to a new stack called extension stack
public void stackextender(int value){
extensionstack[newcounter] = value;
newcounter ++;
}
//This method modifies the contents of original stack
public void mystackmodifier(){
int temparray[] = new int[(global_size+newcounter)*2];
if(extensionstack.length>0){
int key;
for ( key = 0; key<mystack.length; key++){
temparray[key] = mystack[key];
}
for (int i = 0; i<newcounter; i++){
temparray[key+i] = extensionstack[i];
}
mystack = temparray;
}
}
Below is my main method
import java.util.*;
public class ArrayStack{
public static void main(String args[]){
StackOperations mystack = new StackOperations(100);
System.out.println(mystack.toString());
/*Although the stack size is instantiated as 10, the code works for insertion for as many
number of items as demonstrated below*/
for (int i = 0; i<150; i+=1){
mystack.push(i);
}
int stacksize = mystack.getSize();
if (stacksize == 0) {
try{
throw new NoSuchElementException();
}catch (NoSuchElementException exc){
exc.printStackTrace();
}
}
System.out.println(mystack.toString());
}
Any help will be highly appereciated
I'm trying to increase the size of a two dimensional array dynamically. However,I'm getting an Array out of Bounds error it. Below posted the code. In this scenario,I'm trying to add values dynamically to the two dimensional vector weight[][] under some condition. Any suggestions would be highly helpful!
class perceptron {
public static void main(String[] args) {
int[][] myPoints = {{2,3},{4,5},{7,8},{9,10}};
int [] classlabels = {1,1,-1,-1};
int [] [] weight = {{0,0}};
int base=0;
int i,j;
int activation=0;
for(i=0;i<myPoints.length;i++) {
for(j=0;j<classlabels.length;j++) {
activation = activation+((myPoints[i][0]*weight[i][0])+(myPoints[i]
[1]*weight[i][1]));
System.out.println("dot product of two vectors" + activation);
if((activation*classlabels[j]) <= 0) {
System.out.println("hi");
weight[i+1][0] = weight[i][0]+ (classlabels[j]*myPoints[i]
[0]);
weight [i+1][1] =weight[i][1]+(classlabels[j]*myPoints[i]
[1]);
System.out.println(weight[i+1][0]);
System.out.println(weight[i+1][1]);
base = base+classlabels[j];
System.out.println(base);
}
}
}
}
}
Java arrays are strictly fixed-size. You must use an ArrayList.
Example:
ArrayList<ArrayList<Double>> weights = new ArrayList<>();
weights.add(new ArrayList<Double>()); // extend to be 1x0
weights.get(0).add(1.2); //weights[0][0]=1.2
weights.get(0).add(2.3); // weights[0][1]=2.3
Hello I have implemented this basic program which should sort out the strings that are inserted however it somehow is failing to insert the strings .
For example if I implement :
TestSort t = new TestSort();
t.i("abc");
t.i("aab");
Can anybody see the error and help me fix this error please ?
Thank you
Here is the code :
public class TestSort {
private int length;
String[] data;
public TestSort() {
length = 0;
}
public void i(String value) {
data[length] = value;
setSorted(data);
length++;
}
public void setSorted(String data[]) {
for(int i = data.length-1; i >= 0; i--) {
for(int j = 0; j < i; j++) {
if(data[j].compareTo(data[j + 1]) > -1) {
String temp = data[j];
data[j] = data[j + 1];
data[j + 1] = temp;
}
}
}
for(int i = 0; i < data.length; i++) {
System.out.print(data[i] +" ");
}
}
}
You don't initialize the array data. So it is set null, and accesses with data[i] will get you an NullPointerException. Even if you initialize this field, it will not work, as Arrays in Java have a fixed size, you have to reallocate the Array, if you insert a new value. You should try a List-implementation instead.
So the code should initialize in the constructor:
data = new ArrayList<String>();
and insertion would change to
data.add(value);
you can change your constructor code as (String array max length can be taken as input parameter):
public testsort()
{
data = new String[10];
length = 0;
}
But if you are not sure with the size of array you can use ArrayList.
You are getting exception because you are comparing with data[j+1] that is still null.
first time when you call
t.i("abc");
there is only one reference in data array that is pointing to String literal "abc" and that is at index 0. index 1 is still referring to null.
first String is already sorted so no need to sort that. if you are having more than one string then you should call setSorted() method.
to solve this you can put your condition in loop as:
if((data[j] != null && data[j+1] != null) &&(data[j].compareTo(data[j + 1]) > -1))
A working example but still: use a List and life is much easier :-)
public class Test {
private int length;
private String[] data;
public Test(int arrayLength) {
// INITIALIZE YOU ARRAY --> No NULLPOINTEREXCEPTION!
data = new String[arrayLength];
length = 0;
}
public void i(String value) {
data[length] = value;
length++;
}
public void setSorted() {
for (int j = 0; j < data.length - 1; j++) {
if (data[j].compareTo(data[j + 1]) > -1) {
String temp = data[j];
data[j] = data[j + 1];
data[j + 1] = temp;
}
}
for (String s : data) {
System.out.println(s);
}
}
public static void main(String[] args) {
Test t = new Test(5);
t.i("bbb");
t.i("aaa");
t.i("ccc");
t.i("zzz");
t.i("ddd");
// USE SETSORTED HERE --> else you fill your array with the same elements
t.setSorted();
}
}
The variable 'data' is null since it is nowhere initialized hence giving null pointer exception. Since 'data' is an array and as per the rule whenever an array is defined, it has to be of defined length. for e.g if we consider your case. 'data' can be initialized as :-
String[] data = new String[any numerical value]
the numerical value will be its length i.e. the maximum number of elements it can hold.
Secondly, as per your program statement :-
data[length] = value;
is trying to assign value at data's [length] index which is completely wrong since you haven't defined the length therefore how could you guess the index's value. Therefore your this approaoch is logically wrong.
For such situation i.e. whenever we're unaware about the length of the array, use of ArrayList is suggested. Therefore your program can be re-written by two ways:-
1) Either define the length of the array
String[] data = new String[n];
where n ranges from at least 1 to any positive integer.
2) By using ArrayList
public class Main {
List<String> data;
public Main(){
data = new ArrayList<String>();
}
public static void main(String... q){
Main m = new Main();
m.insertData("abc");
m.insertData("zxy");
m.insertData("aab");
m.insertData("aaa");
m.showData();
}
public void insertData(String str){
data.add(str);
Collections.sort(data);
}
public void showData(){
if(data!=null && !data.isEmpty()){
for(String s : data){
System.out.println(s);
}
}
}
}
output:-
aaa
aab
abc
zxy
Hope this helps.
as Mnementh suggested, the reason for NPE is that you have created the field data of type String[] but you never initialized it.
Other answers have provided every reason on why your code throwing ugly errors; I have just improved your code by replacing your String[] with List<String> so you don't have to worry about the size of your array anymore.
Sorting is also simplified now using Collections.sort().
have a look,
class test1 {
public static void main(String[] args) {
Test sorting = new Test();
sorting.input("abc");
sorting.input("cba");
sorting.input("aab");
sorting.setSorted();
}
}
class Test {
private List<String> data = new ArrayList<String>();
public void input(String value) {data.add(value);}
public void setSorted() {
Collections.sort(data);
for (String current : data) {
System.out.println(current);
}
}
}
if you are using Java 8, then you can use Arrays.parallerSort(), it performs sorting the same way as Collection.sort but with a parallel implementation.
Current sorting implementations provided by the Java Collections Framework > (Collections.sort and Arrays.sort) all perform the
sorting operation sequentially in the calling thread. This enhancement
will offer the same set of sorting operations currently provided by
the Arrays class, but with a parallel implementation that utilizes the
Fork/Join framework. These new API's are still synchronous with regard
to the calling thread as it will not proceed past the sorting
operation until the parallel sort is complete.
to implement it, replace Collections.sort with Arrays.parallelSort in the above code,
Replace,
Collections.sort(data);
with,
Arrays.parallelSort(data.toArray(new String[data.size()]));
I am trying to use the summer to practice more Java to get better by learning how to code algorithms. I have this problem where I add elements to my ArrayList but somehow the first number I add also sets the number of positions in my list which I want to avoid. I only want the 0th index to contain the number 5. I seem to not catch a clue on how to solve this.
public class Algorithms {
private ArrayList<Integer> numbers;
public Algorithms() {
numbers = new ArrayList<Integer>();
numbers.add(5);
numbers.add(4);
bubblesort();
}
public static void main(String args[]) {
new Algorithms();
}
public void bubblesort() {
System.out.println(numbers);
for (int a = 0; a < numbers.size();) {
for (int b = 1; b < numbers.size();) {
int currentNumber = numbers.get(a);
if (currentNumber > numbers.get(b)) {
//Collections.swap(numbers, currentNumber, numbers.get(b));
numbers.set(numbers.get(a), numbers.get(b));
numbers.set(numbers.get(b), numbers.get(a));
a++;
b++;
} else if (currentNumber < numbers.get(b)) {
a++;
b++;
}
System.out.println(numbers);
}
}
}
}
You are not swapping elements correctly. Instead of
numbers.set(numbers.get(a), numbers.get(b));
numbers.set(numbers.get(b), numbers.get(a));
it should be
int temp = numbers.get(a);
numbers.set(a, numbers.get(b));
numbers.set(b, temp);
The below two statements:
numbers.set(numbers.get(a), numbers.get(b));
numbers.set(numbers.get(b), numbers.get(a));
is not performing swapping. The first argument to the List#set(int, E) method is the index in the list, where you want to set the value passed as 2nd argument. You need to use a temp variable for swapping.
Also, the swapping didn't work for your commented line for the same reason. Collections#swap method take indices for swapping. So, just change:
Collections.swap(numbers, currentNumber, numbers.get(b));
to:
Collections.swap(numbers, a, b);
And please for the love of all that is holy, don't call method from inside a constructor. Remove the method invocation from inside the constructor, and move it to main method like this:
Algorithms algo = new Algorithms();
algo.bubbleSort()
I think the constructor is logically correct, I just can't figure out how to call it in the main ! :) Can anyone help please ? If someone would just have a quick look over my code it would be nice :) Thanks a lot !
Also, I am using arrayLists in this implementation and I have to do it this way so I don't wish to change it, even though it is far more easily implemented using only arrays.
import java.util.*;
public class PrimeNumberss {
public static void main(String args []){
PrimeNumberss PrimeNumbers = new PrimeNumberss(10);
}
public PrimeNumberss (int initialCapacity) {
ArrayList<Integer> listOfPrimeNumbers = new ArrayList<Integer>(initialCapacity);
long numberOfPrimes = 0; //Initialises variable numberOfPrimes to 0
int start = 2;
boolean[] isPrimeNumber = new boolean[initialCapacity + 1];
for (int i=0;i==initialCapacity;i++) {//setting all values in array of booleans to true
isPrimeNumber[i] = true;
}
while (start != initialCapacity)
{
if (isPrimeNumber[start])
{
listOfPrimeNumbers.add(start);
//add to array list
numberOfPrimes++;
for (int i = start; start < initialCapacity; i+=start)
{
isPrimeNumber[i] = false;
}
}
start++;
}
}
}
Your algorithm is not correct; you will only find the primes less than N (your initial capacity), not the first N primes.
If you're going to store each prime, you should store them in a class variable not a variable local to the constructor. You won't be able to access them outside the constructor if you do.
You should expose the list using a getter method to provide access to them.
You're not printing anything in the constructor.
i==initialCapacity is clearly wrong.
Everything important is there, its small changes. Right now you are getting primes less than N, so if you want to change it to first N primes that's going to be a real functional difference. For now lets just make N=50 so you'll get well over 10 primes.
public class PrimeNumberss {
private List listOfPrimeNumbers; //add a member variable for the ArrayList
public static void main(String args []){
PrimeNumberss PrimeNumbers = new PrimeNumberss(50);
PrimeNumbers.print(); //use our new print method
}
public PrimeNumberss (int initialCapacity) {
listOfPrimeNumbers = new ArrayList<Integer>(initialCapacity/2); //initialCapacity/2 is an easy (if not tight) upper bound
long numberOfPrimes = 0; //Initialises variable numberOfPrimes to 0
int start = 2;
boolean[] isPrimeNumber = new boolean[initialCapacity + 1];
for (int i=0;i==initialCapacity;i++) {//setting all values in array of booleans to true
isPrimeNumber[i] = true;
}
//.... complete the constructor method as you have it. honestly, i didnt even read it all
public void print() //add this printout function
{
int i = 1;
it = listOfPrimeNumbers.listIterator();
while (it.hasNext())
{
System.out.println("the " + i + "th prime is: " + it.next());
i++;
}
//or just System.out.println(listOfPrimeNumbers);, letting ArrayList's toString do the work. i think it will be in [a,b,c,..,z] format
}
public List getPrimes() {return listOfPrimeNumbers;} //a simple getter isnt a bad idea either, even though we arent using it yet
}
On a side note, you could probably d oa little better with the naming (PrimeNumberss and PrimeNumbers??), but I didnt change any of that. Also, intiialCapacity does not reflect what it really means. Maybe something along the lines of 'top'.