Setting instance Variable, before creating an object - java

So i got this program which sets subject, and grades it.
now i got this piece of code:
package ectsmonitor;
import java.util.Scanner;
import java.util.stream.IntStream;
/**
*
* #author JasperF
*/
public class ECTSMonitor {
private int aantalvakken;
private final double voldoende = 5.5;
private String[] vak = new String[aantalvakken];
private Scanner input = new Scanner(System.in);
private int[] ECTS = new int[aantalvakken];
private double[] Cijfer = new double[aantalvakken];
private int totaalECTS;
/**
* #param args the command line arguments
*/
/**
* Asks for amount of Subjects, and sets instance variable for size of
* Arrays
*/
public void setSubjects() {
//System.out.println("Hoeveel vakken heb je?");
//aantalvakken = input.nextInt();
System.out.println(vak.length);
for (int x = 0; x < getAantalvakken(); x++) {
System.out.println("Voer de naam in van je vak!");
vak[x] = input.next();
System.out.println("Voer het aantal punten in voor " + vak[x]);
ECTS[x] = input.nextInt();
System.out.println("Vak Toegevoegd!!");
}
}
public void setCijfer() {
for (int x = 0; x < vak.length; x++) {
System.out.println("Wat is je Cijfer voor " + vak[x] + "?");
Cijfer[x] = input.nextDouble();
System.out.println("Voor het vak " + vak[x] + "heb je als cijfer ingevuld " + Cijfer[x]);
}
}
public void Checkscore() {
for (int x = 0; x < vak.length; x++) {
if (Cijfer[x] >= voldoende) {
System.out.println("vak:" + vak[x] + "\t\t\t\t Cijfer: " + Cijfer[x] + "ECTS behaald: " + ECTS[x]);
} else {
System.out.println("vak:" + vak[x] + "\t\t\t\t Cijfer: " + Cijfer[x] + "ECTS behaald: 0");
}
}
}
public void BAS() {
totaalECTS = IntStream.of(ECTS).sum();
if (totaalECTS < (totaalECTS * (5 / 6))) {
System.out.println("PAS OP!!: Je ligt op schema voor een BAS!");
} else {
System.out.println("Gefeliciteerd!!: Je bent op weg naar je Propodeuse!!");
}
}
/**
* #return the aantalvakken
*/
public int getAantalvakken() {
return aantalvakken;
}
/**
* #param aantalvakken the aantalvakken to set
*/
public void setAantalvakken(int aantalvakken) {
this.aantalvakken = aantalvakken;
}
}
and i got this piece of code to run it:
public class Run {
/**
*
* #author JasperF
* #param args
*/
public static void main(String[] args) {
ECTSMonitor mon = new ECTSMonitor();
mon.setSubjects();
mon.setCijfer();
mon.Checkscore();
mon.BAS();
}
}
now in the first code, the lenght of the arrays is set by the variable 'aantalvakken',
but when i run my program, and print the lenght of te array it says 0.
how can i set the variable aantalvakken to set the array length

