This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
This program cannot run but I don't know why:
Abstract class
public class Mahasiswa implements Comparable {
private String nama;
private int nim;
public Mahasiswa(String nama, int nim) {
}
public String getNama() {
return nama;
}
public int getNim() {
return nim;
}
public void setNama() {
this.nama=nama;
}
public void setNim() {
this.nim=nim;
}
#Override
public int compareTo(Object o) {
Mahasiswa key = (Mahasiswa) o;
if (this.nama.compareTo(key.getNama()) == 0) {
return -1;
}else if (this.nama.compareTo(key.getNama()) > 0) {
return 1;
}else{
return 0;
}
}
}
Method class:
public static Mahasiswa[] BubbleSort(Object[] object) {
Mahasiswa[] data =(Mahasiswa[]) object;
for (int i = 1; i < data.length; i++) {
for (int j = 0; j < data.length - i; j++) {
if (((Comparable)data[j]).compareTo(data[j+1]) ==1 ) {
Mahasiswa c = data[j];
data[j] = data[j + 1];
data[j + 1] = c;
}
}
}
return data;
}
Main class
public class Main {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Mahasiswa[] data = {new Mahasiswa("Karel", 175314105),
new Mahasiswa("Fandur", 175314006),
new Mahasiswa("Yeski", 1753141104),
new Mahasiswa("Tiosu", 175314001),
new Mahasiswa("Jono", 175314090)};
Larik.BubbleSort(data);
for (int i = 0; i < data.length; i++) {
System.out.println(data[i].getNama()+" "+data[i].getNim());
}
}
}
Output
Exception in thread "main" java.lang.NullPointerException
at SortingObject.Mahasiswa.compareTo(Mahasiswa.java:33)
at SortingObject.Larik.BubbleSort(Larik.java:16)
at SortingObject.Main.main(Main.java:24)
C:\Users\Yeski's Legion\AppData\Local\NetBeans\Cache\8.2\executor-
snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 0 seconds)
You have to set the instance variable value either constructor or setter, otherwise it will be null.
public Mahasiswa(String nama, int nim) {
this.nama = nama;
this.nim = nim;
}
You can also use setter methods.
Related
Trying to get the return function to return the full array, but not able to do it with a for loop or without. Is there any way to get this done?
public class Teams {
String Game;
String Coach;
String Player[];
public void setPlayer(String a[])
{
for (int i = 2; i<10; i++)
{
Player[i-2] = a[i];
}
}
public String getPlayer()
{
for(int i = 0; i < 8; i++)
{
return Player[i];
}
}
}
There's nothing special about arrays - you can return the member as is:
public String[] getPlayer() {
return Player;
}
I've written my first Genetic Algorithm in Java and I'm able to optimize functions with one argument x, but I don't know how to optimize functions with two arguments x and y. Algorithm class and main app works correctly so i send only Individual.java and Population.java. If I think correctly in genes I have only x-coordinate but I'm not sure how to add y-coordinate. Any advise will be helpfull.
Individual.java
public class Individual {
private int[] genes;
private int fitness;
private Random randomGenerator;
public Individual() {
this.genes = new int[Constants.CHROMOSOME_LENGTH];
this.randomGenerator = new Random();
}
public void generateIndividual() {
for(int i = 0; i < Constants.CHROMOSOME_LENGTH; i++) {
int gene = randomGenerator.nextInt(2);
genes[i] = gene;
}
}
public double f(double x) {
// return Math.pow(x,2);
return (Math.pow((1-x),2)) + (100*(Math.pow((1-Math.pow(x,2)),2)));
// return Math.sin(x)*((x-2)*(x-2))+3;
}
public double getFitness() {
double genesToDouble = genesToDouble();
return f(genesToDouble);
}
public double getFitnessResult() {
double genesToDouble = genesToDouble();
return genesToDouble;
}
public double genesToDouble() {
int base = 1;
double geneInDouble = 0;
for( int i =0; i < Constants.GENE_LENGTH; i++) {
if(this.genes[i] == 1)
geneInDouble += base;
base = base*2;
}
geneInDouble = (geneInDouble / 1024) * 10.1;
return geneInDouble;
}
public int getGene(int index) {
return this.genes[index];
}
public void setGene(int index, int value) {
this.genes[index] = value;
this.fitness = 0;
}
}
Population.java
public class Population {
private Individual[] individuals;
public Population(int populationSize) {
individuals = new Individual[populationSize];
}
public void initialize() {
for(int i = 0; i < individuals.length; i++) {
Individual newIndividual = new Individual();
newIndividual.generateIndividual();
saveIndividual(i, newIndividual);
}
}
public Individual getIndividual(int index) {
return this.individuals[index];
}
//maksimum lub minimum
public Individual getFittestIndividual() {
Individual fittest = individuals[0];
for(int i =0; i < individuals.length; i++) {
if(getIndividual(i).getFitness() < fittest.getFitness())
fittest = getIndividual(i);
}
return fittest;
}
public int size() {
return this.individuals.length;
}
public void saveIndividual(int index, Individual individual) {
this.individuals[index] = individual;
}
}
public class PlaneDemo
{
public static void main(String args[])
{
ArrayQueue<Plane> q = new ArrayQueue<Plane>();
Plane p1 = new Plane("Aircraft 1", 3);
Plane p2 = new Plane("Aircraft 2", 1);
Plane p3 = new Plane("Aircraft 3", 2);
q.addQueue(p1);
q.addQueue(p2);
q.addQueue(p3);
while(!q.isEmptyQueue())
{
System.out.println("Vehicle: ");
System.out.println(q.front());
q.deleteQueue();
}
}
}
cannot find symbol
q.addQueue(p1);
^
symbol: method addQueue(Plane)
location: variable q of type ArrayQueue<Plane>
error: cannot find symbol
q.addQueue(p2);
^
symbol: method addQueue(Plane)
location: variable q of type ArrayQueue<Plane>
Im like panicking this is due soon and I can't figure out what I did wrong.
public class ArrayQueue<T>
{
private int maxQueueSize;
private int count;
private int queueFront;
private int queueRear;
private T[] list;
public ArrayQueue()
{
maxQueueSize = 100;
queueFront = 0;
queueRear = maxQueueSize - 1;
count = 0;
list = (T[]) new Object[maxQueueSize];
}
public ArrayQueue(int queueSize)
{
if(queueSize <= 0)
{
System.err.println("Array size must be a positive number. Creating array at default size of 100.");
maxQueueSize = 100;
}
else
maxQueueSize = queueSize;
queueFront = 0;
queueRear = maxQueueSize - 1;
count = 0;
list = (T[]) new Object[maxQueueSize];
}
public void initializeQueue()
{
for(int i = queueFront; i < queueRear; i = (i + 1) % maxQueueSize)
list[i] = null;
queueFront = 0;
queueRear = maxQueueSize - 1;
count = 0;
}
public boolean isEmptyQueue()
{
return(count == 0);
}
public boolean isFullQueue()
{
return(count == maxQueueSize);
}
public T peek() //throws QueueUnderflowException
{
/*if(isEmptyQueue())
throw new QueueUnderflowException();*/
return (T) list[queueFront];
}
/*public T back() throws QueueOverflowException
{
if(isFullQueue())
throw new QueueUnderflowException();
return (T) list[queueRear];
}
*/
public void enqueue(T queueElement) throws QueueOverflowException
{
if(isFullQueue())
throw new QueueOverflowException();
queueRear = (queueRear + 1) % maxQueueSize;
count++;
list[queueRear] = queueElement;
}
public void dequeue() throws QueueUnderflowException
{
if(isEmptyQueue())
throw new QueueUnderflowException();
count--;
list[queueFront] = null;
queueFront = (queueFront + 1) % maxQueueSize;
}
}
Replace this
q.addQueue(p1);
q.addQueue(p2);
q.addQueue(p3);
For this q.enqueue(p1); etc because is the only,method you have to add an element to the class
public void enqueue(T queueElement) throws QueueOverflowException
{
I am in the somewhat beginning stages of creating a bowling program in Java. I currently have a JUnit test file called BowlingGameTest and a Java class called Game...both of these are under my Java project, BowlingGame. I have the following code in my BowlingGameTest file:
import junit.framework.TestCase;
public class BowlingGameTest extends TestCase {
private Game g;
protected void setUp() throws Exception {
g = new Game();
}
private void rollMany (int n, int pins) {
for (int i = 0; i < n; i++) {
g.roll(pins);
}
}
public void testGutterGame() throws Exception {
rollMany(20,0);
assertEquals(0, g.score());
}
public void testAllOnes() throws Exception {
rollMany(20,1);
assertEquals(20, g.score());
}
public void testOneSpare() throws Exception {
rollSpare();
g.roll(3);
rollMany(17,0);
assertEquals(16,g.score());
}
public void testOneStrike() throws Exception {
g.roll(10); //strike
g.roll(3);
g.roll(4);
rollMany(16,0);
assertEquals(24, g.score());
}
private void rollSpare() {
g.roll(5);
g.roll(5);
}
}
and the following code in my Java class, Game:
public class Game {
private int rolls[] = new int[21];
private int currentRoll = 0;
public void roll(int pins) {
rolls[currentRoll++] = pins;
}
public int score() {
int score = 0;
int frameIndex = 0;
for (int frame = 0; frame < 10; frame++) {
if (rolls[frameIndex] == 10) //strike
{
score += 10 +
rolls[frameIndex + 1] +
rolls[frameIndex + 2];
frameIndex++;
}
else if (isSpare(frameIndex))
{
score += 10 + rolls[frameIndex + 2];
frameIndex += 2;
} else {
score += rolls[frameIndex] +
rolls[frameIndex+1];
frameIndex += 2;
}
}
return score;
}
private boolean isSpare(int frameIndex) {
return rolls[frameIndex] +
rolls[frameIndex + 1] == 10;
}
}
I keep getting 2 errors when testing my program:
How can I fix this? I know I can simply change the numbers in my assertEquals code, but I am wanting those numbers, 16 and 24.
I have three classes, those being Lister, ObjectSortedList and SortedListProgram. I'm having trouble with the iterator for the generic class. What am I doing wrong?
This is the error I get:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 6
at objectsortedlist.ObjectSortedList.getData(ObjectSortedList.java:122)
at objectsortedlist.Lister.hasNext(Lister.java:28)
at objectsortedlist.SortedListProgram.main(SortedListProgram.java:52)
Java Result: 1
Here are my classes:
package objectsortedlist;
import java.util.Iterator;
/**
*
* #author Steven
*/
public class ObjectSortedList<T> implements Cloneable, Iterable<T> {
private T[] data;
private int capacity;
public ObjectSortedList()
{
final int init_capacity = 10;
capacity = 0;
data = (T[])new Object[init_capacity];
}
public ObjectSortedList(int init_capacity)
{
if(init_capacity < 0)
throw new IllegalArgumentException("Initial capacity is negative: " + init_capacity);
capacity = 0;
data = (T[])new Object[init_capacity];
}
private boolean empty()
{
if(data.length == 0 || data[0] == null)
return true;
else
return false;
}
public int length()
{
return capacity;
}
public void insert(T element)
{
if(capacity == data.length)
{
ensureCapacity(capacity * 2 + 1);
}
data[capacity] = element;
capacity++;
}
public boolean delete(T target)
{
int index;
if(target == null)
{
index = 0;
while((index < capacity) && (data[index] != null))
index++;
}
else
{
index = 0;
while((index < capacity) && (!target.equals(data[index])))
index++;
}
if(index == capacity)
return false;
else
{
capacity--;
data[index] = data[capacity];
data[capacity] = null;
return true;
}
}
private void ensureCapacity(int minCapacity)
{
T[] placeholder;
if(data.length < minCapacity)
{
placeholder = (T[])new Object[minCapacity];
System.arraycopy(data, 0, placeholder, 0, capacity);
data = placeholder;
}
}
public ObjectSortedList<T> clone()
{
// Cloning
ObjectSortedList<T> answer;
try
{
answer = (ObjectSortedList<T>) super.clone();
}
catch(CloneNotSupportedException cnse)
{
throw new RuntimeException("This class does not implement cloneable.");
}
answer.data = data.clone();
return answer;
}
#Override
public Iterator<T> iterator()
{
return (Iterator<T>) new Lister<T>(this, 0);
}
public T getData(int index)
{
return (T)data[index];
}
}
package objectsortedlist;
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
*
* #author Steven
*/
public class Lister<T> implements Iterator<T>
{
private ObjectSortedList<T> current;
private int index;
public Lister(ObjectSortedList<T> top, int index)
{
current = top;
this.index = index;
}
#Override
public boolean hasNext()
{
return (current.getData(index) == null);
}
#Override
public T next()
{
T answer;
if(!hasNext())
throw new NoSuchElementException("The Lister is empty.");
answer = current.getData(index+1);
return answer;
}
#Override
public void remove() {
throw new UnsupportedOperationException("Don't use this. Use objectsortedlist.SortedList.delete(T target).");
}
}
package objectsortedlist;
import java.util.Scanner;
/**
*
* #author Steven
*/
public class SortedListProgram {
private static Scanner scan = new Scanner(System.in);
private static String[] phraseArray = {"Hullabaloo!", "Jiggery pokery!", "Fantastic!", "Brilliant!", "Clever!", "Geronimo!", "Fish sticks and custard.", "Spoilers!",
"Exterminate!", "Delete!", "Wibbly-wobbly!", "Timey-wimey!"};
private static Lister<String> print;
public static void main(String args[])
{
int phraseNo = 0;
System.out.println("I'm gonna say some things at you, and you're going to like it."
+ " How many things would you like me to say to you? Put in an integer from 1-12, please.");
try
{
phraseNo = Integer.parseInt(scan.nextLine());
while((phraseNo < 1) || (phraseNo > 12))
{
System.out.println("The integer you entered wasn't between 1 and 12. Make it in between those numbers. Please? Pleaseeeee?");
phraseNo = Integer.parseInt(scan.nextLine());
}
}
catch(NumberFormatException nfe)
{
System.out.println("C'mon, why don't you follow directions?");
phraseNo = 0;
}
if(phraseNo == 0);
else
{
ObjectSortedList<String> phrases = new ObjectSortedList<String>(phraseNo);
for(int i = 0; i < phrases.length(); i++)
{
phrases.insert(phraseArray[i]);
}
print = new Lister<String>(phrases, phraseNo);
while(print.hasNext())
System.out.println(print.next());
}
}
}
After looking at your code I found multiple issues, here are they:
In your SortedListProgram class, in following code the phrases.length() will be 0, so the it will never go in that loop.
ObjectSortedList<String> phrases = new ObjectSortedList<String>(phraseNo);
for(int i = 0; i < phrases.length(); i++)
{
phrases.insert(phraseArray[i]);
}
Moreover in SortedListProgram class's this call sequence
print.hasNext() -> current.getData(index)
the index passed is equal to size of data array field in the
ObjectSortedList class and Since in java array indexes ranges from
zero to array size -1. So you are bound to get
java.lang.ArrayIndexOutOfBoundsException always.
Please correct your code.