Below is my code and I have notes beside where my errors are showing. Im unsure where I am going wrong when recalling my method or if that is even the issue.
import java.util.Scanner;
public class HurlerUse
{
static Hurler[] hurlerArray;
// find lowest score (static method)
public static int findLow(Hurler[] hurlerArray)
{
for(int i = 0; i < hurlerArray.length; i++)
{
int lowest = 0;
int index = 0;
for(int j=0; j<hurlerArray.length; j++)
{
int current = hurlerArray[i].totalPoints();// issue with my method 'totalPoints'
if(current < lowest)
{
lowest = current;
index = i;
}
}
return index;
}
}
//main code
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
Hurler[] hurlerArray = new Hurler[5];
for (int i = 0; i <4; i++)
{
hurlerArray[i] = new Hurler();
System.out.println ("Enter Hurler Name:");
hurlerArray[i].setName(sc.nextLine());
hurlerArray[i].setGoalsScored(sc.nextInt());
System.out.println("Enter the hurler's goals scored");
hurlerArray[i].setPointsScored(sc.nextInt());
System.out.println("Enter the hurler's points scored");
}
for(int i=0;i< hurlerArray.length; i++)
{
hurlerArray[i] = new Hurler(MyName, MyGoalsScored, MyPointsScored);// issue with all 3 objects in the brackets but im unsure of how to fix them
}
System.out.println("The lowest scoring hurler was " + hurlerArray[findLow(hurlerArray)].getName());// error with my code here I think it is in the method
}
}//end of class
I know the nyName, myGoalsScored, myPointsScored is incorrect but can anyone explain why?
This is the class page that accompanies it
public class Hurler
{
private String name;
private int goalsScored;
private int pointsScored;
public Hurler() //constructor default
{
name ="";
goalsScored = 0;
pointsScored = 0;
}
public Hurler(String myName, int myGoalsScored, int myPointsScored) // specific constructor
{
name = myName;
goalsScored = myGoalsScored;
pointsScored = myPointsScored;
}
//get and set name
public String getMyName()
{
return name;
}
public void setName(String myName)
{
name = myName;
}
//get and set goals scored
public int getGoalsScored()
{
return goalsScored;
}
public void setGoalsScored(int myGoalsScored)
{
goalsScored = myGoalsScored;
}
// get and set points scored
public int getPointsScored()
{
return pointsScored;
}
public void setPointsScored(int myPointsScored)
{
pointsScored = myPointsScored;
}
public int totalPoints(int myGoalsScored, int myPointsScored)
{
int oneGoal = 3;
int onePoint = 1;
int totalPoints = ((goalsScored * oneGoal) + (pointsScored * onePoint));
{
return totalPoints;
}
}
}//end of class
You call totalPoints() without parameters while method totalPoints(int, int) in Hurler class expects two int parameters.
Objects MyName, MyGoalsScored, MyPointsScored are not declared at all.
You call getName() method, while in Hurler class you do not have one. There is method getMyName(), maybe you want to call that one.
Related
Cannot make a reference to the nonstatic method toString() other is saying that I can't have a static toString but when I change it and go to the main it says I need a static toString. I was wondering if anyone could make sense of it because I referenced multiple codes and notes from classes but could not understand.
import java.util.Scanner;
import java.util.Arrays;
class Main
{
public static void main(String[] args)
{
String[] answer = new String();
answerArray();
Quiz Quiz1 = new Quiz();
Quiz.toString();
System.out.print("Number of Correct Answers: ");
System.out.println(Quiz.totalCorrect(answerArray[]));
System.out.print("Number of Mistakes: ");
System.out.println(Quiz.totalMistakes(answerArray[]));
System.out.println("The Student is"+Quiz.isPassing());
}
public static String answerArray()
{
Scanner scan = new Scanner(System.in);
String[] answerArray = new String[10];
for (int i = 0; i < answerArray.length; i++)
{
System.out.println("Enter Grade "+i+1);
answerArray[i]=scan.next;
answerArray[i]=answerArray[i].toLowerCase();
}
return answerArray;
}
}
Quiz Class:
import java.util.Arrays;
class Quiz
{
public static void main(String[] args) {
String[] answerKey = new String[10];
String[] studentAns = new String[answerKey.length];
answerKey[0] = B;
answerKey[1] = D;
answerKey[2] = C;
answerKey[3] = A;
answerKey[4] = E;
answerKey[5] = A;
answerKey[6] = B;
answerKey[7] = A;
answerKey[8] = E;
answerKey[9] = B;
}
public static void studentAns(String answerKey[])
{
for (int i = 0; i < answerArray.length; i++)
studentAns[i]=answerKey[i];
for (int i=0; i<answerKey.length;i++)
studentAns[i]=studentAns[i].toUpperCase();
}
public static String getstudentAns()
{
return studentAns;
}
public static int totalCorrect(String answerArray[])
{
int numCorrect=0;
for (int i = 0; i < answerArray.length; i++)
{
if (answerArray[i].equals(studentAns[i]))
numCorrect=numCorrect+1;
}
return numCorrect;
}
public static int totalMistakes(String answerArray[])
{
int numMistakes=0;
for (int i = 0; i < answerKey.length; i++)
{
if (answerArray[i]!=studentAns[i])
numMistakes=numMistakes+1;
}
return numMistakes;
}
public static boolean isPassing()
{
if (totalCorrect-numMistakes>=7)
return PASSED;
else
return FAILED;
}
public static String toString(String answerArray[])
{
String firstLine = "ANSWER KEY \t Student's Answers";
for (int i = 0; i < answerKey.length; i++)
{
String full=(i+1)+") "+answerArray[i]+"\t\t"+(i+1)+studentAns[i]+"\n";
return full;
}
}
}
Here you are trying to use a static method toString() but that does not exist because classes only have the nonstatic method toString().
Quiz.toString();
To use your static method you should write this instead:
Quiz.toString(answerArray());
I've written my first Genetic Algorithm in Java and I'm able to optimize functions with one argument x, but I don't know how to optimize functions with two arguments x and y. Algorithm class and main app works correctly so i send only Individual.java and Population.java. If I think correctly in genes I have only x-coordinate but I'm not sure how to add y-coordinate. Any advise will be helpfull.
Individual.java
public class Individual {
private int[] genes;
private int fitness;
private Random randomGenerator;
public Individual() {
this.genes = new int[Constants.CHROMOSOME_LENGTH];
this.randomGenerator = new Random();
}
public void generateIndividual() {
for(int i = 0; i < Constants.CHROMOSOME_LENGTH; i++) {
int gene = randomGenerator.nextInt(2);
genes[i] = gene;
}
}
public double f(double x) {
// return Math.pow(x,2);
return (Math.pow((1-x),2)) + (100*(Math.pow((1-Math.pow(x,2)),2)));
// return Math.sin(x)*((x-2)*(x-2))+3;
}
public double getFitness() {
double genesToDouble = genesToDouble();
return f(genesToDouble);
}
public double getFitnessResult() {
double genesToDouble = genesToDouble();
return genesToDouble;
}
public double genesToDouble() {
int base = 1;
double geneInDouble = 0;
for( int i =0; i < Constants.GENE_LENGTH; i++) {
if(this.genes[i] == 1)
geneInDouble += base;
base = base*2;
}
geneInDouble = (geneInDouble / 1024) * 10.1;
return geneInDouble;
}
public int getGene(int index) {
return this.genes[index];
}
public void setGene(int index, int value) {
this.genes[index] = value;
this.fitness = 0;
}
}
Population.java
public class Population {
private Individual[] individuals;
public Population(int populationSize) {
individuals = new Individual[populationSize];
}
public void initialize() {
for(int i = 0; i < individuals.length; i++) {
Individual newIndividual = new Individual();
newIndividual.generateIndividual();
saveIndividual(i, newIndividual);
}
}
public Individual getIndividual(int index) {
return this.individuals[index];
}
//maksimum lub minimum
public Individual getFittestIndividual() {
Individual fittest = individuals[0];
for(int i =0; i < individuals.length; i++) {
if(getIndividual(i).getFitness() < fittest.getFitness())
fittest = getIndividual(i);
}
return fittest;
}
public int size() {
return this.individuals.length;
}
public void saveIndividual(int index, Individual individual) {
this.individuals[index] = individual;
}
}
This is what i got
Constructor:
public class Assignment08_ {
String name;
String abrv;
int atomicNumber;
double atomicMass;
int group;
int period;
public Assignment08_(String name, String abrv, int atomicNumber, double
atomicMass, int group, int period) {
this.name = name;
this.abrv = abrv;
this.atomicNumber = atomicNumber;
this.atomicMass = atomicMass;
this.group = group;
this.period = period;
}
}
And the Class:
import java.io.File;
import java.util.Scanner;
public class Assignment08 {
public static void main(String[] args) throws Exception {
Assignment08_[] elementArr = new Assignment08_[119];
reader(elementArr);
for(int i = 0; i < args.length; i++) {
action(elementArr, args[i]);
}
}
public static void reader(Assignment08_[] elements) throws Exception {
Scanner data = new Scanner(new File("/srv/datasets/elements"));
while (data.hasNext()) {
int atomicNumber = data.nextInt();
String abrv = data.next();
String name = data.next();
double atomicMass = data.nextDouble();
int period = data.nextInt();
int group = data.nextInt();
elements[atomicNumber] = new Assignment08_(name, abrv, atomicNumber,
atomicMass, group, period);
}
data.close();
}
public static void action(Assignment08_[] element, String str) {
// for testing
System.out.printf("%s%n", element[4].abrv);
for (int i = 0; i < 119; i++) {
if (str.compareTo(element[i].abrv) == 0)
System.out.println(element[i].name);
}
}
}
i input "java Assignment08_ H" (which is equal to element[0].abrv)
i get the output:
"
Be
Exception in thread "main" java.lang.NullPointerException
at Assignment08.action(Assignment08.java:33)\
at Assignment08.main(Assignment08.java:11)
"
Be = element[4].abrv
and its wierd because if i were to take away that for statement and leave only the nested if statement and change the i to a Number (like 0), it will print the name and run properly( if i input H which equals element[0].abrv), soooo i dont know what going on here, any help would be great, thx
I am working on an assignment and I can not figure out what to do. I have three different Java classes. And I am trying to use the methods in one class to do something in a different class. I am making a very primitive playlist program. I have to check to see if the playlist is full, if its not i have to ask the title and artist. Then I have to call my method using the title and artist as parameters. I was wondering if anyone could point me in the right direction as to what I had to do to call the method? I still don't completely understand loops either but i know that I have to use a for loop in order to do this. Thankyou for your time.
Here is my code:
Main Class
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
PlayList p = new PlayList (5);
Scanner sc = new Scanner(System.in);
String command;
String title;
String artist;
System.out.println("Enter a to add, r to remove, d to display,or q to
quit:");
command = sc.nextLine();
while (!command.equals("q")) {
// Interpret command
if (command.equals("a")) {
//add song
for (int i = 0; i <= PlayList.isFull(title, artist);i++) {
if(songs[i])== null {
songs[i] = filled;
}
}
} else if (command.equals("r")) {
// Remove a song
System.out.print("Title: ");
title = sc.nextLine();
p.remove(title);
} else if (command.equals("d")) {
// Fill this in
}
// Get the next command
System.out.println("Enter a to add, r to remove, d to display, or q to
quit:");
command = sc.nextLine();
}
System.out.println("Program Ended");
}
}
PlayList Class
public class PlayList {
private Song [] songs;
private int filled;
public PlayList (int size){
songs = new Song[size];
}
public boolean isFull() {
return (filled >= songs.length);
}
public void add(String t, String a) {
for (int i = 0; i < songs.length; i++){
if (songs[i] == null){
songs[i] = new Song(t,a);
filled++;
}
}
}
public void display() {
for (int i = 0; i < songs.length; i++){
if (songs[i] != null) {
System.out.println(songs[i]);
}
}
}
public void remove(String t) {
//return t?
for (int i = 0; i < songs.length; i--){
if (songs[i] == null){
songs[i] = null;
break;
}
}
}
}
Song Class
public class Song {
String title;
String artist;
public Song (String t, String a) {
title = t;
artist = a;
}
public String toString() {
return "Title: " + title + " " + "Artist: " + artist;
}
}
First of all you are using isFull function of class PlayList wrong.
for (int i = 0; i <= PlayList.isFull(title, artist);i++)
isFull is a no argument function, and you are using it with passing 2 arguments.
isFull function returns a boolean value (i.e. true/false), but you are comparing it with an int, which does not make any sense.
isFull is not a static function. Therefore you cannot use it directly with class name.
-either you will need to declare function isFull as static.
public static boolean isFull()
-or you will need to create an object of class PlayList in class Main and then call the java function using that java object.
Also, your Function remove is not performing any task
if (songs[i] == null){
songs[i] = null;
}
It is checking if songs[i] is already null and then it sets it back to null, which does not make any sense.
And you should increment i (i.e. i++) not decrement it (i.e. i--)
for (int i = 0; i < songs.length; i--)
If you want to call method from another class that method must be a static method. Then you can call it using Class name and Method name.
For an example;
public class main(){
A a = new A();
a.x();
}
public class A{
public static void x(){};
}
You called isFull method with two parameters but your PlayList class does not have any parameter for isFull method. That is an error.
I re-write your assignment class set using ArrayList for PlayList class. Follow this codes. Hope you can understand it's concept of OOP(Follow this tutorials. https://www.javatpoint.com/java-oops-concepts).
Main Class
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
PlayList p = new PlayList (5);
Scanner sc = new Scanner(System.in);
String command;
String title;
String artist;
System.out.println("Enter a to add, r to remove, d to display,or q to quit:");
command = sc.nextLine();
while (!command.equals("q")) {
// Interpret command
if (command.equals("a")) {
//add song
System.out.println("Enter Title:");
title = sc.nextLine();
System.out.println("Enter Artist:");
artist = sc.nextLine();
if(!p.isFull()) {
p.add(title, artist);
System.out.println("Added Success!");
}
else
System.out.println("Sorry,Playlist is full");
} else if (command.equals("r")) {
// Remove a song
System.out.print("Title: ");
title = sc.nextLine();
p.remove(title);
} else if (command.equals("d")) {
// Fill this in
p.display();
}
// Get the next command
System.out.println("Enter a to add, r to remove, d to display, or q to quit:");
command = sc.nextLine();
}
System.out.println("Program Ended");
}
}
PlayList Class
import java.util.ArrayList;
import java.util.List;
public class PlayList {
private static List<Song> songs;
private static int filled;
private static int size = 0;
public PlayList (int s){
songs = new ArrayList<>();
size = s;
}
public static boolean isFull() {
return (filled == size);
}
public static void add(String t, String a) {
songs.add(new Song(t,a));
filled++;
}
public void display() {
for (int i = 0; i < songs.size(); i++){
if (songs.get(i) != null) {
System.out.println(songs.get(i));
}
}
}
public void remove(String t) {
//return t?
for (int i = 0; i < songs.size(); i++){
if (songs.get(i).title == t){
songs.remove(i);
break;
}
}
}
public static int getSize(){
return songs.size();
}
}
Song Class is same as you wrote.
I'm trying to access the method changeAll from class MarkMaker the following way:
import java.util.Scanner;
class Question10e
{
public static void main(String[] args)
{
System.out.println();
Scanner input = new Scanner(System.in);
System.out.print("Enter mark 1: ");
int newm1=input.nextInt();
System.out.print("Enter mark 2: ");
int newm2=input.nextInt();
System.out.print("Enter mark 3: ");
int newm3=input.nextInt();
String linem=input.nextLine();
System.out.print("Enter a master password: ");
String masterpass = input.next();
linem=input.nextLine();
MarkMaker mm = new MarkMaker(masterpass);
Mark masterMark1 = mm.makeMark(newm1);
Mark masterMark2 = mm.makeMark(newm2);
Mark masterMark3 = mm.makeMark(newm3);
try{
System.out.println("The new mark 1 is "+masterMark1.provisional(masterpass));
System.out.println("The new mark 2 is "+masterMark2.provisional(masterpass));
System.out.println("The new mark 3 is "+masterMark3.provisional(masterpass));
System.out.println("The new master password is is "+masterMark1.returnPass());
int avg = mm.average();
System.out.println("The average is "+avg);
changeAll(5.5, 3);
}
catch(IncorrectPasswordException e){}
}
}
This is the MarkMaker class:
import java.util.*;
class MarkMaker{
private String masterPass = "";
private ArrayList<Mark> masterArr = new ArrayList<Mark>();
public MarkMaker(String masterPass)
{
this.masterPass = masterPass;
}
public Mark makeMark(int m)
{
Mark newMarkObj = new Mark(m,masterPass);
masterArr.add(newMarkObj);
return newMarkObj;
}
public ArrayList<Mark> returnMasterArr()
{
return masterArr;
}
public int average() throws IncorrectPasswordException
{
int n = 0;
for(int i=0; i<masterArr.size(); i++)
{
n = n + masterArr.get(i).provisional(masterPass);
}
int avg = n/masterArr.size();
return avg;
}
public void changeAll(double d, int x) throws IncorrectPasswordException
{
for(int i=0; i<masterArr.size(); i++)
{
double currentMark = masterArr.get(i).provisional(masterPass);
System.out.println("Current mark is: "+currentMark);
currentMark = currentMark*d;
System.out.println("Current mark is: "+currentMark);
currentMark = Math.ceil(currentMark);
System.out.println("Current mark is: "+currentMark);
}
} }
And this is the Mark class:
class Mark
{
private int value;
private String password;
boolean released;
public Mark(int value, String password)
{
this.value = value;
this.password = password;
released = false;
}
public void release(String p) throws IncorrectPasswordException
{
if(p.equals(password))
{
if(released==false)
released = true;
}
else throw new IncorrectPasswordException(p);
}
public int value() throws UnReleasedException
{
if(released==true)
return value;
else
throw new UnReleasedException();
}
public int provisional(String p) throws IncorrectPasswordException
{
if(p.equals(password))
return value;
else
throw new IncorrectPasswordException(p);
}
public void change(String p, int arg) throws IncorrectPasswordException
{
if(p.equals(password))
value = arg;
else
throw new IncorrectPasswordException(p);
}
public String returnPass()
{
return password;
}
public boolean isReleased()
{
return released;
}
public boolean equals(Mark m2) throws UnReleasedException
{
if(this.isReleased() && m2.isReleased())
{ //it throws an error, that's why i'm using the Unreleased Exception
if(this.value()==m2.value())
return true;
}
throw new UnReleasedException();
} }
The problem is that I always get a "cannot find symbol error - method changeAll(double, int), location class Question10e"
Question10e doesn't have this method. Perhaps you intended to call this on an instance of a class which does like.
mm.changeAll(5.5, 3);
changeAll is a method which belongs to the MarkMaker class rather than the current Question10e class where you are attempting to call the method:
mm.changeAll(5.5, 3);
You need to call changeAll() through a MarkMarker object. It doesn't exist in your Question10e class. So, you could do this by:
mm.changeAll(5.5, 3)
Just because changeAll() is public doesn't mean that you can call it from anywhere. It simply means that a MarkMarker object can call it from anywhere.
You need
mm.changeAll(5.5, 3);