Pass aantalvakken value to constructor. And create ArrayList's depends on aantalvakken at constructor.
public class ECSTMonitor {
private int aantalvakken;
private final double voldoende = 5.5;
private String[] vak;
private Scanner input = new Scanner(System.in);
private int[] ECTS;
private double[] Cijfer;
private int totaalECTS;
public ECSTMonitor(int aantalvakken) {
this.aantalvakken = aantalvakken;
vak = new String[aantalvakken];
ECTS = new int[aantalvakken];
Cijfer = new double[aantalvakken];
}

private int aantalvakken;
is not initialized and therefore 0 by default.

try using static variables like below, initialize the variable(aantalvakken) how much array length you want.
public static final int aantalvakken;
or
public static final int aantalvakken=10;

Related

How to call upon a variable from another object of the same class

import java.util.Random;
public class Character
{
// instance variables - vervang deze door jouw variabelen
private String _name;
private double _level;
private double _strenght;
private double _speed;
private double _defense;
private double _currenthp;
private double _maxhp;
/**
* Voorbeeld van een method - schrijf hier jouw comment
*
* #param y deze method krijgt deze parameter mee in de aanroep
* #return deze method geeft de som van x en y terug
*/
public Character()
{
}
public Character(String name,double level)
{
// schrijf hier jouw code
_name = name;
_level = level;
Random rand = new Random();
//level voor het berekenen van skills
int lvl = (int)level;
//stenght en speed parameter voor random
int stsplvl = 12*lvl - 8*lvl;
//defense parameter voor random
int deflvl = 6*lvl - 4*lvl;
//hp parameter voor random
int hplvl = 30*lvl - 20*lvl;
//Strenght berekenen
double st = (double)rand.nextInt(stsplvl);
st = st + 8*lvl;
_strenght = st;
//Speed berekenen
double sp = (double)rand.nextInt(stsplvl);
sp = sp + 8*lvl;
_speed = sp;
//Defense berekenen
double def = (double)rand.nextInt(deflvl);
def = def + 4*lvl;
_defense = def;
//Hp berekenen
double hp = (double)rand.nextInt(hplvl);
hp = hp + 20*lvl;
_currenthp = hp;
_maxhp = hp;
}
public void Character(String name,double level)
{
_name = name;
_level = level;
}
public void ploth()
{
System.out.println(_name + ": " + _currenthp + " / " + _maxhp + " HP");
}
public int attack(Character _other)
{
int defe = super (double._other _defense);
Random rando = new Random();
//_strenght is een double
int damcalc = (int)(1.2 * _strenght - 0.8 * _strenght);
int netdam = rando.nextInt(damcalc);
int totdam = (int)(netdam + 0.8*_strenght);
int enddam = totdam - defe;
}
}
So in the last return statement I am trying to get the defense variable of the other object (character that is being attacked). I am trying to take a random number based on the strength stat of this character and then to create a damage stat. After that I'd do damage - defense (from the other character). Does anyone know what code I use for this? PS:Please don't cringe this is the stuff we learn at school these days.
From your description you want your method attack return enddam like below:
public int attack(Character _other)
{
int defe = (int)_other._defense;
Random rando = new Random();
//_strenght is een double
int damcalc = (int)(1.2 * _strenght - 0.8 * _strenght);
int netdam = rando.nextInt(damcalc);
int totdam = (int)(netdam + 0.8*_strenght);
int enddam = totdam - defe;
return enddam;
}
Delete the void method Character, if it is a constructor you already have one with the same signature.

Not sure why i'm getting an java.util.NoSuchElementException error

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

Solving The Sagrada Familia Magic Square using Depth First Search in Java

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

Objects are being overwritten when adding a new Object to an array

I am working on an assignment for school and cannot figure why my items are being overwritten in my shopping cart class. If it were up to me id be using an arraylist but the assignment calls for an array of Items.
package jjobrien_assignement_4;
import java.util.Arrays;
import java.util.Scanner;
public class ShoppingCart extends Shopper{
private static final int DEFAULT_SIZE = 10;
String userName;
Item[] cart;
int itemCount = 0;
/**
* ShoppingCart default constructor
*/
public ShoppingCart(){
userName = "";
cart = new Item[DEFAULT_SIZE];
}
/**
* Shopping cart overloaded constructor
* #param aUserName
*/
public ShoppingCart(String aUserName){
userName = aUserName;
cart = new Item[DEFAULT_SIZE];
}
/**
* Adds a single item to the array cart[]
* #param cart
* #return
*/
public void addItem(Item theItem){
for(int i = 0; i < DEFAULT_SIZE; i++){
if(cart[i] == null){
System.out.print(i);
cart[i]= theItem;
itemCount += 1;
System.out.print(cart[i]);
break;
} //System.out.print(cart[i]);
}
}
public String removeItem(){
return "";
}
/**
*
* #param cleared
* #return cleared
* Will clear every object inside of the array cart[]
* by setting all valuse in the cart[] to null.
*/
public boolean clear(boolean cleared){
for(int i = 0; i < cart.length; i++){
cart[i] = null;
}
cleared = true;
itemCount = 0;
return cleared;
}
public String indexOf(){
return "";
}
/**
* Grabs single item from array to return to shopper
* #return
*/
public String getItem(){
String theItem = "";
for(int i = 0; i < itemCount; i++){
theItem = cart[i].getProductName();
}
return theItem;
}
public String showAll(String all){
for(int i = 0; i < itemCount; i++){
all += cart[i].getProductName() + " $"
+ cart[i].getPrice() + "\n";
}
return all;
}
/**
*
* #return
* Adds total cost and divides by item count to get avgCost
*/
public double showAverageCost(){
double avgCost = 0;
double totalCartCost = 0;
double singleItemCost = 0;
for(int i = 0; i < itemCount; i++){
singleItemCost = cart[i].getPrice();
totalCartCost = totalCartCost + singleItemCost;
}
avgCost = totalCartCost/itemCount;
return avgCost;
}
/**
*
* #param totalCartCost
* #return
* Calculates total cost by getting each price
* of all existing items in the array cart[].
*/
public double totalCost(double totalCartCost){
double singleItemCost = 0;
for(int i = 0; i < itemCount; i++){
singleItemCost = cart[i].getPrice();
totalCartCost = totalCartCost + singleItemCost;
}
return totalCartCost;
}
/**
* #return itemCount
* Counts how many items are in the shoppers cart
*/
public int countItems(){
int numOfItems = 0;
for(int i = 0; i < itemCount; i++){
numOfItems = numOfItems + 1;
}
return numOfItems;
}
}
}
{package jjobrien_assignement_4;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class Shopper {
public final static String MENU = "\nSelect an option: \nType \"add\" to add an Item to the cart\n" +
"Type \"count\" to determine the total number of Items in the" +
"cart\n" +
"Type \"total cost\" to determine the total cost of Items in" +
"the cart\n" +
"Type \"show all\" to display the contents of the cart\n" +
"Type \"show average cost\" to display the average price of" +
"the contents of the cart\n" +
"Type \"cheapest\" to display the Item with the lowest price" +
"in the cart\n" +
"Type \"highest\" to display the Item with the highest price" +
"in the cart\n" +
"Type \"remove\" to remove a specific Item from the cart\n" +
"Type \"clear\" to remove all Items from the cart\n" +
"Type \"quit\" to exit the program: ";
public static void main (String [] args){
Scanner keyboard = new Scanner(System.in);
/*
cart[0] = new Item("Milk", 3.00);
cart[1] = new Item("Eggs", 4.25);
cart[2] = new Item("Bread", 2.50);
*/
boolean cleared = false;
boolean done = false;
double totalCartCost = 0.0;
String userName = "";
String userOption = "No option yet";
JOptionPane.showMessageDialog(null, "Welcome to the shopping cart!");
userName = JOptionPane.showInputDialog(null, "Please enter your name: ");
ShoppingCart newCart = new ShoppingCart(userName);
//While to display menu to customer and call methods based on user input
while(!done){
userOption = JOptionPane.showInputDialog(null, MENU);
if(userOption.equals("quit")){
if(quit(done) == true){
JOptionPane.showMessageDialog(null, "Thank you for using the Shopping Cart program!\n");
done = true;
}else if(quit(done) == false){
done = false;
}
}else if(userOption.equals("add")){
addItem(keyboard, newCart);
}else if(userOption.equals("count")){
}else if(userOption.equals("total cost")){
findTotalCost(newCart);
}else if(userOption.equals("show all")){
showAllItems(newCart);
}else if(userOption.equals("show average cost")){
showAverage(newCart);
}else if(userOption.equals("cheapest")){
//getCheapest();
}else if(userOption.equals("highest")){
//getHighest();
}else if(userOption.equals("remove")){
//remove();
}else if(userOption.equals("clear")){
clear(cleared, newCart);
}
}
}
/**
* Exits the program
*/
public static boolean quit(boolean isDone){
isDone = true;
return isDone;
}
/**
* Calls shopping cart class to add a single item to the array
* #param keyboard
* #param theCart
*/
public static void addItem(Scanner keyboard, ShoppingCart theCart){
String theItem = "";
String tempPrice = "";
Double thePrice = 0.0;
Item temp = null;
theItem = JOptionPane.showInputDialog(null, "Enter product name: ");
tempPrice = JOptionPane.showInputDialog(null, "Enter the price of " + theItem + ": ");
thePrice = Double.parseDouble(tempPrice);
temp = new Item(theItem, thePrice);
if(temp != null){
theCart.addItem(temp);
}
}
/**
* Will call ShoppingCart Clear Method
* #param cleared
* #param theCart
* #return
*/
public static boolean clear(boolean cleared, ShoppingCart theCart){
theCart.clear(cleared);
JOptionPane.showMessageDialog(null, "Your cart was cleared");
return cleared;
}
/**
* will call totalCost method from shopping cart class
* to add the total cost of all items stored in cart[]
* #param theCart
*/
public static void findTotalCost( ShoppingCart theCart){
double totalCost = 0;
JOptionPane.showMessageDialog(null, "Total cost: "
+ theCart.totalCost(totalCost));
}
/**
* Will print every item with their corresponding price
* in the cart[] array
*/
public static void showAllItems(ShoppingCart theCart){
String all = "";
JOptionPane.showMessageDialog(null, theCart.showAll(all));
}
/**
* calls shopping cart class to get average cost or all items
* in the current cart
*/
public static void showAverage(ShoppingCart theCart){
JOptionPane.showMessageDialog(null, theCart.showAverageCost());
}
}
}
{package jjobrien_assignement_4;
public class Item {
private static String productName;
private static double price;
public Item(){
productName = "No Name yet";
price = 0;
}
public Item(String aProductName, double aPrice){
setProductName(aProductName);
setPrice(aPrice);
}
public double getPrice(){
return price;
}
public String getProductName(){
return productName;
}
public double setPrice(double aPrice){
price = aPrice;
return aPrice;
}
public String setProductName(String aProductName){
productName = aProductName;
return aProductName;
}
public java.lang.String toString(){
String text = "";
text += productName.toString();
return text;
}
}
}
Your Item class uses static variables to store its values.
A static variable is class-level - there is only one instance of that variable which is shared by every instance of your class.
When you change the values of your Item (such as when creating a new Item), you are in fact changing the static variables - effectively setting your new values for all Item objects.
Replacing your static variables with standard member variables should resolve your issues:
private String productName;
private double price;
Note that Eclipse will automatically generate constructors and setters using the syntax:
public void setSomething(String something) {
this.something = something;
}
and Eclipse should also give you a warning if you attempt to assign to a static variable in this way (because you are using a static variable in a non-static context.)
I'm not sure about other IDEs - but they should do something similar.

