I need some help with this one. I have trying to get this array to work properly but do not know what I am doing wrong. I am a noob to java and really need some help
private static int respondentID;
private static int count;
static void enterQuestions() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
private String surveyName;
private boolean surveyStart = true;
private boolean surveyStop = true;
private String question [] = new String[10];
private int responses[][]= new int[10][10];
Scanner input = new Scanner(System.in);
// first overloaded constructor
public Phase2() {
this( "Customer Survey" );
respondentID = 0;
count = 0;
} // end
// second overloaded constructor
public Phase2( String title ) {
surveyName = title;
respondentID = 0;
count = 0;
} // end constructor Survey
// method to be called when a user starts filling out a survey ( surveyStart will have been set to "true" )
public int startSurveyCount( int ct ) { // parameter for testing only
if( surveyStart ) {
if( respondentID > 0 ) {
if( count >= respondentID ) {
count++;
} else {
setCount( getRespondentID() );
}
} else {
//test
setCount( ct );
count = getCount();
count++;
setCount( count - 1 );
}
}
return count;
} // end method
// method to be called when a survey is successfully
public int generateRespondentID() {
if( surveyStop ) {
//
count = getCount();
setRespondentID( count );
} else {
if( count < 2 ) {
count = 0;
respondentID = 0;
} else {
count--;
setCount( count );
}
}
return respondentID;
} // end method generateRespondentID
public void setRespondentID( int count ) {
// count is the number of completed surveys.
respondentID = count;
respondentID++; // and then incremented by 1.
} //end method
public int getRespondentID() {
return respondentID;
} // end method
public void setSurveyTitle( String title ) {
surveyName = title;
} // end method
public String getSurveyTitle() {
return surveyName;
} // end method
public void setCount( int ct ) {
count = ct;
} // end method
public int getCount() {
return count;
} // end method
public void setSurveyStart( boolean surveySt ) {
surveyStart = surveySt;
} // end method
public boolean getSurveyStart() {
return surveyStart;
} // end method
public void setSurveySubmit( boolean surveySub ) {
surveyStop = surveySub;
} // end method
public boolean getSurveySubmit() {
return surveyStop;
} // end method
public void logResponse(int respondentID, int questionNumber, int responseEntered)
{
responses[respondentID] [questionNumber-1] = responseEntered;
}
public void displaySurveyResults (int no)
{
for (int j=0; j<10; j++)
System.out.print("Question"+(no)+" : " + question[no-1]+"Reply");
if (responses[respondentID][no] == 0)
{
System.out.print("NO");
}
else
{
System.out.print("Yes");
}
}
public void enterQuestion()
{
for (int i=0; i<10; i++)
{
System.out.println("Enter Question "+(i+1)+" : ");
question[i] = input.nextLine();
}
}
public void displayQuestionStats(int no)
{
int answer;
System.out.print("Question"+(no)+" : "+question[no-1]+" (0-No/1-Yes) : ");
answer = input.nextInt();
logResponse(respondentID, no, answer);
}
}
This is my tester
public static void main(String[] args) {
Scanner input = new Scanner( System.in );
System.out.println( "Below are the results of running the no–argument");
// demonstrates the no–arg constructor
Phase2 noArgSurvey = new Phase2();
System.out.printf( "The no–argument survey values are:\ntitle: %s\n"
+ "initial value of respondentID: %d\ncount: %d\n",
noArgSurvey.getSurveyTitle(), noArgSurvey.getRespondentID(),
noArgSurvey.getCount() );
// demonstrates the constructor with a title argument ( for user input of survey title )
System.out.println( "\nPlease enter a name for the survey" );
String inputTitle = input.nextLine();
System.out.println(); // inserts a blank line
Phase2 titleArgConst = new Phase2( inputTitle );
System.out.printf( "Survey Name is: %s\n"
+ "initial values of:\nrespondentID: %d\ncount: %d\n\n",
titleArgConst.getSurveyTitle(), titleArgConst.getRespondentID(),
titleArgConst.getCount() );
//respondent id test
System.out.println( "This will test the generateRespondentID method.\n\n"
+ "Enter the number of surveys that have been taken");
int testInt = input.nextInt();
// values for respondentID and count after 1 survey has been successfully submitted
System.out.println( "\nAssuming " + testInt + " surveys submitted");
Phase2 oneDone = new Phase2();
oneDone.startSurveyCount( testInt );
oneDone.generateRespondentID();
System.out.printf( "The Respondent ID is: %d\ncount: %d\n\n",
oneDone.getRespondentID(), oneDone.getCount() );
noArgSurvey.enterQuestion();
for(int i = 1; i <= 10; i++)
{
noArgSurvey.displayQuestionStats(i);
}
//Display The Inputs Entered by User
System.out.println("Result for Survey with Title \""+titleArgConst.getSurveyTitle()+"\" :");
for(int i=1; i<11; i++)
{
noArgSurvey.displaySurveyResults(i);
}
} // end main method
} // end class SurveyTest
Change loop condition to
for(int i = 1; i < 10; i++)
Java follows Zero indexing. So in your case question and responses array is of size 10 which means it will iterate from 0 to 9 use for(int i = 1; i < 10; i++) instead for iterating. or use arrayName.length length is a variable provided by JVM which gives you the size of array at runtime.
AS Vishrant mentioned *Java follows Zero indexing. So in your case question and responses array is of size 10 which means it will iterate from 0 to 9 *
in your tester class, you are trying to access 10th index in loop in 2 places
for(int i = 1; i <= 10; i++) (1)
{
noArgSurvey.displayQuestionStats(i);
}
for(int i=1; i<11; i++) (2)
{
noArgSurvey.displaySurveyResults(i);
}
You should to write
for(int i = 0; i < 10; i++) (1)
{
noArgSurvey.displayQuestionStats(i);
}
for(int i=0; i<10; i++) (2)
{
noArgSurvey.displaySurveyResults(i);
}
EDIT Addition
public void displaySurveyResults (int no)
{
for (int j=0; j<10; j++)
System.out.print("Question"+(no)+" : " + question[no]+"Reply"); <<<--------- change [no-1] to [no]
if (responses[respondentID][no] == 0)
{
System.out.print("NO");
}
Related
so i have two classes
It's supossed to be like a digital movie shop, so it should return the user names, the movie names and the rating of the movies
This is the interface one:
import modelo.Matriz;
public class MenuConsola {
private Matriz userItem;
public MenuConsola(){
String[] peliculas = { "Toy story2", "Jumanji", "Amelie", "Wolverine", "Spider Man", "Yes Men", "Sabrina",
"Tom and Huck", "Sudden Death", "GoldenEye" };
String[] usuarios = { "Jhon", "Michael", "Jimmy", "Janis", "Carla", "Angie" };
userItem = new Matriz(peliculas, usuarios);
cargarMatriz();
mostrarBanner();
mostrarUsuarios();
System.out.println("\n");
mostrarPeliculas();
//System.out.println(mostrarMatriz());
}
public void cargarMatriz(){
userItem.cargarCalificaciones();
}
public String mostrarMatriz(){
return userItem.mostrarMatriz();
}
static void appendChars(StringBuilder sb, char c, int count) {
for (int i = 0; i < count; i++) {
sb.append(c);
}
}
public void mostrarUsuarios(){
System.out.println("Usuarios:");
String[] usuarios = userItem.obtenerUsuarios();
int c = 1;
for(String us : usuarios){
System.out.println(c + ". " + us + "\t");
c++;
}
}
public void mostrarPeliculas(){
System.out.println("Peliculas:");
String[] pelis = userItem.obtenerPeliculas();
int c = 1;
for(String pel : pelis){
System.out.println(c + ". " + pel + "\t");
c++;
}
}
**public void mostrarMayor(){
System.out.println(userItem.darPeliculaMayorPromedio());
}
public void mostrarMenor(){
System.out.println(userItem.darPeliculaMenorPromedio());
}**
public static void main(String[] args) {
MenuConsola menu = new MenuConsola();
}
}
And this is the matrix one:
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class Matriz {
private String[] peliculas;
private String[] usuarios;
private int[][] calificaciones;
public Matriz(String[] pelis, String[] users) {
this.peliculas = pelis;
this.usuarios = users;
calificaciones = new int[users.length][pelis.length];
}
public void cargarCalificaciones() {
BufferedReader br;
try {
br = new BufferedReader(new FileReader("data/userItem.txt"));
String linea = "";
int fila = 0;
while ((linea = br.readLine()) != null) {
String[] data = linea.split("\t");
int col = 0;
for (String strRatig : data) {
calificaciones[fila][col] = Integer.parseInt(strRatig);
col++;
}
fila++;
}
br.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
}
}
public String mostrarMatriz(){
String mensaje = "";
for(int i = 0; i<calificaciones.length; i++){
for(int j = 0; j < calificaciones[0].length; j++){
mensaje += " " + calificaciones[i][j];
}
mensaje += "\n";
}
return (mensaje);
}
public String[] obtenerPeliculas() {
return peliculas;
}
*/
public String[] obtenerUsuarios() {
return usuarios;
}
**public String darPeliculaMayorPromedio**(){
int mayor = calificaciones[0][0];
String peliMayor = "";
for ( int i = 0 ; i < calificaciones.length ; i++ )
{
for ( int j = 0 ; j < calificaciones[i].length ; j++ )
{
if ( calificaciones[i][j] > mayor )
{
mayor = calificaciones[i][j];
peliMayor = peliculas[j];
}
}
}
return peliMayor;
}
**public String darPeliculaMenorPromedio(){**
int menor = calificaciones[0][0];
String peliMenor = "";
for ( int i = 0 ; i < calificaciones.length ; i++ )
{
for ( int j = 0 ; j < calificaciones[i].length ; j++ )
{
if ( calificaciones[i][j] < menor )
{
menor = calificaciones[i][j];
peliMenor = peliculas[j];
}
}
}
return peliMenor;
}
}
Ok this is all the code, i don't know why isn't it printing something? isn't the array or matrix initializated? I doesn't give me any error when i compile and it executes normally until the last two methods
I would think its maybe because you haven't initilised your array that your looking through so it would return nothing. Try initialising the array full of values and then you may find you'll get some result
there doesnt seem to be enough code to accurately answer this question.
Stepping through with a debugger is the best bet, but here are some potential failures I can brainstorm
userItem is not static. Since you call userItem.darPeliculaMenorPromedio() in an encapsulated method, you need to either have an instantiated object (which I can see you don't) or the class needs to be static (which I assume it isn't since the methods are not static either) - this should throw an error though, so I assume its not executing.
you never execute the functions mostrarMayor and mostrarMenor. I can;t see your main class, and what calls are in it, but you would need to call and execute the two functions in your main.
I have used an existing genetic algorithm from
here
and reworked it I but don't know what I'm doing wrong
This is the error that I get
Exception in thread "main" java.lang.NullPointerException at
simpleGa.Algorithm.crossover(Algorithm.java:69) at
simpleGa.Algorithm.evolvePopulation(Algorithm.java:34) at
simpleGa.GAprisonerdilemma.main(GAprisonerdilemma.java:41)
I can't figure out exactly where the mistake is. Read a lot about NullPointerException but couldn't figure it out
package simpleGa;
public class Population {
public static Individual[] individuals;
/*
* Constructors
*/
// Create a population
public Population(int populationSize, boolean initialise) {
individuals = new Individual[populationSize];
// Initialise population
if (initialise) {
// Loop and create individuals
for (int i = 0; i < size(); i++) {
Individual newIndividual = new Individual();
newIndividual.generateIndividual();
saveIndividual(i, newIndividual);
}
for(int i=0;i<size();i++)
{
if(i%2==1){Individual individual1=individuals[i-1];
Individual individual2=individuals[i];
if(individuals[i-1].getGene(i-1)==0 && individuals[i].getGene(i)==0){
individuals[i-1].fitness=individual1.fitness+1;
individuals[i].fitness=individual2.fitness+1;
}
if(individuals[i-1].getGene(i-1)==1 && individuals[i].getGene(i)==1){
individuals[i-1].fitness=individual1.fitness+2;
individuals[i].fitness=individual2.fitness+2;
}
if(individuals[i-1].getGene(i-1)==0 && individuals[i].getGene(i)==1){
individuals[i-1].fitness=individual1.fitness+3;
individuals[i].fitness=individual2.fitness+0;
}
if(individuals[i-1].getGene(i-1)==1 && individuals[i].getGene(i)==0){
individuals[i-1].fitness=individual1.fitness+0;
individuals[i].fitness=individual2.fitness+3;
}
}}}
}
/* Getters */
public Individual getIndividual(int index) {
return individuals[index];
}
public Individual getFittest() {
Individual fittest = individuals[0];
// Loop through individuals to find fittest
for (int i = 1; i < size(); i++) {
if (fittest.getFitness() <= getIndividual(i).getFitness()) {
fittest = getIndividual(i);
}
}
return fittest;
}
/* Public methods */
// Get population size
public int size() {
return individuals.length;
}
// Save individual
public void saveIndividual(int index, Individual indiv) {
individuals[index] = indiv;
}
}
package simpleGa;
public class Individual {
static int defaultGeneLength = 1000;
private long[] genes =new long [defaultGeneLength];
// Cache
public static int fitness = 0;
// Create a random individual
public void generateIndividual() {
for (int i = 0; i < size(); i++) {
long gene = Math.round(Math.random());
genes[i] = gene;
}
}
/* Getters and setters */
// Use this if you want to create individuals with different gene lengths
public static void setDefaultGeneLength(int length) {
defaultGeneLength = length;
}
public long getGene(int i) {
return genes[i];
}
public void setGene(int index, long value) {
genes[index] = value;
fitness = 0;
}
/* Public methods */
public int size() {
return genes.length;
}
public static int getFitness() {
return fitness;
}
public void setFitness(int i) {
fitness=i;
}
#Override
public String toString() {
String geneString = "";
for (int i = 0; i < size(); i++) {
geneString += getGene(i);
}
return geneString;
}
}
package simpleGa;
public class Algorithm {
/* GA parameters */
private static final double uniformRate = 0.5;
private static final double mutationRate = 0.015;
private static final int tournamentSize = 5;
private static final boolean elitism = true;
/* Public methods */
// Evolve a population
public static Population evolvePopulation(Population pop) {
Population newPopulation = new Population(pop.size(), false);
// Keep our best individual
if (elitism) {
newPopulation.saveIndividual(0, pop.getFittest());
}
// Crossover population
int elitismOffset;
if (elitism) {
elitismOffset = 1;
} else {
elitismOffset = 0;
}
// Loop over the population size and create new individuals with
// crossover
for (int i = elitismOffset; i < pop.size(); i++) {
Individual indiv1 = tournamentSelection(pop);
Individual indiv2 = tournamentSelection(pop);
Individual newIndiv = crossover(indiv1, indiv2);
newPopulation.saveIndividual(i, newIndiv);
}
// Mutate population
for (int i = elitismOffset; i < newPopulation.size(); i++) {
mutate(newPopulation.getIndividual(i));
}
for(int i=0;i<pop.size();i++)
{for(int j=0;j<pop.getIndividual(i).size();j++)
{if(i%2==1){Individual individual1=Population.individuals[i-1];
Individual individual2=Population.individuals[i];
if(Population.individuals[i-1].getGene(i-1)==0 && Population.individuals[i].getGene(i)==0){
Population.individuals[i-1].fitness=individual1.fitness+1;
Population.individuals[i].fitness=individual2.fitness+1;
}
if(Population.individuals[i-1].getGene(i-1)==1 && Population.individuals[i].getGene(i)==1){
Population.individuals[i-1].fitness=individual1.fitness+2;
Population.individuals[i].fitness=individual2.fitness+2;
}
if(Population.individuals[i-1].getGene(i-1)==0 && Population.individuals[i].getGene(i)==1){
Population.individuals[i-1].fitness=individual1.fitness+3;
Population.individuals[i].fitness=individual2.fitness+0;
}
if(Population.individuals[i-1].getGene(i-1)==1 && Population.individuals[i].getGene(i)==0){
Population.individuals[i-1].fitness=individual1.fitness+0;
Population.individuals[i].fitness=individual2.fitness+3;
} }}}``
return newPopulation;
}
// Crossover individuals
private static Individual crossover(Individual indiv1, Individual indiv2) {
Individual newSol = new Individual();
// Loop through genes
for (int i = 0; i < indiv1.size(); i++) {
// Crossover
if (Math.random() <= uniformRate) {
newSol.setGene(i, indiv1.getGene(i));
} else {
newSol.setGene(i, indiv2.getGene(i));
}
}
return newSol;
}
// Mutate an individual
private static void mutate(Individual indiv) {
// Loop through genes
for (int i = 0; i < indiv.size(); i++) {
if (Math.random() <= mutationRate) {
// Create random gene
long gene = Math.round(Math.random());
indiv.setGene(i, gene);
}
}
}
// Select individuals for crossover
private static Individual tournamentSelection(Population pop) {
// Create a tournament population
Population tournament = new Population(tournamentSize, false);
// For each place in the tournament get a random individual
for (int i = 0; i < tournamentSize; i++) {
int randomId = (int) (Math.random() * pop.size());
tournament.saveIndividual(i, pop.getIndividual(randomId));
}
// Get the fittest
Individual fittest = tournament.getFittest();
return fittest;
}
package simpleGa;
public class FitnessCalc {
/* Public methods */
// Set a candidate solution as a byte array
// To make it easier we can use this method to set our candidate solution
// with string of 0s and 1s
// Calculate inidividuals fittness by comparing it to our candidate solution
static int getFitness(Individual individual) {
int fitness = 0;
// Loop through our individuals genes and compare them to our cadidates
fitness=Individual.fitness;
return fitness;
}
}
// Get optimum fitness
}
package simpleGa;
import java.util.Scanner;
public class GAprisonerdilemma {
public static void main(String[] args) {
// Set a candidate solution
Scanner keyboard = new Scanner(System.in);
System.out.println("Input number of games!");
int k = keyboard.nextInt();
Individual.setDefaultGeneLength(k);
// Create an initial population
System.out.println("Input number of individuals in the population!");
int p = keyboard.nextInt();
Population myPop = new Population(p, true);
System.out.println("Input acceptable number of generations!");
int l = keyboard.nextInt();
// Evolve our population until we reach an optimum solution
int generationCount = 0;
int j=l+1;
System.out.println("Input requiered fitness value !");
int f = keyboard.nextInt();
int h=0;
// Evolve our population until we reach an optimum solution
for(int i=0;i<j;i++)
{
if(i==0){}
else{
if(myPop.getFittest().getFitness()>=f){if(h==0){h++;}
else{ System.out.println("Solution found!");
System.out.println("Generation: " + generationCount);
System.out.println( "Fitness(Points): " + myPop.getFittest().getFitness());
break;}
}else {myPop = Algorithm.evolvePopulation(myPop);
generationCount++;
System.out.println("Generation: " + generationCount + " Fittest: " + myPop.getFittest().getFitness());
}
if(i==j-1){ if(myPop.getFittest().getFitness()>=f)System.out.println("Solution found !");
else System.out.println("Solution not found closest solution is!");
System.out.println("Generation: " + generationCount);
System.out.println( " Fitness(Points): " + myPop.getFittest().getFitness());}
}
}
System.out.println("0 for betrays in that turn 1 for cooperates!");
System.out.println("Turns:");
System.out.println(myPop.getFittest());
}
}
I am new to Java programming. I developed a Pizza class that takes for parameters and outputs the description and cost. I developed a PizzaOrderArray class that stores the pizza orders in an array. I have a class containing the main method also.
When I tried to print the values of the orders, nothing prints yet debugging shows that the proper methods and loops were entered.
What am I doing incorrect? I have invested many hours and am still very confused. Any suggestions, please? Thank you! I appreciate it.
Pizza.java
import java.text.NumberFormat;
import java.util.Locale;
public class Pizza {
public Pizza(String size, int numCheeseTop, int numPepTop, int numHamTop) {
if (!setPizzaSize(size)) {
System.out.println(size + " is invalid size." + "Use small, medium or large.");
}
setNumCheese(numCheeseTop);
setNumPep(numPepTop);
setNumHam(numHamTop);
}
public Pizza(String size, int numPepTop, int numHamTop) {
if (!setPizzaSize(size)) {
System.out.println(size + " is invalid size." + "Use small, medium or large.");
}
pizza_cheese = 0;
setNumPep(numPepTop);
setNumHam(numHamTop);
}
public Pizza(String size, int numHamTop) {
if (!setPizzaSize(size)) {
System.out.println(size + " is invalid size." + "Use small, medium or large.");
}
pizza_pep = 0;
setNumHam(numHamTop);
pizza_cheese = 0;
}
public Pizza(String size) {
if (!setPizzaSize(size)) {
System.out.println(size + " is invalid size." + "Use small, medium or large.");
}
pizza_cheese = 0;
pizza_pep = 0;
pizza_ham = 0;
}
public Pizza() {
pizza_size = "small";
pizza_cheese = 0;
pizza_pep = 0;
pizza_ham = 0;
}
public Pizza(Pizza copyPizza) {
pizza_size = copyPizza.getPizzaSize();
pizza_cheese = copyPizza.getNumCheese();
pizza_pep = copyPizza.getNumPep();
pizza_ham = copyPizza.getNumHam();
}
//Setters
public boolean setPizzaSize(String size) {
if (size.equalsIgnoreCase("small") || (size.equalsIgnoreCase("medium") || (size.equalsIgnoreCase("large")))) {
pizza_size = size.toLowerCase();
return true;
}
return false;
}
public void setNumCheese(int numCheeseTop) {
pizza_cheese = numCheeseTop;
}
public void setNumPep(int numPepTop) {
pizza_pep = numPepTop;
}
public void setNumHam(int numHamTop) {
pizza_ham = numHamTop;
}
//End of setters
//Getters
public String getPizzaSize() {
return pizza_size;
}
public int getNumCheese() {
return pizza_cheese;
}
public int getNumPep() {
return pizza_pep;
}
public int getNumHam() {
return pizza_ham;
}
//End of getters
public double calcCost() {
if (pizza_size.toLowerCase() == "small") {
return 10 + ((pizza_cheese + pizza_pep + pizza_ham) * 2);
}
if (pizza_size.toLowerCase() == "medium") {
return 12 + ((pizza_cheese + pizza_pep + pizza_ham) * 2);
}
if (pizza_size.toLowerCase() == "large") {
return 14 + ((pizza_cheese + pizza_pep + pizza_ham) * 2);
}
if (pizza_size.toLowerCase() != "small" && pizza_size.toLowerCase() != "medium"
&& pizza_size.toLowerCase() != "large") {
System.out.println("Invalid pizza size");
return 0;
}
return 0;
}
public String getDescription() {
return pizza_size + " pizza with " + pizza_cheese + " cheese toppings " + pizza_pep + " pepperoni toppings and "
+ pizza_ham + " ham toppings "; //+ " which is " + money.format(pizza2.calcCost());
}
//private String pizza_size;
//private int pizza_cheese, pizza_pep, pizza_ham;
public String pizza_size;
public int pizza_cheese, pizza_pep, pizza_ham;
} //End of Pizza class
PizzaOrderArray.java
import static java.lang.System.out;
public class PizzaOrderArray {
public String pizza_size;
public int pizza_cheese, pizza_pep, pizza_ham;
//private String pizza_size;
//private int pizza_cheese; pizza_pep; pizza_ham;
private Pizza[] pizza;
private int index = 0;
public PizzaOrderArray() {
System.out.println("PizzaOrderArray()");
index = 1;
pizza = new Pizza[index];
}
public PizzaOrderArray(int i) {
System.out.println("PizzaOrderArray(int i)");
index = 1;
pizza = new Pizza[index];
}
public PizzaOrderArray(PizzaOrderArray poa) {
System.out.println("PizzaOrderArray(PizzaOrderArray poa)");
pizza = new Pizza[poa.index];
index = poa.index;
for (int i = 0; i < poa.index; i++) {
System.out.println("PizzaOrderArray(PizzaOrderArray poa) for loop");
pizza[i] = new Pizza(poa.pizza[i]);
}
}
public void setPizza(int index1, Pizza newpizza) {
System.out.println("Inside of setPizza");
pizza[index1] = new Pizza(newpizza);
}
public String getPizzaSize() {
System.out.println("Inside of getPizzaSize");
return pizza_size;
}
public int getNumCheese() {
System.out.println("Inside of getNumCheese");
return pizza_cheese;
}
public int getNumPep() {
System.out.println("Inside of getNumPep");
return pizza_pep;
}
public int getNumHam() {
System.out.println("Inside of getNumHam");
return pizza_ham;
}
public String toString() {
String s = "";
int indexUsed = 0;
System.out.println("Inside of toString");
for (int i = 0; i < indexUsed; i++) {
s = (s + pizza[i].toString());
}
System.out.println("Inside of toString for loop");
return s;
}
public double calcTotal() {
double r = 0.0;
System.out.println("Inside of calcTotal");
for (int i = 0; i < index; i++) {
System.out.println("Inside of calcTotal for loop");
r = r + pizza[i].calcCost();
}
return r;
}
public boolean equals(PizzaOrderArray orderarray) {
boolean r = false;
System.out.println("Inside of equals");
if (orderarray.pizza.length != pizza.length) {
System.out.println("Inside of equals if");
return r;
}
for (int i = 0; i < orderarray.pizza.length; i++) {
if (pizza[i].equals(orderarray.pizza[i])) {
System.out.println("Inside of equals for-if");
r = true;
} else {
System.out.println("Inside of equals for-else");
return false;
}
}
System.out.println("Return of equals");
return r;
}
} //End of PizzaOrderArray class
V4_Project_15_page_418.java
import java.text.DecimalFormat;
import java.util.Scanner;
import java.util.Arrays;
public class V4_Project_15_page_418 {
public static void main(String args[]) {
//Order1
PizzaOrderArray order1 = new PizzaOrderArray();
Pizza pizzaone = new Pizza("Medium", 0, 0, 0);
Pizza pizzatwo = new Pizza("Small", 1, 0, 0);
order1.setPizza(0, pizzaone);
System.out.println("Order 1: ");
System.out.println(order1.toString());
System.out.println(order1);
System.out.println();
//Order2
Pizza pizzathree = new Pizza(pizzatwo);
PizzaOrderArray order2 = new PizzaOrderArray(2);
order2.setPizza(0, pizzaone);
order2.setPizza(0, pizzatwo);
System.out.println("Order 2: ");
System.out.println(order2.toString());
System.out.println(order2);
System.out.println();
//Order3
PizzaOrderArray order3 = new PizzaOrderArray(1);
order3.setPizza(0, pizzaone);
order3.setPizza(0, pizzatwo);
System.out.println("Order 3: ");
System.out.println(order3.toString());
System.out.println(order3);
System.out.println();
//Order4
PizzaOrderArray order4 = new PizzaOrderArray(order3);
System.out.println("Order 4: ");
System.out.println(order4.toString());
System.out.println(order4);
//TEST THE PROGRAM
System.out.println("TEST: The total for order 4 is: " + order4.calcTotal());
System.out.println();
//Order5
PizzaOrderArray order5 = new PizzaOrderArray(order1);
System.out.println("Order5: ");
System.out.println(order5);
System.out.println();
}//End of main class
}//End of V4_Project_15_page_418 class
Output:
PizzaOrderArray()
Inside of setPizza
Order 1:
Inside of toString
Inside of toString for loop
Inside of toString
Inside of toString for loop
PizzaOrderArray(int i)
Inside of setPizza
Inside of setPizza
Order 2:
Inside of toString
Inside of toString for loop
Inside of toString
Inside of toString for loop
PizzaOrderArray(int i)
Inside of setPizza
Inside of setPizza
Order 3:
Inside of toString
Inside of toString for loop
Inside of toString
Inside of toString for loop
PizzaOrderArray(PizzaOrderArray poa)
PizzaOrderArray(PizzaOrderArray poa) for loop
Order 4:
Inside of toString
Inside of toString for loop
Inside of toString
Inside of toString for loop
Inside of calcTotal
Inside of calcTotal for loop
Invalid pizza size
TEST: The total for order 4 is: 0.0
PizzaOrderArray(PizzaOrderArray poa)
PizzaOrderArray(PizzaOrderArray poa) for loop
Order5:
Inside of toString
Inside of toString for loop
Take a close look at the condition in this for loop, it isn't going to ever print anything since the condition is never true since i is never less than indexUsed which is 0.
public String toString() {
String s = "";
int indexUsed = 0;
System.out.println("Inside of toString");
for(int i = 0; i < indexUsed; i++)
s= (s + pizza[i].toString());
System.out.println("Inside of toString for loop");
return s;
}
Something also need pay attention to:
for(int i = 0; i < indexUsed; i++)
s= (s + pizza[i].toString());
System.out.println("Inside of toString for loop");
means:
for(int i = 0; i < indexUsed; i++) {
s= (s + pizza[i].toString());
}
System.out.println("Inside of toString for loop");
So this is System.out.println just misleading you, you are never "inside of" the for loop.
I think it's better to always use the braces '{}' with for/while loop.
The snippet
int indexUsed = 0;
System.out.println("Inside of toString");
for(int i = 0; i < indexUsed; i++)
s= (s + pizza[i].toString()); is wrong, your for loop is never executed since indexUsed is 0
In your toString method, the for loop condition never becomes true (before the first iteration itself, 0<0 becomes false & loop terminates without executing once) so the loop never executes.
You can try changing the for loop statement to:
for(int i = 0; i < index; i++)
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 8 years ago.
How could I get the program to output all the information? IT currently returns a NullPointException error. Thanks.
I am supposed to use the delete methods just as they are, I cannot change them, but I am sure there must be something I can do.
public class TestCandidate7
{
public static int getTotal(Candidate[] election)
{
int total = 0;
for(Candidate candidate : election )
{
total += candidate.numVotes;
}
return total;
}
public static void printResults(Candidate[] election)
{
double percent;
System.out.println("Candidate Votes Received % of Total Votes");
for (int x = 0; x < election.length; x++)
{
percent = (double) (election[x].votes()) / getTotal(election) * 100;
System.out.printf("%-15s %10d %20.0f", election[x].getName(), election[x].votes(), percent);
System.out.println();
}
}
public static void deleteByLoc(Candidate[] election,
int location)
{
if ((location > 0) && (location < election.length))
{
//move items up in the array -
for(int index = location; index < election.length -1; index++)
election[index] = election[index + 1];
election[election.length-1] = null;
}
}
public static void deleteByName(Candidate[] election,
String find)
{
int location = 0;
int index;
// find location of item you want to delete
for(index = 0; index < election.length; index++)
if ((election[index] != null) && (election[index].getName().equals(find)))
{
location = index;
break;
}
else if (election[index] == null)
{
location = -1;
break;
}
if ((index != election.length) && (location >= 0))
{ //move items up in the array
for(index = location; index < election.length -1; index++)
election[index] = election[index + 1];
election[election.length-1] = null;
}
}
public static void main(String[] args)
{
Candidate[] election = new Candidate[10];
// create election
election[0] = new Candidate("John Smith", 5000);
election[1] = new Candidate("Mary Miller", 4000);
election[2] = new Candidate("Michael Duffy", 6000);
election[3] = new Candidate("Tim Robinson", 2500);
election[4] = new Candidate("Joe Ashtony", 1800);
election[5] = new Candidate("Mickey Jones", 3000);
election[6] = new Candidate("Rebecca Morgan", 2000);
election[7] = new Candidate("Kathleen Turner", 8000);
election[8] = new Candidate("Tory Parker", 500);
election[9] = new Candidate("Ashton Davis", 10000);
System.out.println("Original results:");
System.out.println();
printResults(election);
System.out.println();
System.out.println("Total of votes in election: " + getTotal(election) );
System.out.println();
deleteByLoc(election, 6);
System.out.println("Deleted location 6:");
System.out.println();
printResults(election);
System.out.println();
System.out.println("Total of votes in election: " + getTotal(election) );
System.out.println();
deleteByName(election, "Kathleen Turner");
System.out.println("Deleted Kathleen Turner:");
System.out.println();
printResults(election);
System.out.println();
System.out.println("Total of votes in election: " + getTotal(election) );
System.out.println();
}
}
Candidate
public class Candidate
{
// instance variables
int numVotes;
String name;
/**
* Constructor for objects of class InventoryItem
*/
public Candidate(String n, int v)
{
// initialise instance variables
name = n;
numVotes = v;
}
public int votes()
{
return numVotes;
}
public void setVotes(int num)
{
numVotes = num;
}
public String getName()
{
return name;
}
public void setName(String n)
{
name = n;
}
public String toString()
{
return name + " received " + numVotes + " votes.";
}
}
When you "delete" array elements, after the shift you assign null to the most right element of the array.
In your getTotal() you traverse the entire array and retrieve the value of numVotes for each element. When you reach the null element you are getting the exception since null does not have any fields..
This is the zoo manager coding:
public class ZooManager {
public void feedAnimals(Animals a, Food[] arrayFood) {
Food temp = null;
for (int i = 0; i < arrayFood.length; i++) {
if (arrayFood[i].getFoodName().equals(a.getTypeOfFood())) {
arrayFood[i].setAmount(arrayFood[i].getAmount() - 1);
System.out.print("Animal is fed.");
}
}
System.out.print(temp);
}
public void isFoodEmpty(Food[] arrayFood) {
for (int i = 0; i < arrayFood.length; i++) {
if (arrayFood[i] == null) {
System.out.print("True");
} else {
System.out.print("False");
}
}
}
}
This is the code for the main application:
import java.util.Scanner;
public class ZooApp {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Animals[] a = new Animals[4];
for (int i = 0; i < 4; i++) {
System.out.print("Enter the animal name: ");
String an = in.nextLine();
System.out.print("What type of food do they eat: ");
String tof = in.nextLine();
a[i] = new Animals(an, tof);
}
Food[] b = new Food[3];
for (int i = 0; i < 3; i++) {
System.out.print("Enter the type of food: ");
String f = in.nextLine();
System.out.print("Enter the amount: ");
int am = in.nextInt();in.nextInt();
b[i] = new Food(f, am);
}
ZooManager z= new ZooManager();
System.out.print(z.feedAnimals(a[i], b));
System.out.print(z.isFoodEmpty(b[i]));
}
}
I have an error at the two final out prints on the main application. The first one is that "the void type is not allowed there." and "variable i can not be found." The second out put says that "isFoodEmpty cannot be given to the type: Food, required: Food[]." Thank you for any advice or help.
Your isFoodEmpty function is a void, so the first error is telling you that you can't print it because it doesn't return anything. Second, you are passing an individual instance of Food into a function that is looking for an array. That's the second error. Also note that variable i is only defined within the scope of the for loop, so you can't go using it outside of the loop.
Edit:
Currently your isFoodEmpty is a void. you have one of two options:
public void isFoodEmpty(Food[] arrayFood) {
for (int i = 0; i < arrayFood.length; i++) {
if (arrayFood[i] == null) {
System.out.print("True");
} else {
System.out.print("False");
}
}
}
}
[...]
isFoodEmpty(b); // it already prints within the function
or
public boolean isFoodEmpty(Food[] arrayFood) {
for (int i = 0; i < arrayFood.length; i++) {
if (arrayFood[i] == null) {
return true;
} else {
return false;
}
}
}
}
[...]
System.out.println(isFoodEmpty(b)); // print the boolean that it returns
Either way, you might want to check the logic on that function, since it will return empty if even one of the elements in the array is null. (You could have 20 food items, then one null value, and it would return true).