first excuse me for my English it is not strong.
Yesterday a friend tell me about The Sagrada Familia Magic Square that is conformed by 16 numbers in a 4x4 matrix.
According to the creator "Antoni Gaudi" there are 310 possible combinations of 4 number without getting repeated that sums 33 'age at which Jesus died'.
So, i have created a java program using Depth First Search algorithm "just for practice" but i just get 88 combinations, i would like to know if there is anything wrong with my code or if making 310 combinations is not possible.
PDT:"I have searched on internet if it is not possible to make 310 combinations but without lucky".
The program has three classes Nodo, IA, Pila.
"IA is the main part of the project which centralize everything, Nodo is just a Node and Pila is for Stacking purposes"
First, I have divided the matrix 4x4 Sagrada familia in position and values. Position starts at 0 and ends in 15 and each position has a specific values "wath the hastable on IA"
The program creates every possible combination of positions in a DFS way "combinations of four numbers" and then checks if they sum 33.
the value -1 is a special number that means that this position can take any number.
How does it works - tree ('posx','posy','posw','posz')
-1,-1,-1,-1
0,-1,-1,-1 1,-1,-1,-1 . . .
0,1,-1,-1 0,2,-1,-1 . . . 1,0,-1,-1 1,2,-1,-1 . .
0,1,2,-1 . . . . . . . .
0,1,2,3 . . .
Nodo Class
import java.util.Arrays;
/**
*
* #author Vicar
*/
public class Nodo {
private int posx;
private int posy;
private int posw;
private int posz;
private int valx;
private int valy;
private int valw;
private int valz;
public Nodo (){
posx=-1;
posy=-1;
posw=-1;
posz=-1;
valx=-1;
valy=-1;
valw=-1;
valz=-1;
}
public Nodo (int posx, int posy, int posw, int posz, int valx, int valy, int valw, int valz){
this.posx=posx;
this.posy=posy;
this.posw=posw;
this.posz=posz;
this.valx=valx;
this.valy=valy;
this.valw=valw;
this.valz=valz;
}
//returns the sum
public int sumar (){
return valx+valy+valw+valz;
}
//Returns the position of each value
public String retornarPos(){
return posx+","+posy+","+posw+","+posz;
}
//returns the value
public String retornarVal(){
return valx+","+valy+","+valw+","+valz;
}
//Returns the sorted position of the 4 combinations
public String retornarPosOrdenado(){
int [] arreglo ={posx,posy,posw,posz};
Arrays.sort(arreglo);
return arreglo[0]+","+arreglo[1]+","+arreglo[2]+","+arreglo[3];
}
/**
* #return the posx
*/
public int getPosx() {
return posx;
}
/**
* #param posx the posx to set
*/
public void setPosx(int posx) {
this.posx = posx;
}
/**
* #return the posy
*/
public int getPosy() {
return posy;
}
/**
* #param posy the posy to set
*/
public void setPosy(int posy) {
this.posy = posy;
}
/**
* #return the posw
*/
public int getPosw() {
return posw;
}
/**
* #param posw the posw to set
*/
public void setPosw(int posw) {
this.posw = posw;
}
/**
* #return the posz
*/
public int getPosz() {
return posz;
}
/**
* #param posz the posz to set
*/
public void setPosz(int posz) {
this.posz = posz;
}
/**
* #return the valx
*/
public int getValx() {
return valx;
}
/**
* #param valx the valx to set
*/
public void setValx(int valx) {
this.valx = valx;
}
/**
* #return the valy
*/
public int getValy() {
return valy;
}
/**
* #param valy the valy to set
*/
public void setValy(int valy) {
this.valy = valy;
}
/**
* #return the valw
*/
public int getValw() {
return valw;
}
/**
* #param valw the valw to set
*/
public void setValw(int valw) {
this.valw = valw;
}
/**
* #return the valz
*/
public int getValz() {
return valz;
}
/**
* #param valz the valz to set
*/
public void setValz(int valz) {
this.valz = valz;
}
}
Pila class
import java.util.ArrayList;
import java.util.Stack;
/**
*
* #author Vicar
*/
public class Pila {
private Stack <Nodo> pila;
private ArrayList<String> valor;
public Pila (){
pila = new Stack();
valor = new ArrayList<String>();
}
//add a Node to the stack
public void agregar(Nodo nodo){
pila.push(nodo);
valor.add(nodo.retornarPos());
}
//Pops a node from the stack
public Nodo sacar(){
valor.remove(valor.indexOf(pila.peek().retornarPos()));
return pila.pop();
}
// checks if the stack is empty
public boolean estaVacia(){
return pila.isEmpty();
}
// checks if the stack contains an specific node
public boolean contiene(String busqueda){
return valor.contains(busqueda);
}
}
IA Class
import java.util.*;
/**
*
* #author vicar
*/
public class IA {
Hashtable<Integer,Integer> tabla=new Hashtable<Integer,Integer>();
//add the matrix 4,4 to a hastable (pos,val)
public IA(){
tabla.put(0, 1);
tabla.put(1, 14);
tabla.put(2, 14);
tabla.put(3, 4);
tabla.put(4, 11);
tabla.put(5, 7);
tabla.put(6, 6);
tabla.put(7, 9);
tabla.put(8, 8);
tabla.put(9, 10);
tabla.put(10,10);
tabla.put(11, 5);
tabla.put(12, 13);
tabla.put(13, 2);
tabla.put(14, 3);
tabla.put(15, 15);
}
//DFS
public ArrayList<String> busquedaAProfundidad(){
Pila pila = new Pila();
ArrayList <String> visitados = new ArrayList<String>();
ArrayList <Nodo> hijos = new ArrayList<Nodo>();
ArrayList <String> resultado = new ArrayList<String>();
Nodo nodoRaiz = new Nodo();
pila.agregar(nodoRaiz);
//Chsck if the stack is empty
while(!pila.estaVacia()){
Nodo nodo = pila.sacar();
visitados.add(nodo.retornarPos());
//i get every possible children from the node
hijos=crearHijos(nodo);
for (int i = 0; i < hijos.size(); i++) {
//checks that the node is not visited and the sum results in 33
if(!visitados.contains(hijos.get(i).retornarPos()) && !pila.contiene(hijos.get(i).retornarPos())){
if(hijos.get(i).getPosx()!=-1 && hijos.get(i).getPosy()!=-1 && hijos.get(i).getPosw()!=-1 && hijos.get(i).getPosz()!=-1 && hijos.get(i).sumar()==33 ){
//this is the final result without repeted numbers
if(!resultado.contains(hijos.get(i).retornarPosOrdenado())){
resultado.add(hijos.get(i).retornarPosOrdenado());
}
}
else{
//System.err.println("pos: "+hijos.get(i).retornarPosOrdenado());
pila.agregar(hijos.get(i));
}
}
}
}
return resultado;
}
// method to create children from a father node
public ArrayList<Nodo> crearHijos(Nodo padre){
ArrayList <Nodo> hijos = new ArrayList<Nodo>();
//positions of the father
int x = padre.getPosx();
int y = padre.getPosy();
int w = padre.getPosw();
int z = padre.getPosz();
if (x==-1 && y==-1 && w==-1 && z==-1){
for (int i = 0; i < 16; i++) {
hijos.add(new Nodo(i,-1,-1,-1,tabla.get(i),-1,-1,-1));
}
return hijos;
}
else if(x>=0 && y==-1 && w==-1 && z==-1){
for (int i = 0; i < 16; i++) {
if (x != i){
hijos.add(new Nodo(x,i,-1,-1,tabla.get(x),tabla.get(i),-1,-1));
}
}
}
else if(x>=0 && y>=0 && w==-1 && z==-1){
for (int i = 0; i < 16; i++) {
if (x != i && y != i){
hijos.add(new Nodo(x,y,i,-1,tabla.get(x),tabla.get(y),tabla.get(i),-1));
}
}
}
else if(x>=0 && y>=0 && w>=0 && z==-1){
for (int i = 0; i < 16; i++) {
if (x != i && y != i && w !=i){
hijos.add(new Nodo(x,y,w,i,tabla.get(x),tabla.get(y),tabla.get(w),tabla.get(i)));
}
}
}
return hijos;
}
}
a final class to check the result and send the output to a txt file
import java.util.ArrayList;
import java.io.File;
import java.io.FileWriter;
/**
*
* #author vicar
*/
public class Probador {
public static void main(String[] args) {
IA run = new IA();
ArrayList<String> resultado = run.busquedaAProfundidad();
try {
File archivo = new File("/tmp/gaudi.in");
FileWriter escribir = new FileWriter(archivo, true);
for (String resul : resultado) {
escribir.write(resul+"\n");
}
escribir.close();
}
catch (Exception e) {
System.out.println("Error al escribir");
}
}
}
Thanks!!!
The number 310 refers to the number of combinations of any size taking elements from the matrix (without picking the same cell twice). See https://blog.sagradafamilia.org/en/divulgation/the-magic-square-the-passion-facade-keys-to-understanding-it/
Here are the seventeen possible combinations of three numbers: [...]
With four numbers, there are 88 possible combinations that add up to
33; with five, there are 131; and with six, 66. With seven numbers,
there are eight different combinations:...
17 + 88 + 131 + 66 + 8 = 310
Related
I am currently working on a program where I take information from a text document, then I print it out into another file and from java but halfway through, i'm getting an no such exception error and i'm not sure why.
Tester code:
import java.util.ArrayList;
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
public class HurricaneSelectorTester
{
public static void main (String [ ] args) throws IOException
{
//File scanner
File fileName = new File("HurricaneData.txt");
Scanner inFile = new Scanner(fileName);
PrintWriter outputFile = new PrintWriter(new File("OutputData.txt"));
Scanner in;
in = new Scanner(System.in);
//construct a Scanner object with one line
//Declare variables
int arrayLength = 156;
int [] years = new int[156];
int index = 0;
int cat1 = 0;
int cat2 = 0;
int cat3 = 0;
int cat4 = 0;
int cat5 = 0;
double windAvg = 0;
double windTotal = 0;
double windMax = Integer.MIN_VALUE;
double windMin = Integer.MAX_VALUE;
double pressureAvg = 0;
double pressureTotal = 0;
int pressureMax = Integer.MIN_VALUE;
int pressureMin = Integer.MAX_VALUE;
double catAvg = 0;
double catTotal = 0;
int catMax = Integer.MIN_VALUE;
int catMin = Integer.MAX_VALUE;
int rangeMax = 0;
int rangeMin = 0;
//Ask for range
System.out.println("Please enter minimum year (1995-2015)");
rangeMin = in.nextInt();
System.out.println("Please enter maximum year (1995-2015)");
rangeMax = in.nextInt();
//Print title info
System.out.println("Hurricanes "+ ""+ rangeMin + "-" + "" + rangeMax);
System.out.println();
System.out.println("Year Hurricane Category Pressure (mb) Wind Speed (mph)");
System.out.println("****************************************************************");
ArrayList<HurricaneSelector> hurricanes = new ArrayList<HurricaneSelector>();
//Load all the info into the arrays
while (inFile.hasNext())
{
hurricanes.add(new HurricaneSelector(inFile.nextInt(),inFile.next(),inFile.nextInt(),inFile.nextInt(),inFile.next()));
}
for(index = 0; index < 156; index++){
years[index] = inFile.nextInt();
}
inFile.close();
HurricaneSelector dataRecord; //Data record for HurricaneSelector
for(index = 0; index < 156; index++)
{if(years[index]>= rangeMin && years[index]<= rangeMax){
dataRecord = hurricanes.get(index);
dataRecord.calcCategoriesAndTotals();
dataRecord.calcNewWind();
dataRecord.calcWindMax();
dataRecord.calcWindMin();
dataRecord.calcPressureMax();
dataRecord.calcPressureMin();
dataRecord.calcCategoryMax();
dataRecord.calcCategoryMin();
}
}
dataRecord = hurricanes.get(index);
dataRecord.calcWindAverage();
dataRecord.calcCategoryAverage();
dataRecord.calcPressureAverage();
//Print out data
outputFile.println("Year Name Category Pressure Wind Speed");
for (index = 0; index < 156; index++){
if(years[index]>= rangeMin && years[index]<= rangeMax){
System.out.println(" "+hurricanes.get(index));
System.out.println();
outputFile.println(" "+hurricanes.get(index));
}
}
outputFile.close();
System.out.println("****************************************************************");
System.out.print(" Average:");
System.out.printf("%15.1f%13.1f%20.2f",catAvg,pressureAvg,windAvg);
System.out.println();
System.out.print(" Maximum:");
System.out.printf("%15d%13d%20.2f",catMax , pressureMax , windMax);
System.out.println();
System.out.print(" Minimum:");
System.out.printf("%15d%13d%20.2f",catMin , pressureMin , windMin);
System.out.println();
System.out.println();
System.out.println("Summary of categories");
System.out.println(" Category 1: " + cat1);
System.out.println(" Category 2: " + cat2);
System.out.println(" Category 3: " + cat3);
System.out.println(" Category 4: " + cat4);
System.out.println(" Category 5: " + cat5);
}
Methods:
public class HurricaneSelector
{
private int myYear, myPressure, myWind, myRangeMin, myRangeMax, myCategory, category1, category2,category3, category4, category5;
private String myMonth, myName;
private double myNewWind;
public double myWindAverage, myPressureAverage, myCategoryAverage, myWindMax = Integer.MIN_VALUE,
myWindMin = Integer.MAX_VALUE, myPressureMax = Integer.MIN_VALUE, myPressureMin = Integer.MAX_VALUE,
myCatMax = Integer.MIN_VALUE,myCatMin = Integer.MAX_VALUE;
public int total;
/**
* Constructor for objects of type HurricaneSelector
* #param year is the year of the hurricane
* #param month is the month of the hurricane
* #param pressure is the pressure of the hurricane
* #param wind is the wind speed of the hurricane
* #param name is the name of the hurricane
*/
HurricaneSelector(int year, String month, int pressure, int wind, String name)
{
myYear = year;
myMonth = month;
myPressure = pressure;
myWind = wind;
myName = name;
}
/**
* Mutator method to calculate the wind speed in mph (no parameters)
*/
public void calcNewWind()
{
myNewWind = (myWind* 1.15);
}
/**
* Mutator method to calculate if the value is the new Maximum (no parameters)
*/
public void calcWindMax()
{
if (myNewWind > myWindMax){
myWindMax = myNewWind;
}
}
/**
* Mutator method to calculate if the value is the new Minimum (no parameters)
*/
public void calcWindMin()
{
if (myNewWind > myWindMin){
myWindMin = myNewWind;
}
}
/**
* Mutator method to calculate if the value is the new Maximum (no parameters)
*/
public void calcPressureMax()
{
if (myPressure > myPressureMax){
myPressureMax = myPressure;
}
}
/**
* Mutator method to calculate if the value is the new Minimum (no parameters)
*/
public void calcPressureMin()
{
if (myPressure > myPressureMin){
myPressureMin = myPressure;
}
}
/**
* Mutator method to calculate if the value is the new Maximum (no parameters)
*/
public void calcCategoryMax()
{
if (myCategory > myCatMax){
myCatMax = myCategory;
}
}
/**
* Mutator method to calculate if the value is the new Minimum (no parameters)
*/
public void calcCategoryMin()
{
if (myCategory > myCatMin){
myCatMin = myCategory;
}
}
/**
* Mutator method to calculate which category the Hurricane fits into and get the totals(no parameters)
*/
public void calcCategoriesAndTotals()
{
myWindAverage += myNewWind;
myPressureAverage += myPressure;
if (myNewWind > 74 && myNewWind < 95)
{
myCategory = 1;
myCategoryAverage += myCategory;
category1++;
}
else if(myNewWind > 96 && myNewWind < 110)
{
myCategory = 2;
myCategoryAverage += myCategory;
category2++;
}
else if(myNewWind > 111 && myNewWind < 129)
{
myCategory = 3;
myCategoryAverage += myCategory;
category3++;
}
else if(myNewWind > 130 && myNewWind < 156)
{
myCategory = 4;
myCategoryAverage += myCategory;
category4++;
}
else if(myNewWind > 157)
{
myCategory = 5;
myCategoryAverage += myCategory;
category5++;
}
total++;
}
/**
* Mutator method to calculate the wind speed average (no parameters)
*/
public void calcWindAverage()
{
myWindAverage = myWindAverage/total;
}
/**
* Mutator method to calculate the category average (no parameters)
*/
public void calcCategoryAverage()
{
myCategoryAverage = myCategoryAverage/total;
}
/**
* Mutator method to calculate the pressure average (no parameters)
*/
public void calcPressureAverage()
{
myPressureAverage = myPressureAverage/total;
}
/**
* Getter method to return the year of the hurricane (no parameters)
*/
public int getYear()
{
return myYear;
}
/**
* Getter method to return the month of the hurricane (no parameters)
*/
public String getMonth()
{
return myMonth;
}
/**
* Getter method to return the pressure of the hurricane (no parameters)
*/
public int getPressure()
{
return myPressure;
}
/**
* Getter method to return the wind speed of the hurricane (no parameters)
*/
public double getNewWind()
{
return myNewWind;
}
/**
* Getter method to return the name of the hurricane (no parameters)
*/
public String getName()
{
return myName;
}
/**
* Getter method to return the wind average (no parameters)
*/
public Double getWindAverage()
{
return myWindAverage;
}
/**
* Getter method to return the pressure average (no parameters)
*/
public Double getPressureAverage()
{
return myPressureAverage;
}
/**
* Getter method to return the category average (no parameters)
*/
public Double getCategoryAverage()
{
return myCategoryAverage;
}
/**
* Getter method to return the category maximum (no parameters)
*/
public Double getWindMax()
{
return myWindMax;
}
/**
* Getter method to return the category minimum (no parameters)
*/
public Double getWindMin()
{
return myWindMin;
}
/**
* Getter method to return the category maximum (no parameters)
*/
public Double getPressureMax()
{
return myPressureMax;
}
/**
* Getter method to return the category minimum (no parameters)
*/
public Double getPressureMin()
{
return myPressureMin;
}
/**
* Getter method to return the category maximum (no parameters)
*/
public Double getCategoryMax()
{
return myCatMax;
}
/**
* Getter method to return the category minimum (no parameters)
*/
public Double getCategoryMin()
{
return myCatMax;
}
public String toString(){
return String.format("%10d%10s%10d%10d%10.2f",myYear,myName, myCategory, myPressure, myNewWind);
}
The links to the text files: https://drive.google.com/file/d/1eazHCEwT0Se6hfx2SDilqCqY8ZMi4E9k/view?usp=sharing
https://drive.google.com/file/d/1CN0JnlbMWNEB7B4nomgJ_-6mkwR1wgYc/view?usp=sharing
I know there are other problems with the code such as useless variables, formatting, etc. but right now I need to fix the program so that it can actually run and print out most of the data right now.
You need to reset() the Scanner because you've reached the end in your loop, and you want to start from the beginning for the next set of operations.
From JavaSE docs:
public int nextInt()
Scans the next token of the input as an int.
An invocation of this method of the form nextInt() behaves in exactly the same way as the invocation nextInt(radix), where radix is the default radix of this scanner.
Returns:
the int scanned from the input
Throws:
InputMismatchException - if the next token does not match the Integer regular expression, or is out of range
NoSuchElementException - if input is exhausted
IllegalStateException - if this scanner is closed
Thank you for everyone who got me on my feet. However, My cutSplice method is inefficient. I need to be able to modify it easy so that i can do the reverse method.
developing a single Java class (LinkedDnaStrand) that uses a linked list of nodes to represent a strand of DNA that supports splicing. Each node in the list will contain a string of one or more nucleotides (A, C, G, or T). The class will be responsible for operations such as append() and cutSplice(), which model real-world restriction enzyme processing.
EX. tt will be replaced with cat. (Better LinkedDnaStrandTester)
package dnasplicing;
public class DnaSequenceNode {
public String dnaSequence;
public DnaSequenceNode previous;
public DnaSequenceNode next;
public DnaSequenceNode(String initialDnaSequence) {
dnaSequence = initialDnaSequence;
}
}
package dnasplicing;
public class LinkedDnaStrand implements DnaStrand {
int nodeCount = 0;
int appendCount = 0;
long nucleotideCount = 0;
String sequenceString;
DnaSequenceNode cursor, head, tail;
public LinkedDnaStrand(String dnaSequence) {
DnaSequenceNode newNode = new DnaSequenceNode(dnaSequence);
head = newNode;
cursor = head;
tail = head;
head.previous = null;
tail.previous = null;
sequenceString = dnaSequence;
nodeCount++;
}
public String toString() {
String result = "";
DnaSequenceNode n = head;
while (n != null) {
result += n.dnaSequence;
n = n.next;
}
return result;
}
#Override
public long getNucleotideCount() {
nucleotideCount = sequenceString.length();
return nucleotideCount;
}
#Override
public void append(String dnaSequence) {
if (dnaSequence != null && dnaSequence.length() > 0) {
tail.next = new DnaSequenceNode(dnaSequence);
tail.next.previous = tail;
tail = tail.next;
sequenceString += dnaSequence;
appendCount++;
nodeCount++;
}
}
#Override
public DnaStrand cutSplice(String enzyme, String splicee) {
boolean frontSplice = false;
boolean backSplice = false;
if (sequenceString.startsWith(enzyme)) {
frontSplice = true;
}
if (sequenceString.endsWith(enzyme)) {
backSplice = true;
}
String[] dnaParts = sequenceString.split(enzyme);
LinkedDnaStrand newLinkedStrand = null;
if (frontSplice == true) {
newLinkedStrand = new LinkedDnaStrand(splicee);
// newLinkedStrand.append(dnaParts[0]);
for (int i = 1; i < dnaParts.length; i++) {
newLinkedStrand.append(dnaParts[i]);
if (i < dnaParts.length - 1) {
newLinkedStrand.append(splicee);
}
}
} else {
newLinkedStrand = new LinkedDnaStrand(dnaParts[0]);
for (int index = 1; index < dnaParts.length; index++) {
newLinkedStrand.append(splicee);
newLinkedStrand.append(dnaParts[index]);
}
}
if (backSplice == true) {
newLinkedStrand.append(splicee);
}
// sequenceString = newLinkedStrand.toString();
return newLinkedStrand;
}
#Override
public DnaStrand createReversedDnaStrand() {
// TODO Auto-generated method stub
return null;
}
#Override
public int getAppendCount() {
// TODO Auto-generated method stub
return appendCount;
}
#Override
public DnaSequenceNode getFirstNode() {
return head;
}
#Override
public int getNodeCount() {
return nodeCount;
}
}
package dnasplicing;
public interface DnaStrand {
/**
* NOTE: Your LinkedDnaStrand class must have a constructor that takes one parameter: String dnaSequence. When the
* constructor completes, your linked list should have just one node, and it should contain the passed-in
* dnaSequence. For example, if the following line of code was executed:
*
* LinkedDnaStrand strand = new LinkedDnaStrand("GATTACA");
*
* Then strand's linked list should look something like (previous pointers not shown):
*
* first -> "GATTACA" -> null
*
* The first line of this constructor should look like:
*
* public LinkedDnaStrand(String dnaSequence) {
*/
/**
* #return The entire DNA sequence represented by this DnaStrand.
*/
public String toString();
/**
* Returns the number of nucleotides in this strand.
*
* #return the number of base-pairs in this strand
*/
public long getNucleotideCount();
/**
* Appends the given dnaSequence on to the end of this DnaStrand. appendCount is incremented. Note: If this
* DnaStrand is empty, append() should just do the same thing as the constructor. In this special case, appendCount
* is not incremented.
*
* #param dnaSequence
* is the DNA string to append
*/
public void append(String dnaSequence);
/**
* This method creates a <bold>new</bold> DnaStrand that is a clone of the current DnaStrand, but with every
* instance of enzyme replaced by splicee. For example, if the LinkedDnaStrand is instantiated with "TTGATCC", and
* cutSplice("GAT", "TTAAGG") is called, then the linked list should become something like (previous pointers not
* shown):
*
* first -> "TT" -> "TTAAGG" -> "CC" -> null
*
* <b>NOTE</b>: This method will only be called when the linke list has just one node, and it will only be called
* once for a DnaStrand. This means that you do not need to worry about searching for enzyme matches across node
* boundaries.
*
* #param enzyme
* is the DNA sequence to search for in this DnaStrand.
*
* #param splicee
* is the DNA sequence to append in place of the enzyme in the returned DnaStrand
*
* #return A <bold>new</bold> strand leaving the original strand unchanged.
*/
public DnaStrand cutSplice(String enzyme, String splicee);
/**
* Returns a <bold>new</bold> DnaStrand that is the reverse of this strand, e.g., if this DnaStrand contains "CGAT",
* then the returned DnaStrand should contain "TAGC".
*
* #return A <bold>new</bold> strand containing a reversed DNA sequence.
*/
public DnaStrand createReversedDnaStrand();
/**
*
* #return The number of times that the DnaStrand has been appended via a call to append() or during the cutSplice()
* operation. Note that the very first time that a DnaStrand is given a DNA sequence is not to be counted as
* an append.
*/
public int getAppendCount();
/**
* This is a utility method that allows the outside world direct access to the nodes in the linked list.
*
* #return The first DnaSequenceNode in the linked list of nodes.
*/
public DnaSequenceNode getFirstNode();
/**
* This is a utility method that allows the outside world to determine the number of nodes in the linked list.
*
* #return
*/
public int getNodeCount();
}
package sbccunittest;
import static java.lang.Math.*;
import static java.lang.System.*;
import static org.apache.commons.lang3.StringUtils.*;
import static org.junit.Assert.*;
import java.io.*;
import org.apache.commons.lang3.*;
import org.junit.*;
import dnasplicing.*;
// Updated 25-Feb-2016 at 6:10pm
public class LinkedDnaStrandTester {
static String ecoliSmall = "AGCTTTTCATTAGCCCGCAGGCAGCCCCACACCCGCCGCCTCCTGCACCGAGAGAGATGGAATAAAGCCCTTGAACCAGC";
static String ecor1 = "GAATTC"; // restriction enzyme
public static int totalScore = 0;
public static int extraCredit = 0;
public static InputStream defaultSystemIn;
public static PrintStream defaultSystemOut;
public static PrintStream defaultSystemErr;
public static String newLine = System.getProperty("line.separator");
public void testCutSplice() {
String enzyme = "GAT";
String splicee = "TTAAGG";
String[] strands = { "TTGATCC", "TCGATCTGATTTCCGATCC", "GATCTGATCTGAT" };
String[][] recombinants = { { "TT", "TTAAGG", "CC" },
{ "TC", "TTAAGG", "CT", "TTAAGG", "TTCC", "TTAAGG", "CC" },
{ "TTAAGG", "CT", "TTAAGG", "CT", "TTAAGG" } };
for (int ndx = 0; ndx < strands.length; ndx++) {
LinkedDnaStrand linkedStrand = new LinkedDnaStrand(strands[ndx]);
DnaStrand newlinkedStrand = linkedStrand.cutSplice(enzyme, splicee);
assertEquals("cutSplice(" + enzyme + ", " + splicee + ") failed at ndx = " + ndx, join(recombinants[ndx]),
newlinkedStrand.toString());
assertEquals("Append counts didn't match for ndx = " + ndx, recombinants[ndx].length - 1,
newlinkedStrand.getAppendCount());
// Verify that each node contains the correct DNA sequence
DnaSequenceNode node = newlinkedStrand.getFirstNode();
for (int nodeNdx = 0; nodeNdx < recombinants.length; nodeNdx++) {
assertNotNull("For strand " + ndx + ", there is no node at position " + nodeNdx, node);
assertEquals("For strand " + ndx + ", the sequences don't match at position " + nodeNdx,
recombinants[ndx][nodeNdx], node.dnaSequence);
node = node.next;
}
}
totalScore += 5;
}
/**
* Verifies that LinkedDnaStrand can model a cut and splice of (part of) the E Coli sequence using the ECoR1
* restriction enzyme and insulin as a splicee.
*/
#Test
public void testSpliceInsulinIntoEcoli() {
for (int testNumber = 1; testNumber <= 5; testNumber++) {
int startNdx = (int) (random() * 0.33 * ecoliSmall.length()); // Somewhere in the
// first third
int endNdx = ecoliSmall.length() - 1 - (int) (random() * 0.33 * ecoliSmall.length());
String ecoliPart = ecoliSmall.substring(startNdx, endNdx);
LinkedDnaStrand linkedStrand = new LinkedDnaStrand(ecoliPart);
SimpleDnaStrand simpleStrand = new SimpleDnaStrand(ecoliPart);
DnaStrand newL = linkedStrand.cutSplice(ecor1, insulin);
DnaStrand newS = simpleStrand.cutSplice(ecor1, insulin);
assertEquals(newS.toString(), newL.toString());
assertEquals(newS.getAppendCount(), newL.getAppendCount());
assertEquals(newS.getAppendCount(), newL.getNodeCount() - 1);
// Verify that the nodes exist
DnaSequenceNode node = newL.getFirstNode();
for (int ndx = 0; ndx < newL.getNodeCount(); ndx++) {
assertNotNull("There is no node at position " + ndx, node);
node = node.next;
}
}
totalScore += 10;
}
/**
* Verifies that LinkedDnaStrand can model a cut and splice efficiently.
*/
#Test
public void testSplicingTime() {
// First verify that the LinkedDnaStrand cutSplice works
int startNdx = (int) (random() * 0.33 * ecoliSmall.length()); // Somewhere in the first
// third
int endNdx = ecoliSmall.length() - 1 - (int) (random() * 0.33 * ecoliSmall.length());
String ecoliPart = ecoliSmall.substring(startNdx, endNdx);
LinkedDnaStrand linkedStrand = new LinkedDnaStrand(ecoliPart);
SimpleDnaStrand simpleStrand = new SimpleDnaStrand(ecoliPart);
String splicee = createRandomDnaSequence(1024 * 1024, 1024 * 1024);
DnaStrand newL = linkedStrand.cutSplice(ecor1, splicee);
DnaStrand newS = simpleStrand.cutSplice(ecor1, splicee);
assertEquals(newS.toString(), newL.toString());
assertEquals(newS.getAppendCount(), newL.getAppendCount());
// Now verify that it can cut and splice N times in less than T seconds
int numSplicings = 200;
double maxTime = 2.0;
double start = nanoTime();
for (int i = 0; i < numSplicings; i++)
newL = linkedStrand.cutSplice(ecor1, splicee);
double end = nanoTime();
double time = ((end - start) / 1e9);
// out.println("Time = " + time);
assertTrue("Time limit of " + maxTime + " seconds exceeded. Time to splice " + numSplicings + " times was "
+ time + " seconds.", time <= maxTime);
totalScore += 5;
}
/**
* Verifies that LinkedDnaStrand can create a new, reversed LinkedDnaStrand.
*/
#Test
public void testReverse() {
String dnaSequence = createRandomDnaSequence(50, 100);
String dnaToAppend = createRandomDnaSequence(5, 10);
int numTimesToAppend = (int) (random() * 10);
LinkedDnaStrand linkedStrand = new LinkedDnaStrand(dnaSequence);
SimpleDnaStrand simpleStrand = new SimpleDnaStrand(dnaSequence);
for (int ndx = 0; ndx < numTimesToAppend; ndx++) {
linkedStrand.append(dnaToAppend);
simpleStrand.append(dnaToAppend);
}
assertEquals(simpleStrand.toString(), linkedStrand.toString());
assertEquals(numTimesToAppend + 1, linkedStrand.getNodeCount());
LinkedDnaStrand rl = (LinkedDnaStrand) linkedStrand.createReversedDnaStrand();
// Verify that the original linked strand wasn't changed
DnaSequenceNode node = linkedStrand.getFirstNode();
int nodeNdx = 0;
while (node != null) {
assertEquals("Sequences don't match at node index " + nodeNdx, nodeNdx == 0 ? dnaSequence : dnaToAppend,
node.dnaSequence);
node = node.next;
nodeNdx++;
}
// Verify that the new strand string is reversed
assertEquals(simpleStrand.createReversedDnaStrand().toString(), rl.toString());
totalScore += 10;
// If the new strand has a reverse order of nodes and sequences within each node, give extra
// credit
int numNodes = linkedStrand.getNodeCount();
if (numNodes == rl.getNodeCount()) {
// Build array of reversed dna strings from original LinkedDnaStrand. Start at end of
// array and move toward
// start
node = linkedStrand.getFirstNode();
String[] reversedDnaSequences = new String[linkedStrand.getNodeCount()];
nodeNdx = numNodes - 1;
while (node != null) {
reversedDnaSequences[nodeNdx] = reverse(node.dnaSequence);
node = node.next;
nodeNdx--;
}
// Verify that the reversed list's nodes contain the same data as in the array
node = rl.getFirstNode();
nodeNdx = 0;
while (node != null) {
if (!node.dnaSequence.equals(reversedDnaSequences[nodeNdx]))
break;
node = node.next;
nodeNdx++;
}
if (nodeNdx == linkedStrand.getNodeCount())
extraCredit += 5;
}
}
private String[] createRandomDnaSequences(int numDnaSequences, int minLength, int maxLength) {
String[] dnaSequences = new String[numDnaSequences];
for (int ndx = 0; ndx < numDnaSequences; ndx++)
dnaSequences[ndx] = createRandomDnaSequence(minLength, maxLength);
return dnaSequences;
}
private String createRandomDnaSequence(int minLength, int maxLength) {
return RandomStringUtils.random((int) (random() * (maxLength - minLength) + minLength), "ACGT");
}
#BeforeClass
public static void beforeTesting() throws Exception {
totalScore = 0;
extraCredit = 0;
}
#AfterClass
public static void afterTesting() {
out.println("Estimated score (w/o late penalties, etc.) = " + totalScore);
out.println("Estimated extra credit (assuming on time submission) = " + extraCredit);
}
#Before
public void setUp() throws Exception {
defaultSystemIn = System.in;
defaultSystemOut = System.out;
defaultSystemErr = System.err;
}
#After
public void tearDown() throws Exception {
System.setIn(defaultSystemIn);
System.setOut(defaultSystemOut);
System.setErr(defaultSystemErr);
}
public void sendToStdinOfTestee(String message) {
System.setIn(new ByteArrayInputStream(message.getBytes()));
}
}
So I don't have some of the classes like the node class you are using so I cannot write the actual code but i will give you some pseudo code.
public String toString(){
String result = "";
Node n = start;
while(n != null){
string += n.data;
}
return result;
}
public long getNucleotideCount() {
long result = 0;
Node n = start;
while(n != null){
result += n.data.length();
}
return result;
}
public void append(String dnaSequence) {
end.next = new Node(dnaSequence);
end = end.next;
appendCount++;
}
public DnaStrand cutSplice(String enzyme, String splice) {
// For this I think it would be best to assemble into string then use replace
Node n = start;
String result = "";
while(n != null){
result += n.data;
}
result = result.replace(enzyme, splice)
return new DnaStrand(result);
}
The reverse method would be similar to cutSplice. Assemble to string, manipulate, then return new strand. If you need more help LMK.
I'm making a game similar to solitaire, and when the user recognizes they have lost I have a button to reset the game. Currently I'm unsure how I can reset the game. I know ill have to make a new deck and clear my array to recreate everything as if the game was starting for the first time, but I don't know how to do this. How can I reset my game when a user presses reset?
/**
* This is a class that tests the Deck class.
*/
public class DeckTester {
/**
* The main method in this class checks the Deck operations for consistency.
* #param args is not used.
*/
public static void main(String[] args) {
Board board = new Board();
board.startGame();
}
}
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
/**
* The Deck class represents a shuffled deck of cards.
* It provides several operations including
* initialize, shuffle, deal, and check if empty.
*/
public class Deck {
/**
* cards contains all the cards in the deck.
*/
private List<Card> cards;
/**
* size is the number of not-yet-dealt cards.
* Cards are dealt from the top (highest index) down.
* The next card to be dealt is at size - 1.
*/
private int size;
/**
* Creates a new <code>Deck</code> instance.<BR>
* It pairs each element of ranks with each element of suits,
* and produces one of the corresponding card.
* #param ranks is an array containing all of the card ranks.
* #param suits is an array containing all of the card suits.
* #param values is an array containing all of the card point values.
*/
ArrayList<Card> cardList = new ArrayList<>();
String[] ranks = {"Ace","Two","Three","Four","Five","Six" , "Seven" , "Eight","Nine","Ten", "Jack", "Queen","King"};
String[] suits = {"spades" , "diamonds" , "clubs" , "hearts"};
int[] values = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13};
boolean selected = false;
public Deck() {
cards = new ArrayList<Card>();
for (int j = 0; j < ranks.length; j++) {
for (String suitString : suits) {
cards.add(new Card(ranks[j], suitString, values[j], selected));
}
}
size = cards.size();
}
public Card nextCard() {
if(cards.size() > 0) {
System.out.println(cards.get(0).toString());
return cards.remove(0);
}else{
return null;
}
}
/**
* Determines if this deck is empty (no undealt cards).
* #return true if this deck is empty, false otherwise.
*/
public boolean isEmpty() {
return size == 0;
}
/**
* Accesses the number of undealt cards in this deck.
* #return the number of undealt cards in this deck.
*/
public int size() {
return cards.size();
}
/**
* Randomly permute the given collection of cards
* and reset the size to represent the entire deck.
*/
List<Card> shuffledDeck;
ArrayList<Integer> usedNumbers = new ArrayList<Integer>();
public void shuffle() {
shuffledDeck = new ArrayList<>();
Random random = new Random();
for(usedNumbers.size(); usedNumbers.size() < 52;) {
int randomNum = random.nextInt(52);
if(!usedNumbers.contains(randomNum)) {
shuffledDeck.add(usedNumbers.size(), cards.get(randomNum));
usedNumbers.add(randomNum);
}
}
size = shuffledDeck.size();
cards = shuffledDeck;
}
/**
* Generates and returns a string representation of this deck.
* #return a string representation of this deck.
*/
#Override
public String toString() {
String rtn = "size = " + size + "\nUndealt cards: \n";
for (int k = cards.size() - 1; k >= 0; k--) {
rtn = rtn + cards.get(k);
if (k != 0) {
rtn = rtn + ", ";
}
if ((size - k) % 2 == 0) {
// Insert carriage returns so entire deck is visible on console.
rtn = rtn + "\n";
}
}
rtn = rtn + "\nDealt cards: \n";
for (int k = cards.size() - 1; k >= size; k--) {
rtn = rtn + cards.get(k);
if (k != size) {
rtn = rtn + ", ";
}
if ((k - cards.size()) % 2 == 0) {
// Insert carriage returns so entire deck is visible on console.
rtn = rtn + "\n";
}
}
rtn = rtn + "\n";
return rtn;
}
}
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Board extends JFrame implements ActionListener {
Deck deck = new Deck();
Card card;
JPanel buttonPanel = new JPanel();
JPanel menuPanel = new JPanel();
JButton cardOne = new JButton();
JButton cardTwo = new JButton();
JButton cardThree = new JButton();
JButton cardFour = new JButton();
JButton cardFive = new JButton();
JButton cardSix = new JButton();
JButton cardSeven = new JButton();
JButton[] buttons = {cardOne, cardTwo, cardThree, cardFour, cardFive, cardSix, cardSeven};
int winCount = 0;
int lossCount = 0;
int deckCount = 52;
JButton replace = new JButton("Replace");
JButton reset = new JButton("Reset");
JLabel cardsLeft = new JLabel("Cards left:" + deckCount);
JLabel winLossLabel = new JLabel("Win: " + winCount + "\tLoss: " + lossCount);
public Board() {
initGUI();
}
ArrayList<Card> boardArray = new ArrayList<>();
public void startGame() {
deck.shuffle();
Card card;
for(int i = 0 ; i <=6 ; i++) {
boardArray.add(card = deck.nextCard());
buttons[i].setIcon(card.cardImage);
}
}
public void initGUI() {
setTitle("Elevens");
setLayout(new GridLayout(1,2));
buttonPanel.setLayout(new GridLayout(2,4));
menuPanel.setLayout(new GridLayout(4,1));
setResizable(false);
buttonPanel.add(cardOne);
buttonPanel.add(cardTwo);
buttonPanel.add(cardThree);
buttonPanel.add(cardFour);
buttonPanel.add(cardFive);
buttonPanel.add(cardSix);
buttonPanel.add(cardSeven);
menuPanel.add(replace);
menuPanel.add(reset);
menuPanel.add(cardsLeft);
menuPanel.add(winLossLabel);
add(buttonPanel);
add(menuPanel);
for(int i = 0; i < buttons.length; i++){
buttons[i].addActionListener(this);
}
replace.addActionListener(this);
reset.addActionListener(this);
replace.setSize(new Dimension (100,10));
pack();
setVisible(true);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(600,300);
}
ImageIcon selectedIcon;
Boolean selected = false;
String newPathString;
int buttonNumber;
public void getPath(int buttonNumber) {
String path = "/Users/AlecR/Documents/workspace/Elevens Lab Midyear Exam/src/";
if(boardArray.get(buttonNumber).rank() == "Ace" || boardArray.get(buttonNumber).rank() == "Jack" || boardArray.get(buttonNumber).rank() == "Queen" || boardArray.get(buttonNumber).rank() == "King") {
newPathString = path + boardArray.get(buttonNumber).rank() + boardArray.get(buttonNumber).suit() + "S.GIF";
}else{
newPathString = path + Integer.toString(boardArray.get(buttonNumber).pointValue()) + boardArray.get(buttonNumber).suit() + "S.GIF";
}
selectedIcon = new ImageIcon(newPathString);
}
public void actionPerformed(ActionEvent e) {
if(e.getSource() == cardOne) {
if(boardArray.get(0).selected == false) {
getPath(0);
buttons[0].setIcon(selectedIcon);
boardArray.get(0).selected = true;
}else{
boardArray.get(0).selected = false;
buttons[0].setIcon(boardArray.get(0).cardImage);
}
}
if(e.getSource() == cardTwo) {
if(boardArray.get(1).selected == false) {
getPath(1);
buttons[1].setIcon(selectedIcon);
boardArray.get(1).selected = true;
}else{
boardArray.get(1).selected = false;
buttons[1].setIcon(boardArray.get(1).cardImage);
}
}
if(e.getSource() == cardThree) {
if(boardArray.get(2).selected == false) {
getPath(2);
buttons[2].setIcon(selectedIcon);
boardArray.get(2).selected = true;
}else{
boardArray.get(2).selected = false;
buttons[2].setIcon(boardArray.get(2).cardImage);
}
}
if(e.getSource() == cardFour) {
if(boardArray.get(3).selected == false) {
getPath(3);
buttons[3].setIcon(selectedIcon);
boardArray.get(3).selected = true;
}else{
boardArray.get(3).selected = false;
buttons[3].setIcon(boardArray.get(3).cardImage);
}
}
if(e.getSource() == cardFive) {
if(boardArray.get(4).selected == false) {
getPath(4);
buttons[4].setIcon(selectedIcon);
boardArray.get(4).selected = true;
}else{
boardArray.get(4).selected = false;
buttons[4].setIcon(boardArray.get(4).cardImage);
}
}
if(e.getSource() == cardSix) {
if(boardArray.get(5).selected == false) {
getPath(5);
buttons[5].setIcon(selectedIcon);
boardArray.get(5).selected = true;
}else{
boardArray.get(5).selected = false;
buttons[5].setIcon(boardArray.get(5).cardImage);
}
}
if(e.getSource() == cardSeven) {
if(boardArray.get(6).selected == false) {
getPath(6);
buttons[6].setIcon(selectedIcon);
boardArray.get(6).selected = true;
}else{
boardArray.get(6).selected = false;
buttons[6].setIcon(boardArray.get(6).cardImage);
}
}
if(e.getSource() == replace) {
checkWin();
}
if(e.getSource() == reset) {
System.out.println("Feature In Progress. Exit game to reset.");
}
}
int total;
int buttonsSelected = 0;
public void checkWin() {
for(int i = 0; i <= 6; i++) {
if(boardArray.get(i).selected == true) {
int pointValue = boardArray.get(i).pointValue();
total = total + pointValue;
buttonsSelected++;
}
}
if((buttonsSelected == 3 && total == 36) || (buttonsSelected == 2 && total == 11)) {
for(int i = 0; i <= 6; i++) {
if(boardArray.get(i).selected == true) {
boardArray.set(i, deck.nextCard());
buttons[i].setIcon(boardArray.get(i).cardImage);
deckCount--;
cardsLeft.setText("Cards left:" + deckCount);
}
}
}
total = 0;
buttonsSelected = 0;
}
}
import javax.swing.ImageIcon;
/**
* Card.java
*
* <code>Card</code> represents a playing card.
*/
public class Card {
/**
* String value that holds the suit of the card
*/
private String suit;
/**
* String value that holds the rank of the card
*/
private String rank;
/**
* int value that holds the point value.
*/
private int pointValue;
/**
* Creates a new <code>Card</code> instance.
*
* #param cardRank
* a <code>String</code> value containing the rank of the card
* #param cardSuit
* a <code>String</code> value containing the suit of the card
* #param cardPointValue
* an <code>int</code> value containing the point value of the
* card
*/
ImageIcon cardImage;
Card card;
Boolean selected = false;
int picNumber = 1;
public Card(String cardRank, String cardSuit, int cardPointValue, Boolean selected) {
// initializes a new Card with the given rank, suit, and point value
rank = cardRank;
suit = cardSuit;
pointValue = cardPointValue;
selected = false;
String pointString = Integer.toString(pointValue);
String path = "/Users/AlecR/Documents/workspace/Elevens Lab Midyear Exam/src/";
if (cardPointValue >= 2 && cardPointValue <= 10) {
String cardImageString = path + pointString + cardSuit + ".GIF";
cardImage = new ImageIcon(cardImageString);
}
if (cardPointValue == 1) {
}
switch (pointValue) {
case 1:
cardImage = new ImageIcon(path + "ace" + cardSuit + ".GIF");
break;
case 11:
cardImage = new ImageIcon(path + "jack" + cardSuit + ".GIF");
break;
case 12:
cardImage = new ImageIcon(path + "queen" + cardSuit + ".GIF");
break;
case 13:
cardImage = new ImageIcon(path + "king" + cardSuit + ".GIF");
break;
}
}
public String getCardImage() {
return cardImage.toString();
}
/**
* Accesses this <code>Card's</code> suit.
*
* #return this <code>Card's</code> suit.
*/
public String suit() {
return suit;
}
/**
* Accesses this <code>Card's</code> rank.
*
* #return this <code>Card's</code> rank.
*/
public String rank() {
return rank;
}
/**
* Accesses this <code>Card's</code> point value.
*
* #return this <code>Card's</code> point value.
*/
public int pointValue() {
return pointValue;
}
/**
* Compare this card with the argument.
*
* #param otherCard
* the other card to compare to this
* #return true if the rank, suit, and point value of this card are equal to
* those of the argument; false otherwise.
*/
public boolean matches(Card otherCard) {
return otherCard.suit().equals(this.suit())
&& otherCard.rank().equals(this.rank())
&& otherCard.pointValue() == this.pointValue();
}
/**
* Converts the rank, suit, and point value into a string in the format
* "[Rank] of [Suit] (point value = [PointValue])". This provides a useful
* way of printing the contents of a <code>Deck</code> in an easily readable
* format or performing other similar functions.
*
* #return a <code>String</code> containing the rank, suit, and point value
* of the card.
*/
#Override
public String toString() {
return rank + " of " + suit + " (point value = " + pointValue + ")";
}
}
When it resets, it is basically same as the state when you start a new game.
When starting a new game:
1) Create deck
2) Shuffle deck
3) Draw images(cards) or reset the image in swing
So when you reset, basically you repeat the same process as above.
You can have something like this:
public static void startNewGame() //use this for reset
{
ArrayList<Card> deck = createNewDeck();
ShuffleCards(deck);
ResetImages(deck); //reset card images
ResetComponents(); //reset all buttons/display to initial state
}
Something like this:
board.this.setVisible(false);
board.this.dispose();
new Board();
You can assign board = new Board(); but you need to make it static in the main class.
The best way is to make it using
public class DeckTester {
.
.
private static Board board;
public static void newBoard(){
board = new Board();
}
Then, refresh what you need.
All you have to do to restart is redefine the attributes as you would at the beginning so if you populate a deck and shuffle it at startup, you should so the same at restart. Try using a function for both scenarios, I'll give you a generic example.
public void setup() {
populate() // populate deck
shuffle() // and shuffle it
// anything else like ...
score = 0;
}
The goal of the program is to find the prime-numbers below a certain maximum.
the cancelNonPrimes() method acts like it's working (in the step-by-step debugger) but just does not write the false-values to the list...
public class Era2
{
int m;
int i;
boolean[] list;
/**
* Constructor for objects of class Era2
*/
public Era2(int max) {
m = max;
list = new boolean[m];
initialize();
}
/**
* Constructor for objects of class Era2 with standard-maximum-value = 25
*/
public Era2() {
m = 25;
list = new boolean[m];
initialize();
}
/**
* Method for initializing an object: all values to true except 0 and 1
*/
void initialize() {
while (i < m) {
setList(i, true);
i = i + 1;
}
setList(0, false);
setList(1, false);
}
/**
* Method for setting a bool to a number on the list
*/
void setList(int p, boolean b) {
list[p] = b;
}
/**
* Method for reading the entire list, printed in terminal
*/
void getList() {
for (int p = 0; p < m; p++){
if (readList(p) == true){
System.out.println(p + "true");
}
else {
System.out.println(p + "false");
}
}
}
/**
* Method for reading a specific shizl on the list
*/
boolean readList(int p) {
return list[p];
}
/**
* Method for setting all non-primes to false
*/
void cancelNonPrimes() {
i = 2;
while (i < m) {
if (readList(i) == true) {
int c = i;
int n = 2;
while (c < m) {
c = (i * n);
setList(c, false);
n = n + 1;
}
}
i = i + 1;
}
}
}
I am working on a Java program called Namesurfer for a home assignment. The program consists of five classes: 'NameSurfer, NameSurferConstants, NameSurferDataBase, NameSurferEntry, and NameSurferGraph.
The code is (I thought) complete, but when I put the name on NameSurfer console and press enter, I get the following error. And when I click Graph, it doesn't do anything.
My suspicion is it has something to do with NameSurferEntry class, but I've been looking for hours without success. I'm really new at Java, and any help will be appreciated.
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at NameSurfer.actionPerformed(NameSurfer.java:58)
at javax.swing.JTextField.fireActionPerformed(JTextField.java:492)
at javax.swing.JTextField.postActionEvent(JTextField.java:705)
at javax.swing.JTextField$NotifyAction.actionPerformed(JTextField.java:820)
at javax.swing.SwingUtilities.notifyAction(SwingUtilities.java:1645)
at javax.swing.JComponent.processKeyBinding(JComponent.java:2859)
at javax.swing.JComponent.processKeyBindings(JComponent.java:2894)
at javax.swing.JComponent.processKeyEvent(JComponent.java:2822)
at java.awt.Component.processEvent(Component.java:6159)
at java.awt.Container.processEvent(Container.java:2083)
at java.awt.Component.dispatchEventImpl(Component.java:4744)
at java.awt.Container.dispatchEventImpl(Container.java:2141)
at java.awt.Component.dispatchEvent(Component.java:4572)
at java.awt.KeyboardFocusManager.redispatchEvent(KeyboardFocusManager.java:1856)
at java.awt.DefaultKeyboardFocusManager.dispatchKeyEvent(DefaultKeyboardFocusManager.java:722)
at java.awt.DefaultKeyboardFocusManager.preDispatchKeyEvent(DefaultKeyboardFocusManager.java:1000)
at java.awt.DefaultKeyboardFocusManager.typeAheadAssertions(DefaultKeyboardFocusManager.java:865)
at java.awt.DefaultKeyboardFocusManager.dispatchEvent(DefaultKeyboardFocusManager.java:686)
at java.awt.Component.dispatchEventImpl(Component.java:4616)
at java.awt.Container.dispatchEventImpl(Container.java:2141)
at java.awt.Window.dispatchEventImpl(Window.java:2489)
at java.awt.Component.dispatchEvent(Component.java:4572)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:710)
at java.awt.EventQueue.access$400(EventQueue.java:82)
at java.awt.EventQueue$2.run(EventQueue.java:669)
at java.awt.EventQueue$2.run(EventQueue.java:667)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87)
at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:98)
at java.awt.EventQueue$3.run(EventQueue.java:683)
at java.awt.EventQueue$3.run(EventQueue.java:681)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:680)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:296)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:211)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:196)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:188)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)
Here's the code for NameSurfer.
/*
* File: NameSurfer.java
* ---------------------
* When it is finished, this program will implements the viewer for
* the baby-name database described in the assignment handout.
*/
import acm.program.*;
import java.awt.event.*;
import javax.swing.*;
public class NameSurfer extends Program implements NameSurferConstants {
/* private instance variables*/
private JButton graphButton;
private JButton clearButton;
private JLabel nameLabel;
private JTextField name;
private NameSurferGraph graph;
private NameSurferDataBase dataBase;
/**
* This method has the responsibility for reading in the data base
* and initializing the interactors at the top of the window.
*/
public void init() {
addActionListeners();
graph = new NameSurferGraph();
add(graph);
/* adds the control bar*/
nameLabel = new JLabel ("Name");
add(nameLabel, NORTH);
name = new JTextField(MAX_FONT_NAME);
name.addActionListener(this);
add(name, NORTH);
graphButton = new JButton ("Graph");
add(graphButton, NORTH);
clearButton = new JButton ("Clear");
add(clearButton, NORTH);
}
/**
* This class is responsible for detecting when the buttons are
* clicked, so you will have to define a method to respond to
* button actions.
*/
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals ("Clear")) {
graph.clear();
graph.update();
} else {
String inputName = name.getText();
NameSurferEntry entry = dataBase.findEntry(inputName);
if (entry != null) {
graph.addEntry(entry);
graph.update();
}
}
}
}
And here's the code for NameSurferEntry.
/*
* File: NameSurferEntry.java
* --------------------------
* This class represents a single entry in the database. Each
* NameSurferEntry contains a name and a list giving the popularity
* of that name for each decade stretching back to 1900.
*/
import acm.util.*;
import java.util.*;
import java.util.StringTokenizer;
public class NameSurferEntry implements NameSurferConstants {
/* private instance variables*/
private String name;
private int[] ranks = new int [NDECADES];
/**
* Creates a new NameSurferEntry from a data line as it appears
* in the data file. Each line begins with the name, which is
* followed by integers giving the rank of that name for each
* decade.
*/
public NameSurferEntry(String line) {
//gets the name
int nameEnd = line.indexOf(" ");
name = line.substring(0, nameEnd);
//gets the ranking and forms it into an array using StringTokenizer class
String rankingStart = line.substring(nameEnd + 1);
StringTokenizer tokenizer = new StringTokenizer(rankingStart);
for (int i = 0; tokenizer.hasMoreTokens(); i++) {
int yearRank = Integer.parseInt(tokenizer.nextToken());
ranks[i] = yearRank;
}
}
/* Method: getName() */
/**
* Returns the name associated with this entry.
*/
public String getName() {
return name;
}
/* Method: getRank(decade) */
/**
* Returns the rank associated with an entry for a particular
* decade. The decade value is an integer indicating how many
* decades have passed since the first year in the database,
* which is given by the constant START_DECADE. If a name does
* not appear in a decade, the rank value is 0.
*/
public int getRank(int decade) {
if (decade <NDECADES) {
return ranks[decade];
}
return 0;
}
/* Method: toString() */
/**
* Returns a string that makes it easy to see the value of a
* NameSurferEntry.
*/
public String toString() {
String result = "";
for (int i = 0; i < ranks.length; i++) {
result += getRank(i);
}
return ("\"" + name + "[" + result + "]\"");
}
}
And here's the code for NameSurferGraph.
import acm.graphics.*;
import java.awt.event.*;
import java.util.*;
import java.awt.*;
public class NameSurferGraph extends GCanvas implements NameSurferConstants, ComponentListener {
/*Private instance variables*/
private ArrayList <NameSurferEntry> dataDisplay;
/**
* Creates a new NameSurferGraph object that displays the data.
*/
public NameSurferGraph() {
addComponentListener(this);
dataDisplay = new ArrayList<NameSurferEntry>();
}
/**
* Clears the list of name surfer entries stored inside this class.
*/
public void clear() {
dataDisplay.clear();
update();
}
/**
* Adds a new NameSurferEntry to the list of entries on the display.
* Note that this method does not actually draw the graph, but
* simply stores the entry; the graph is drawn by calling update.
*/
public void addEntry(NameSurferEntry entry) {
dataDisplay.add(entry);
}
/**
* Updates the display image by deleting all the graphical objects
* from the canvas and then reassembling the display according to
* the list of entries. Your application must call update after
* calling either clear or addEntry; update is also called whenever
* the size of the canvas changes.
*/
public void update() {
removeAll();
drawGraph();
if (dataDisplay.size() >= 0) {
for (int i = 0; i < dataDisplay.size(); i++) {
NameSurferEntry entry = dataDisplay.get(i);
drawRankingGraph (entry, i);
}
}
}
/*draws the background grids and displays the years*/
private void drawGraph() {
drawMargins();
drawVerticalLines();
displayYears();
}
/*Draws the horizontal lines at the top and the bottom of the window*/
private void drawMargins() {
double x1 = 0;
double x2 = getWidth();
double y1 = GRAPH_MARGIN_SIZE;
double y2 = getHeight() - GRAPH_MARGIN_SIZE;
GLine topLine = new GLine (x1, y1, x2, y1);
GLine bottomLine = new GLine (x1, y2, x2, y2);
add(topLine);
add(bottomLine);
}
/*Draws the vertical lines*/
private void drawVerticalLines() {
double x = 0;
for (int i = 0; i < NDECADES; i++) {
GLine verticalLine = new GLine (x, 0, x, getHeight());
x += getWidth() / NDECADES;
add(verticalLine);
}
}
/*Displays the years*/
private void displayYears() {
int decade = START_DECADE;
double x = 0;
for (int i = 0; i < NDECADES; i++) {
GLabel label = new GLabel ("" + decade);
add(label, x, getHeight() - GRAPH_MARGIN_SIZE/2 + (label.getAscent() / 2));
decade += NUMBER_OF_YEARS;
x += getWidth() / NDECADES;
}
}
/*Draws the ranking graph and the input name label*/
private void drawRankingGraph(NameSurferEntry entry, int n) {
int inputOrder = n;
for (int i = 0; i < NDECADES - 1; i++) {
int r1 = entry.getRank(i);
int r2 = entry.getRank(i + 1);
double x1 = i * (getWidth()/NDECADES);
double x2 = (i+1) * (getWidth()/NDECADES);
double y1 = 0;
double y2 = 0;
if (r1 == 0) {
y1 = getHeight() - GRAPH_MARGIN_SIZE;
} else {
y1 = GRAPH_MARGIN_SIZE + (getHeight() - GRAPH_MARGIN_SIZE*2) * r1 / MAX_RANK;
}
if (r2 == 0) {
y2 = getHeight() - GRAPH_MARGIN_SIZE;
} else {
y2 = GRAPH_MARGIN_SIZE + (getHeight() - GRAPH_MARGIN_SIZE*2) * r2 / MAX_RANK;
}
/*Sets the graph and the label on the window*/
GLine rankingGraph = new GLine (x1, y1, x2, y2);
GLabel inputName = new GLabel(entry.getName() + " " + (entry.getRank(i) == 0 ? "*" : entry.getRank(i)));
/*Sets the color*/
Color color = getColor(inputOrder%4);
rankingGraph.setColor(color);
inputName.setColor(color);
/*Displays the graph and the label*/
add(rankingGraph);
add(inputName, x1, y2);
}
}
/*Gets the color of the rankingGraph and the inputName label*/
private Color getColor(int i) {
switch (i) {
case 0: return Color.black;
case 1: return Color.red;
case 2: return Color.blue;
}
return Color.magenta;
}
/* Implementation of the ComponentListener interface */
public void componentHidden(ComponentEvent e) { }
public void componentMoved(ComponentEvent e) { }
public void componentResized(ComponentEvent e) { update(); }
public void componentShown(ComponentEvent e) { }
}
Your "database" seems to be null.
Note that you either provided incomplete NameSurfer source or you need to recompile your application - line numbers are off, line 58 only has a closing brace.
Check the usage of "actionPerformed" method. You're probably trying to use it on something which is not set and therefore "null".
You're calling a method on an object that's null at NameSurfer.java:58 . Find out what can be null on that line and figure out why it's null even though you expect it not to be.
Unrelated to that, read up on the Java Naming Conventions. Only your type names should start with an uppercase.