No main class found,

This is a beginners question, why do I get a message about I don't have any main class. I am a total beginner and i have tried to read all the other answers regarding this problem. Im working in netbeans.
/**
* #author Anders
*/
public class Main {
public enum Valuta { // here i assign the values i allow from the argument
EUR,
USD,
RUB;
// here i assign the conversionrates
static final float C_EUR_TO_DKK_RATE = (float) 7.44;
static final float C_USD_TO_DKK_RATE = (float) 5.11;
static final float C_RUB_TO_DKK_RATE = (float) 0.156;
static float result = 0;
static int value = 0;
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
if (args.length == 2) {
value = Integer.parseInt(args[0]);
String valutaIn = args[1]; //equalsIgnoreCase(null) boolean expression. How does this works??
Valuta enumConvert = Valuta.valueOf(valutaIn);
switch (enumConvert) {
case EUR:
result = value * C_EUR_TO_DKK_RATE;
break;
case USD:
result = value * C_USD_TO_DKK_RATE;
break;
case RUB:
result = value * C_RUB_TO_DKK_RATE;
break;
}
System.out.println((float) value + "" + enumConvert + " converts to " + (result * 100.) / 100.0 + "Dk");
}
else {
System.exit(1);
}
}
}
}
The method main is not in the Class Main, it is inside the enum Valuta. You probably intended the following (note the closing curly bracket after the enum):
/**
* #author Anders
*/
public class Main {
public enum Valuta { // here i assign the values i allow from the argument
EUR,
USD,
RUB;
}
// here i assign the conversionrates
static final float C_EUR_TO_DKK_RATE = (float) 7.44;
static final float C_USD_TO_DKK_RATE = (float) 5.11;
static final float C_RUB_TO_DKK_RATE = (float) 0.156;
static float result = 0;
static int value = 0;
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
if (args.length == 2) {
value = Integer.parseInt(args[0]);
String valutaIn = args[1]; //equalsIgnoreCase(null) boolean expression. How does this works??
Valuta enumConvert = Valuta.valueOf(valutaIn);
switch (enumConvert) {
case EUR:
result = value * C_EUR_TO_DKK_RATE;
break;
case USD:
result = value * C_USD_TO_DKK_RATE;
break;
case RUB:
result = value * C_RUB_TO_DKK_RATE;
break;
}
System.out.println((float) value + "" + enumConvert + " converts to " + (result * 100.) / 100.0 + "Dk");
}
else {
System.exit(1);
}
}
}

Categories