Java Why am I getting a NullPointerException while instantiating my array - java

I am new to programming and don't get why the program gives me a run time error for NullPointerException when I have tried initializing n, numInt, and arrayMenu. None of which seem to work. The program's job is to gather a set of random integers to store in an array and allow the user to pick which sort to choose from. Thanks for reading.
import java.util.Scanner;
import java.util.Random;
public class VariousSortsHS
{
private static int[] arrayMenu;
private static Random generator;
/**
* Constructor for objects of class VariousSortsHS.
*/
public VariousSortsHS(int n) //The error starts here
{
arrayMenu = new int[n]; //I don't get why it says null in the array when
//i am initializing the length of the array to n
/*Assigns a random number between 0 too 100.*/
for(int i = 0; i < n; i++)
{
int temp = generator.nextInt(100);
arrayMenu[n] = temp;
}
}
/**
* Selection Sort method.
*/
public static void selection(int n)
{
for(int i = 0; i < arrayMenu.length - 1; i++)
{
int minPos = i;
for(int j = i + 1; j < arrayMenu.length; j++)
{
if(arrayMenu[j] < arrayMenu[minPos]) minPos = j;
}
int temp = arrayMenu[i];
arrayMenu[i] = arrayMenu[minPos];
arrayMenu[minPos] = temp;
System.out.print(temp + " ");
}
}
/**
* Insertion Sort method.
*/
public static void insertion(int n)
{
for(int i = 1; i < arrayMenu.length; i++)
{
int next = arrayMenu[i];
int j = i;
while(j > 0 && arrayMenu[j - 1] > next)
{
arrayMenu[j] = arrayMenu[j - 1];
j--;
}
arrayMenu[j] = next;
System.out.print(next + " ");
}
}
/**
* Quick Sort method.
*/
public static void quick(int n)
{
int pivot = arrayMenu[0];
int i = 0 - 1;
int j = n + 1;
while(i < j)
{
i++; while(arrayMenu[i] < pivot) i++;
j++; while(arrayMenu[j] > pivot) j++;
if(i < j)
{
int temp = arrayMenu[i];
arrayMenu[i] = arrayMenu[j];
arrayMenu[j] = temp;
System.out.print(temp + " ");
}
}
}
/**
* Main method that allows user to input data.
*/
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.println("Do you wish to sort random integers? (Yes or No) ");
String answer = in.next();
String answer2 = answer.toLowerCase();
do
{
/*Prompts for array length.*/
System.out.println("How many random integers do you wish to sort?");
int numInt = in.nextInt();
/*Promps for sort selection choice.*/
System.out.println("Select a sort to use: \n\t1)Selection\n\t2)Insertion\n\t3)Quick");
String sort = in.next();
String sort2 = sort.toLowerCase();
if(sort2.equals("selection"))
{
selection(numInt);
}
else if(sort2.equals("insertion"))
{
insertion(numInt);
}
else if(sort2.equals("quick"))
{
quick(numInt);
}
else
{
System.out.println("You have entered the wrong input.");
}
} while(!answer2.equals("no"));
}
}

Everything in your code is static. This means the constructor you wrote is never called, and the array has never been changed from its default value, null. Consider changing your constructor code to a static initialization block instead.
generator is never set to anything, so it's null too and you can't call nextInt on it
initializing the array is setting arrayMenu[n] instead of arrayMenu[i]

When you call insertion(numInt);, method public static void insertion(int n) is called and then you are trying to do the for-loop like this for(int i = 1; i < arrayMenu.length; i++)
However, arrayMenu was not initialized, it is null. When you try to call a length, on null, you get NullPointerException.

You need to add a static constructor and initialize the size using a static int
//set parameter = n
public static int parameter;
static
{
arrayMenu = new int[parameter];
}

Related

How to make a Linear Search OOP approach that uses Input Scanner

