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.
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 24 days ago.
Improve this question
I started to learn java and i cant get past my problem with method getting default vaules from class. The code is about cars and garage. Everything works just as I intended with the execption of returning default values for Samochod s1 instead of the values that were set in the main function.
Main:
public static void main(String[] args) {
Samochod s1 = new Samochod("Fiat", "126p", 2, 650, 6.0);
Samochod s2 = new Samochod("Syrena", "105", 2, 800, 7.6);
Garaz g1 = new Garaz();
g1.setAdres( "ul. Garażowa 1" );
g1.setPojemnosc( 1 );
Garaz g2 = new Garaz("ul. Garażowa 2", 2);
g1.wprowadzSamochod(s1);
g1.wypiszInfo();
g1.wprowadzSamochod(s2);
g2.wprowadzSamochod(s2);
g2.wprowadzSamochod(s1);
g2.wypiszInfo();
g2.wyprowadzSamochod();
g2.wypiszInfo();
g2.wyprowadzSamochod();
g2.wyprowadzSamochod();
}
package Lab2_02;
public class Samochod {
private String marka;
private String model;
private int iloscDrzwi;
private int pojemnoscSilnika;
private double srednieSpalanie;
private static int iloscSamochodow = 0;
public String getMarka() {
return marka;
}
public String getModel() {
return model;
}
public int getIloscDrzwi() {
return iloscDrzwi;
}
public int getPojemnoscSilnika() {
return pojemnoscSilnika;
}
public double getSrednieSpalanie() {
return srednieSpalanie;
}
public void setMarka(String marka) {
this.marka = marka;
}
public void setModel(String model) {
this.model = model;
}
public void setIloscDrzwi(int iloscDrzwi) {
this.iloscDrzwi = iloscDrzwi;
}
public void setPojemnoscSilnika(int pojemnoscSilnika) {
this.pojemnoscSilnika = pojemnoscSilnika;
}
public void setSrednieSpalanie(double stednieSpalanie) {
this.srednieSpalanie = stednieSpalanie;
}
public Samochod() {
marka = "nieznany";
model = "nieznany";
iloscDrzwi = 0;
pojemnoscSilnika = 0;
srednieSpalanie = 0.0;
iloscSamochodow++;
}
public Samochod(String marka_, String model_, int iloscDrzwi_, int pojemnoscSilnika_, double srednieSpalanie_) {
marka = marka_;
model = model_;
iloscDrzwi = iloscDrzwi_;
pojemnoscSilnika = pojemnoscSilnika_;
srednieSpalanie = srednieSpalanie_;
iloscSamochodow++;
}
public double obliczSpalanie(double dlugoscTrasy) {
double spalanie = (srednieSpalanie * dlugoscTrasy)/100;
return spalanie;
}
public double obliczKosztPrzejazdu(double dlugoscTrasy, double cenaPaliwa) {
double kosztPrzejazdu = obliczSpalanie(dlugoscTrasy) * cenaPaliwa;
return kosztPrzejazdu;
}
public void wypiszInfo() {
System.out.println("Marka: " + marka);
System.out.println("Model: " + model);
System.out.println("Ilosc drzwi: " + iloscDrzwi);
System.out.println("Pojemnosc silnika: " + pojemnoscSilnika);
System.out.println("Srednie spalanie: " + srednieSpalanie);
}
public static void wypiszIloscSamochodow() {
System.out.println("Ilosc samochodow: " + iloscSamochodow);
}
}
package Lab2_02;
public class Garaz {
private String adres;
private int pojemnosc;
private int liczbaSamochodow = 0;
private Samochod [] samochody;
public String getAdres() {
return adres;
}
public int getPojemnosc() {
return pojemnosc;
}
public void setAdres(String adres) {
this.adres = adres;
}
public void setPojemnosc(int pojemnosc) {
this.pojemnosc = pojemnosc;
samochody = new Samochod[pojemnosc];
}
public Garaz() {
adres = "nieznany";
pojemnosc = 0;
samochody = null;
}
public Garaz(String adres_, int pojemnosc_) {
adres = adres_;
pojemnosc = pojemnosc_;
samochody = new Samochod[pojemnosc];
}
public void wprowadzSamochod(Samochod s) {
if(liczbaSamochodow >= pojemnosc) {
System.out.println("W garazu jest maksymalna ilość pojazdow.");
}
else {
samochody [liczbaSamochodow] = new Samochod();
liczbaSamochodow++;
System.out.println("Samochod zostal wprowadzony.");
}
}
public void wyprowadzSamochod() {
if(liczbaSamochodow == 0) {
System.out.println("W garazu nie ma zadnego auta.");
}
else {
samochody [liczbaSamochodow-1] = null;
liczbaSamochodow--;
System.out.println("Samochod zostal wyprowadzony.");
}
}
public void wypiszInfo(){
for(int i = 0; i <= liczbaSamochodow-1; i++){
samochody[i].wypiszInfo();
}
}
}
So my problem is that instead of returning in console info about my car "Fiat", it say "nieznany" from default class. I know it is simple problem but i can't get past it for a few days. My problem is with this line:
public void wypiszInfo(){
for(int i = 0; i <= liczbaSamochodow-1; i++){
samochody[i].wypiszInfo();
Instead of showing this:
Samochod zostal wprowadzony.
Marka: nieznany
Model: nieznany
Ilosc drzwi: 0
Pojemnosc silnika: 0
Srednie spalanie: 0.0
I can't make it show this:
Marka: Fiat
Model: 126p
Ilosc drzwi: 2
Pojemnosc silnika: 650
Srednie spalanie: 6.0
In wprowadzSamochod(Samochod s) method you're creating a new Samochod instance, instead of using the one passed as parameter. Since you have a default constructor, you are always using it, setting information to default values:
public void wprowadzSamochod(Samochod s) {
if(liczbaSamochodow >= pojemnosc) {
System.out.println("W garazu jest maksymalna ilość pojazdow.");
}
else {
samochody [liczbaSamochodow] = new Samochod(); // <-- there
liczbaSamochodow++;
System.out.println("Samochod zostal wprowadzony.");
}
}
How it should be:
public void wprowadzSamochod(Samochod s) {
if(liczbaSamochodow >= pojemnosc) {
System.out.println("W garazu jest maksymalna ilość pojazdow.");
}
else {
samochody [liczbaSamochodow] = s; // <-- there
liczbaSamochodow++;
System.out.println("Samochod zostal wprowadzony.");
}
}
Just a micro-suggestion: inside the exit condition of a for loop you can just use i < max, instead of i <= max-1 (e.g. in wypiszInfo()).
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;
}
}
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.
I am trying to create a working progress bar program in Java so it can support both console and GUI applications.
The idea is use the thread to provide the current progress information, but it seems the thread code is not working well. Concurrency is so new to me.
I want it to advance the bar every time it is stepped up by one rather than completing the loop prematurely before the progress bar catches up. I guess the problem is timing?
[=====> ] 10% 1
2
3
4
5
6
7
8
9
10
[==================================================] 100%
Can someone tell me what I have gone wrong?
Main code
package console;
import java.util.ArrayList;
import console.ProgressThread;
public class ConsoleProgressBar
{
private static final long REFRESH_DELAY = 50;
private ProgressValue progress;
private ProgressThread target;
private Thread thread;
protected static class ProgressValue
{
protected long total = 0;
protected long current = 0;
protected ProgressValue(long n)
{
total = n;
}
protected synchronized void setMaxTotal(long n)
{
total = n;
}
protected synchronized void stepBy(long n)
{
current = current + n;
if (current > total) total = current;
}
protected synchronized void stepTo(long n)
{
current = n;
if (current > total) total = current;
}
protected synchronized long getCurrent()
{
return current;
}
protected synchronized long getTotal()
{
return total;
}
}
public ConsoleProgressBar(long totalItem)
{
this(totalItem, REFRESH_DELAY);
}
public ConsoleProgressBar(long totalItem, long refreshDelay)
{
progress = new ProgressValue(totalItem);
target = new ProgressThread(progress, refreshDelay);
}
public void start()
{
thread = new Thread(target);
thread.start();
}
public void stepBy(long n)
{
progress.stepBy(n);
}
public void stepTo(long n)
{
progress.stepTo(n);
}
public void step()
{
progress.stepBy(1);
}
public void setMaxTotal(long n)
{
progress.setMaxTotal(n);
}
public void stop()
{
target.terminate();
try
{
thread.join();
}
catch (InterruptedException ex)
{
}
}
public long getCurrent()
{
return progress.getCurrent();
}
public long getTotal()
{
return progress.getTotal();
}
public static void main(String[] args)
{
ArrayList<Integer> test = new ArrayList<>();
ConsoleProgressBar bar = new ConsoleProgressBar(10, 50);
bar.start();
for (int i = 0; i < 10; i++)
{
int sum = i + 5;
test.add(sum);
bar.step();
System.out.format("%s%n", bar.getCurrent());
}
bar.stop();
}
}
Thread code
package console;
import console.ConsoleProgressBar.ProgressValue;
public class ProgressThread implements Runnable
{
private static final int WIDTH = 50;
private volatile boolean terminated;
private ProgressValue progressRef;
private long timeMS;
public ProgressThread(ProgressValue ref, long refreshDelay)
{
progressRef = ref;
timeMS = refreshDelay;
terminated = false;
}
private void refreshProgressBar()
{
StringBuilder sb = new StringBuilder("\r[");
int percent = (int) Math.floor(100.0 * progressRef.current / progressRef.total);
for (int i = 0; i < WIDTH; i++)
{
if (i < (percent / 2)) sb.append("=");
else if (i == (percent / 2)) sb.append(">");
else sb.append(" ");
}
sb.append("] %s ");
if (percent >= 100) sb.append("%n");
System.out.printf(sb.toString(), percent + "%");
}
void terminate()
{
terminated = true;
}
public void run()
{
try
{
while (terminated == false)
{
refreshProgressBar();
Thread.sleep(timeMS);
}
refreshProgressBar();
}
catch (InterruptedException exc)
{
}
}
}
Why do you need a multithreaded application when it is just one task you are trying to achieve?
Nonetheless, to achieve what you want I suggest moving your execution entirely into either the thread class or into the main class.
If the main application is going to run something else, then ideally you'd put the execution in the thread class. However here I've put the execution into the main class. It could also just as easily go in the thread class.
As an example, I've edited run() in ProgressThread to just be this,
public void run()
{
while( terminated )
{
}
}
And I edited main in ConsoleProgressBar to this,
public static void main(String[] args)
{
ArrayList<Integer> test = new ArrayList<>();
ConsoleProgressBar bar = new ConsoleProgressBar(10, 50);
bar.start();
for (int i = 0; i <= 10; i++)
{
int sum = i + 5;
test.add(sum);
bar.refreshProgressBar();
System.out.format( "%s", bar.getCurrent() );
bar.step();
bar.sleep( 1000 );
}
bar.stop();
}
Note that I added the methods sleep( int n ) and refreshProgressBar() to bar so I can call the thread methods, similar to what you did with bar.start() and bar.stop().
To be clear, in ProgressThread I changed refreshProgressBar to public just for the sake of the example and added the following,
void sleep( int n )
{
try
{
Thread.sleep( n );
}
catch( InterruptedException ie )
{
ie.printStackTrace();
}
}
and the following to ConsoleProgressBar,
private void sleep( int n )
{
target.sleep( n );
}
private void refreshProgressBar()
{
target.refreshProgressBar();
}
The output (each line printing at one second intervals) is,
[> ] 0% 0
[=====> ] 10% 1
[==========> ] 20% 2
[===============> ] 30% 3
[====================> ] 40% 4
[=========================> ] 50% 5
[==============================> ] 60% 6
[===================================> ] 70% 7
[========================================> ] 80% 8
[=============================================> ] 90% 9
[==================================================] 100% 10
Not sure if this is what you are looking for but I suggest putting the execution into one place.
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
{