So I refactored a Linear Search code that only uses the main method. My goal is to convert it into an OOP approach. But I have trouble saving the input set of integers.
// LinearSearchDriver.java
import java.util.Scanner;
public class LinearSearchDriver {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
LinearSearch linearSearch = new LinearSearch();
System.out.println("Enter number of elements");
int numElements = in.nextInt();
linearSearch.setNumberOfElements(numElements);
System.out.println("Enter " + numElements + " integers");
for (int count = 0; count < numElements; count++){
int setIntegers = in.nextInt();
linearSearch.setNumberOfIntegers(setIntegers);
}
System.out.println("Enter value to find");
int search = in.nextInt();
linearSearch.findValue(search);
}
}
//LinearSearch.java
public class LinearSearch {
private int c;
private int n;
private int array[];
public void setNumberOfElements(int n) {
this.n = n;
this.array = new int[n];
}
public void setNumberOfIntegers(int y) {
for (c=0; c < n; c++)
array[c] = y;
}
public void findValue(int search) {
for (c = 0; c < n; c++) {
if (array[c] == search) { /* Searching element is present */
System.out.println(search + " is present at location " + (c + 1) + ".");
break;
}
}
if (c == n) { /* Searching element is absent */
System.out.println(search + " is not present in array.");
}
}
}
Example output:
But when I input number 1, this is the output:
The program only reads number 2 output which I think, the last number is only the one that is saving to an array.
for (c = 0; c < n; c++) {
array[c] = y;
}
is where things go wrong. You're setting the last value passed to that function for every index in the Array.
You can adress this in several ways:
Pass an Array to the function instead of a single argument.
You can determine the current number of elements in your Array and then append the newest value "manually". See this post.
Or you could simply use a dynamic structure, such as a List and append the element to that.
Here is a rough outline for the 3rd Option:
public class LinearSearch {
private List<Integer> intList;
public LinearSearch() {
}
public void setNumberOfElements(int n) {
intList = new ArrayList<>(n); //Set the capacity here like before.
}
public void setNumberOfIntegers(int y) {
//If you want your List to always only contain the initially allowed number of elements, you could implement
// this logic here, by adding the new value and removing the "oldest" one.
intList.add(y);
}
public void findValue(int search) {
if (!intList.contains(search)) { //You can put this up here and potentially skip the looping.
System.out.println(search + " is not present in array.");
return;
}
for (int n : intList) {
if (n == search) {
System.out.println(search + " is present at location " + intList.indexOf(search) + ".");
return; //Use return to exit the method, break only exits the loop in your example, and you could print both lines.
}
}
}
}

Creating java program assistance

I have to create a java program with two classes and the challenge is =
"Enter in 10 numbers. Calculate the average and display all numbers greater than the average."
I am fairly new to java and I have no idea on what I am doing and how to send array values from one class to another.
import BreezySwing.KeyboardReader;
import javax.swing.*;
public class Average {
public static void main(String[] args) {
KeyboardReader reader = new KeyboardReader();
System.out.print('\u000C');
AverageTest at = new AverageTest();
int numberArray[];
int i;
numberArray = new int[10];
for (i = 0; i < 10; i++) {
numberArray[i] = reader.readInt("Enter a number: ");
at.setnumber(numberArray);
}
}
}
import javax.swing.*;
import BreezySwing.*;
public class AverageTest
{
private int number[];
private int a;
public void setnumber(int number)
{
number = numberArray;
}
}
import java.util.Scanner;
public class AverageTest {
public static void main(String[] args) {
int[] array = new int[10];
// Try with resources, automatically closes the reader once the work is done
// Read 10 integers from the standard input
try (Scanner reader = new Scanner(System.in);) {
for (int i = 0; i < 2; i++) {
System.out.println("Enter a number: ");
array[i] = reader.nextInt();
}
} catch (Exception e) {
e.printStackTrace();
}
// we have an array with 10 numbers, now create an average object by passing
// this array to the Average class constructor
Average averageObj = new Average(array);
// Compute the average
float average = averageObj.average();
System.out.println("Average: " + average);
System.out.println("Numbers greater than average: ");
// Print out the numbers which are greater than or equal to the average
for (int i = 0; i < array.length; i++) {
if (array[i] >= average) {
System.out.println(array[i]);
}
}
}
}
class Average {
private int[] array;
public Average(int[] array) {
if (array == null || array.length == 0) {
throw new IllegalArgumentException("Array cannot be null or empty");
}
this.array = array;
}
public int[] getArray() {
return array;
}
/**
* Computes the average of the given array and returns it.
*/
public float average() {
int sum = 0;
for (int i = 0; i < array.length; i++) {
sum += array[i];
}
return (float) sum/array.length;
}
}
there are 3 steps about this issue:
1.Enter in 10 numbers.
2.Calculate the average.
3.display all numbers greater than the average.
you have done the step 1,that's great.
and I can see that you are trying to do the step 2.
here's the suggestion of your issue:
if you want to send array values from A class to B,you just need to invoke the method of B in the A correctly.
I think I know what you are trying to do.
the problem of your code that you can't send array values from one class to another is because the method's parameter type is not matching.
the method public void setnumber(int number),the parameter is an int type,and you try to refer it to an int array,this's wrong.
first, you need to change the method's definition to public void setnumber(int[] numberarray),and try to figure out why we have to write like this.
then finish the step 2.
Hope it'll help.

Algorithm course: Output of int sort and method to sort Strings

My assignment asks me to make a TV show program, where I can input shows, delete, modify and sort them. What I'm stuck on is the sorting part. With the show, it asks for the name, day a new episode premieres, and time. Those are the keys I need to sort it by.
The program prompts the user to input one of those keys, then the program needs to sort (sorting by day will sort alphabetically).
I made a class and used an array. Here is the class:
public class showInfo
{
String name;
String day;
int time;
}
And the method to sort by time in the code:
public static void intSort()
{
int min;
for (int i = 0; i < arr.length; i++)
{
// Assume first element is min
min = i;
for (int j = i+1; j < arr.length; j++)
{
if (arr[j].time < arr[min].time)
{
min = j;
}
}
if (min != i)
{
int temp = arr[i].time;
arr[i].time = arr[min].time;
arr[min].time = temp;
}
}
System.out.println("TV Shows by Time");
for(int i = 0; i < arr.length; i++)
{
System.out.println(arr[i].name + " - " + arr[i].day + " - " + arr[i].time + " hours");
}
}
When I call it and output it in the main, it only shows "TV Shows by Time" and not the list. Why is this?
Also, I need to make ONE method that I will be able to use to sort both the day AND the name (both Strings). How can I do this without using those specific arrays (arr[i].name, arr[i].day) in the method?
Any help would be greatly appreciated! Thanks in advance!
In this part of your code
if (min != i) {
int temp = arr[i].time;
arr[i].time = arr[min].time;
arr[min].time = temp;
}
You're just changing the time when you should move the whole object instead. To fix it, the code must behave like this:
if (min != i) {
//saving the object reference from arr[i] in a temp variable
showInfo temp = arr[i];
//swapping the elements
arr[i] = arr[min];
arr[min] = temp;
}
I̶t̶ ̶w̶o̶u̶l̶d̶ ̶b̶e̶ ̶b̶e̶t̶t̶e̶r̶ ̶t̶o̶ ̶u̶s̶e̶ ̶ Arrays#sort ̶w̶h̶e̶r̶e̶ ̶y̶o̶u̶ ̶p̶r̶o̶v̶i̶d̶e̶ ̶a̶ ̶c̶u̶s̶t̶o̶m̶ ̶̶C̶o̶m̶p̶a̶r̶a̶t̶o̶r̶̶ ̶o̶f̶ ̶t̶h̶e̶ ̶c̶l̶a̶s̶s̶ ̶b̶e̶i̶n̶g̶ ̶s̶o̶r̶t̶e̶d̶ ̶(̶i̶f̶ ̶y̶o̶u̶ ̶a̶r̶e̶ ̶a̶l̶l̶o̶w̶e̶d̶ ̶t̶o̶ ̶u̶s̶e̶ ̶t̶h̶i̶s̶ ̶a̶p̶p̶r̶o̶a̶c̶h̶)̶.̶ ̶S̶h̶o̶r̶t̶ ̶e̶x̶a̶m̶p̶l̶e̶:̶
showInfo[] showInfoArray = ...
//your array declared and filled with data
//sorting the array
Arrays.sort(showInfoArray, new Comparator<showInfo>() {
#Override
public int compare(showInfo showInfo1, showInfo showInfo2) {
//write the comparison logic
//basic implementation
if (showInfo1.getTime() == showInfo2.getTime()) {
return showInfo1.getName().compareTo(showInfo2.getName());
}
return Integer.compare(showInfo1.getTime(), showInfo2.getTime());
}
});
//showInfoArray will be sorted...
Since you have to use a custom made sorting algorithm and support different ways to sort the data, then you just have to change the way you compare your data. This mean, in your current code, change this part
if (arr[j].time < arr[min].time) {
min = j;
}
To something more generic like
if (compare(arr[j], arr[min]) < 0) {
min = j;
}
Where you only need to change the implementation of the compare method by the one you need. Still, it will be too complex to create and maintain a method that can support different ways to compare the data. So the best option seems to be a Comparator<showInfo>, making your code look like this:
if (showInfoComparator.compare(arr[j], arr[min]) < 0) {
min = j;
}
where the showInfoComparator holds the logic to compare the elements. Now your intSort would become into something more generic:
public static void genericSort(Comparator<showInfo> showInfoComparator) {
//your current implementation with few modifications
//...
//using the comparator to find the minimum element
if (showInfoComparator.compare(arr[j], arr[min]) < 0) {
min = j;
}
//...
//swapping the elements directly in the array instead of swapping part of the data
if (min != i) {
int temp = arr[i].time;
arr[i].time = arr[min].time;
arr[min].time = temp;
}
//...
}
Now, you just have to write a set of Comparator<showInfo> implementations that supports your custom criteria. For example, here's one that compares showInfo instances using the time field:
public class ShowInfoTimeComparator implements Comparator<showInfo> {
#Override
public int compare(showInfo showInfo1, showInfo showInfo2) {
//write the comparison logic
return Integer.compare(showInfo1.getTime(), showInfo2.getTime());
}
}
Another comparator that uses the name field:
public class ShowInfoNameComparator implements Comparator<showInfo> {
#Override
public int compare(showInfo showInfo1, showInfo showInfo2) {
//write the comparison logic
return showInfo1.getName().compareTo(showInfo2.getName());
}
}
Now in your code you can call it like this1:
if (*compare by time*) {
genericSort(showInfoArray, new ShowInfoTimeComparator());
}
if (*compare by name*) {
genericSort(showInfoArray, new ShowInfoNameComparator());
}
if (*another custom rule*) {
genericSort(showInfoArray, new ShowInfoAnotherCustomRuleComparator());
}
where now you can implement a custom rule like compare showInfo objects using two or more fields. Taking as example your name and day fields (as stated in the question):
public class ShowInfoNameAndDayComparator implements Comparator<showInfo> {
#Override
public int compare(showInfo showInfo1, showInfo showInfo2) {
//write the comparison logic
int nameComparisonResult = showInfo1.getName().compareTo(showInfo2.getName());
if (nameComparisonResult == 0) {
return showInfo1.getDay().compareTo(showInfo2.getDay());
}
return nameComparisonResult;
}
}
1: There are other ways to solve this instead using lot of if statements, but looks like that's outside the question scope. If not, edit the question and add it to show another ways to solve this.
Other tips for your current code:
Declare the names of the classes using CamelCase, where the first letter of the class name is Upper Case, so your showInfo class must be renamed to ShowInfo.
To access to the fields of a class, use proper getters and setters instead of marking the fields as public or leaving the with default scope. This mean, your ShowInfo class should become into:
public class ShowInfo {
private String name;
private String day;
private int time;
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
//similar for other fields in the class
}
Use selection sort algorithm which is easy to implement,
for (int i = 0; i < arr.length; i++)
{
for (int j = i + 1; j < arr.length; j++)
{
if (arr[i].time > arr[j].time) // Here ur code that which should be compare
{
ShowInfo temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
no need to check min element. go through this wiki http://en.wikipedia.org/wiki/Selection_sort
Why not you use a Collection for this sort of a thingy to work. Moreover, in your added example, you are simply changing one attribute of a given object, while sorting, though you not changing the position of the object as a whole, inside the given list.
Create a List which will contain the references of all the Shows, now compare each attribute of one Show with another, in the List. Once the algorithm feels like, that swapping needs to be done, simply pick the reference from the List, save it in a temp variable, replace it with a new reference at this location, and set duplicate to the one stored in the temp variable. You are done, List is sorted :-)
Here is one small example for the same, for help :
import java.io.*;
import java.util.*;
public class Sorter {
private BufferedReader input;
private List<ShowInfo> showList;
public Sorter() {
showList = new ArrayList<ShowInfo>();
input = new BufferedReader(
new InputStreamReader((System.in)));
}
private void createList() throws IOException {
for (int i = 0; i < 5; i++) {
System.out.format("Enter Show Name :");
String name = input.readLine();
System.out.format("Enter Time of the Show : ");
int time = Integer.parseInt(input.readLine());
ShowInfo show = new ShowInfo(name, time);
showList.add(show);
}
}
private void performTask() {
try {
createList();
} catch (Exception e) {
e.printStackTrace();
}
sortByTime(showList);
}
private void sortByTime(List<ShowInfo> showList) {
int min;
for (int i = 0; i < showList.size(); i++) {
// Assume first element is min
min = i;
for (int j = i+1; j < showList.size(); j++) {
if (showList.get(j).getTime() <
showList.get(min).getTime()) {
min = j;
}
}
if (min != i) {
ShowInfo temp = showList.get(i);
showList.set(i, showList.get(min));
showList.set(min, temp);
}
}
System.out.println("TV Shows by Time");
for(int i = 0; i < showList.size(); i++) {
System.out.println(showList.get(i).getName() +
" - " + showList.get(i).getTime());
}
}
public static void main(String[] args) {
new Sorter().performTask();
}
}
class ShowInfo {
private String name;
int time;
public ShowInfo(String n, int t) {
name = n;
time = t;
}
public String getName() {
return name;
}
public int getTime() {
return time;
}
}
EDIT 2 :
For sorting By Name you can use this function :
private void sortByName(List<ShowInfo> showList) {
int min;
for (int i = 0; i < showList.size(); i++) {
// Assume first element is min
min = i;
for (int j = i+1; j < showList.size(); j++) {
int value = (showList.get(j).getName()).compareToIgnoreCase(
showList.get(min).getName());
if (value < 0)
min = j;
}
if (min != i) {
ShowInfo temp = showList.get(i);
showList.set(i, showList.get(min));
showList.set(min, temp);
}
}
System.out.println("TV Shows by Time");
for(int i = 0; i < showList.size(); i++) {
System.out.println(showList.get(i).getName() +
" - " + showList.get(i).getTime());
}
}
EDIT 3 :
Added Comparable<?> Interface, to the existing class to perform sorting based on specified input. Though one can improve on the logic, by using Enumeration, though leaving it for the OP to try his/her hands on :-)
import java.io.*;
import java.util.*;
public class Sorter {
private BufferedReader input;
private List<ShowInfo> showList;
private int command;
public Sorter() {
showList = new ArrayList<ShowInfo>();
input = new BufferedReader(
new InputStreamReader((System.in)));
command = -1;
}
private void createList() throws IOException {
for (int i = 0; i < 5; i++) {
System.out.format("Enter Show Name :");
String name = input.readLine();
System.out.format("Enter Time of the Show : ");
int time = Integer.parseInt(input.readLine());
ShowInfo show = new ShowInfo(name, time);
showList.add(show);
}
}
private void performTask() {
try {
createList();
} catch (Exception e) {
e.printStackTrace();
}
System.out.format("How would you like to sort : %n");
System.out.format("Press 0 : By Name%n");
System.out.format("Press 1 : By Time%n");
try {
command = Integer.parseInt(input.readLine());
} catch (Exception e) {
e.printStackTrace();
}
sortList(showList);
}
private void sortList(List<ShowInfo> showList) {
int min;
for (int i = 0; i < showList.size(); i++) {
// Assume first element is min
min = i;
for (int j = i+1; j < showList.size(); j++) {
showList.get(j).setValues(command);
int value = showList.get(j).compareTo(showList.get(min));
if (value < 0) {
min = j;
}
}
if (min != i) {
Collections.swap(showList, i, min);
}
}
System.out.println("TV Shows by Time");
for(int i = 0; i < showList.size(); i++) {
System.out.println(showList.get(i).getName() +
" - " + showList.get(i).getTime());
}
}
public static void main(String[] args) {
new Sorter().performTask();
}
}
class ShowInfo implements Comparable<ShowInfo> {
private String name;
private int time;
private int command;
public ShowInfo(String n, int t) {
name = n;
time = t;
}
public String getName() {
return name;
}
public int getTime() {
return time;
}
public void setValues(int cmd) {
command = cmd;
}
public int compareTo(ShowInfo show) {
int lastCmp = 1;
if (command == 0) {
lastCmp = name.compareTo(show.name);
} else if (command == 1) {
if (time < show.time) {
lastCmp = -1;
} else if (time == show.time) {
lastCmp = 0;
} else if (time > show.time) {
lastCmp = 1;
}
}
return lastCmp;
}
}

ADT LinkedList intersecting set error

I have a test code for an ADT of LinkedList, which implements interface NumList.java, and is implemented in a NumLinkedList.java, and am using it in a NumSet.java.
I am trying to make it so that my NumSet has methods where I can create a set from a double array input, and use intercept/union and print methods to use and print the data.
but my test code is showing that my test NumSet values are empty, namely testProof and testProof2.
So now my testProof is returning an empty variable, which means nothing is saving into it.
static public NumSet intersect(NumSet S1, NumSet S2) //check 2nd for and if//
{
NumSet intersectAnswer = new NumSet();
for (int i = 0; i < S1.set.size()-1; i++)
{
for(int j = 0; j < S2.set.size()-1; j++)
{
double FUZZ = 0.0001;
if (Math.abs(S1.set.lookup(i) - S2.set.lookup(j)) < FUZZ) // double values, this is more precise than ==.
{
intersectAnswer.set.insert(1, S1.set.lookup(i));
}
}
}
return intersectAnswer;
}
is the method for testProof, and the following is where testProof is defined.
public static void main(String[] args)
{
double[] a = {1.3,2,3,4,101.9};
double[] b = {3,7,13,901,-29.1,0.05};
NumArrayList test;
test = new NumArrayList();
test.printTest(); //runs test code in NumList
//ok below is running. what is wrong with intersect?
NumSet test2;
test2 = new NumSet(a);
NumSet test4;
test4 = new NumSet(b);
NumSet testProof;
NumSet testProof2;
test2.print(); //print out test 2
System.out.println();
test4.print();
System.out.println();
testProof = intersect(test2,test4);
I have initialized as
public class NumSet
{
private NumList set;
public NumSet(double[] sth)
{
//moves elements of sth into set.
set = new NumLinkedList();
for(int i = 0; i < sth.length; i++)
{
set.insert(0,sth[i]);
}
set.removeDuplicates();
}
public NumSet()
{
set = new NumLinkedList();
}
int numSet = 0;
and my intercept, union and print are below:
public NumSet intersect(NumSet S1, NumSet S2) //check 2nd for and if//
{
NumSet intersectAnswer = new NumSet();
for (int i = 0; i < S1.set.size()-1; i++)
{
for(int j = 0; j < S2.set.size()-1; j++)
{
if (S1.set.lookup(i) == S2.set.lookup(j))
{
intersectAnswer.set.insert(0, S1.set.lookup(i));
}
}
}
// intersectAnswer.set.removeDuplicates(); unnecessary, sets are already removed of duplicates
return intersectAnswer;
}
public NumSet union(NumSet S1, NumSet S2)
{ //check logic.
NumSet unionAnswer = new NumSet();
for (int i = 1; i < S1.set.size()+1; i++)
{
unionAnswer.set.insert(1, S1.set.lookup(i));
}
for (int i = 1; i < S2.set.size()+1; i++)
{
unionAnswer.set.insert(1, S2.set.lookup(i));
}
unionAnswer.set.removeDuplicates();
return unionAnswer;
}
public void print()
{
for (int i = 0; i < set.size()-1; i++)
{
System.out.print(set.lookup(i) + ",");
}
System.out.print(set.lookup(set.size()-1));
}
the lookup and size are referred to from my NumLinkedList.java and are as below
public int size() // measure size of list by counting counter++;
{
return nItem;
}
public double lookup(int i)
{
if( i <0 || i >= size()) //cannot lookup nonexistant object
{
System.out.println("out of bounds " + i + " < 0 or > " + size() );
//how do I break out of this loop?
System.out.println("just returning 0 for the sake of the program");
return 0;
}
if(i == 0)
{
return head.value;
}
double answer = 0;
Node currNode = head;
for(int j = 0; j < i+1; j++) //move to ith node and save value
{
answer = currNode.value;
currNode = currNode.next;
}
return answer;
}
and finally my test code is as below, where testProof and testProof2 are.
public static void main(String[] args)
{
double[] a = {1.3,2,3,4,101.9};
double[] b = {3,7,13,901,-29.1,0.05};
NumArrayList test;
test = new NumArrayList();
test.printTest(); //runs test code in NumList
//ok below is running. what is wrong with intersect?
NumSet test2;
test2 = new NumSet(a);
NumSet test4;
test4 = new NumSet(b);
NumSet testProof;
NumSet testProof2;
test2.print();
System.out.println();
testProof = test2.intersect(test2, test4);
System.out.println("tried intersect");
testProof.print();
System.out.println();
System.out.println("tried test.print()");
testProof2 = test2.union(test2,test4);
System.out.println("tried union");
testProof2.print();
System.out.println();
System.out.println("NumSet ran fully.");
I'd suggest you implement you NumSet Class with integer values rather than double values while you debug because comparing two double values tends to add some unneeded complexity to your code at this debug stage.
You might want to look at your removeDuplicates() method, I think that might hold the answer to your problem. Unfortunately I don't see it within the code you posted.
Actually, this part of code within the intersect() method is destined to fail from the start,
if (S1.set.lookup(i) == S2.set.lookup(j))
Because of your use of doubles, == is a very imprecise method of comparing two different values, a better way would be to allow for a certain amount of precision error, i.e.
double final FUZZ = 0.0001
if (Math.abs(S1.set.lookup(i) - S2.set.lookup(j)) < FUZZ )
//...

Beginner: Assigning values to arrays in Java

I am attempting to write a simple Genetic Algorithm in Java after reading a book on Machine Learning and have stumbled on the basics. I'm out of practice with Java so I'm probably missing something extremely simple.
Individual
public class Individual {
int n;
int[] genes = new int[500];
int fitnessValue;
public int getFitnessValue() {
return fitnessValue;
}
public void setFitnessValue(int fitnessValue) {
this.fitnessValue = fitnessValue;
}
public int[] getGenes() {
return genes;
}
public void setGenes(int index, int gene) {
this.genes[index] = gene;
}
public int getN() {
return n;
}
public void setN(int n) {
this.n = n;
}
// Constructor
public Individual() {
}
}
Population
import java.util.Random;
public class Population {
public Population() {
}
public static void main(String[] args) {
Random rand = new Random();
int p = rand.nextInt(10);
int n = rand.nextInt(10);
Individual pop[] = new Individual[p];
System.out.println("P is: " + p + "\nN is: " + n);
for(int j = 0; j <= p; j++) {
for(int i = 0; i <= n; i++) {
pop[j].genes[i] = rand.nextInt(2);
}
}
}
public void addPopulation() {
}
}
The aim of this code is to populate the Population and the Genes with a random number. Could someone please take a look at my code to see where I'm going wrong?
before
pop[j].genes[i] = rand.nextInt(2);
add
pop[j] = new Individual();
the elements of the array are null.
I believe you need to initialize pop[j] before doing pop[j].genes[i] = rand.nextInt();
Individual pop[] = new Individual[p];
This just initializes the array, not the individual elements. Try to put pop[j] = new Individual() between your two loops.
What they said...
Also, do you mean to call your setGenes method, or do you just want to directly access the gene array.
From what I understand of your code I think you need to do this:
for(int j = 0; j <= p; j++) {
pop[j] = new Individual();
for(int i = 0; i <= n; i++) {
pop[j].setGenes(i, rand.nextInt(2));
}
}

Categories