Not sure how to create a default constructor - java

I'm having trouble creating a parameterless default constructor for this class I am writing. The constructor should go into:
public Track(){
}
The following code is the entire class I'm working on, I've tried using the returned values from the below methods and setting them to 0 but that doesn't seem to work. Any help would be greatly appreciated.
package comp125;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
public class Track {
//removed max entries (was 1000, now has no limit)
ArrayList<Waypoint> pointList = new ArrayList<Waypoint>();{
//for (int i = 0; i < pointList.size(); i++){
//System.out.println(pointList.get(i));
//}
}
Scanner scanner;
String fileMain;
public Track(String filename) throws IOException, GPSException {
Scanner scanner = new Scanner(new FileReader(filename));
scanner.hasNextLine();
while(scanner.hasNextLine()) {
String line = scanner.nextLine();
pointList.add(new Waypoint(line));
}
File f = new File(filename); //easy filenotfound exception
if(!f.exists()){
throw new IOException();
}
fileMain = filename;
}
//This is where we create an empty track
public Track(){
}
public int size() {
return pointList.size();
}
public void add(Waypoint wp) {
pointList.add(pointList.size(), wp);
}
public String getFilename() {
return fileMain;
}
public String getTimestamp() {
return pointList.get(0).getTimestamp();
}
public double getDistance() {
double totDist = 0.0;
for (int i = 1; i < pointList.size(); i++)
{
totDist = totDist + pointList.get(i-1).distanceTo(pointList.get(i));
}
//System.out.println(totDist);
return totDist;
}
public double getElevationGain() {
double elevGain = 0.0;
for(int i = 1; i < pointList.size(); i++){
if(pointList.get(i).getElevation() > pointList.get(i-1).getElevation() ){
elevGain = elevGain + Math.abs(pointList.get(i).getElevation() - pointList.get(i-1).getElevation());
}
}
return elevGain;
}
public String toString() {
String str1 = this.getFilename();
String str2 = this.getTimestamp();
String str3 = String.valueOf(this.getDistance());
String str4 = String.valueOf(this.getElevationGain());
//System.out.println(str1);
//System.out.println(str2);
//System.out.println(str3);
return str1 + str2 + str3 + str4;
}
public Waypoint closestTo(Waypoint wp) {
Waypoint returnValue = pointList.get(0);
for(int i = 1; i < pointList.size(); i++){
if(pointList.get(i).distanceTo(wp) < returnValue.distanceTo(wp)){
returnValue = pointList.get(i);
}
}
return returnValue;
}
}

If you are asking what to put into the parameter-less constructor, you have two options :
Keep it empty - all the properties will be initialized to their default values
public Track()
{
}
Use some default value instead of filename, and use it to initialize the instance the same way you do in your other constructor Track(String filename). You can even call one constructor from the other :
public Track() throws IOException, GPSException
{
this("DEFAULT_FILE_NAME");
}
If you require a parameter-less constructor throwing no exceptions, you can catch the exceptions thrown from the other constructor.

I think what is happening is you're attempting to use the class, but there is no data.
You can create fake (mock) data like so:
public Track(){
for (int i = 0; i < 10; i++){
pointList.add(new Waypoint(/* put the data here that you need for the Waypoint constructor */);
}
}
But your comment //This is where we create an empty track on the constructor seems appropriate...there aren't any tracks =)

Related

I am getting the reference as output. What should i include in my program to get the output

package basicprograms;
public class Progrm {
public long[] ph;
public Progrm(long[] ph){
this.ph=ph;
}
}
The main method:
package basicprograms;
import java.util.ArrayList;
public class UseProgrm {
public static void main(String[] args) {
ArrayList<Progrm> ar = new ArrayList<>();
Progrm p1 = new Progrm(new long[] { 942758427l, 4298578432l, 3425962l });
Progrm p2 = new Progrm(new long[] { 942758427l, 4298578432l, 3425962l });
Progrm p3 = new Progrm(new long[] { 942758427l, 4298578432l, 3425962l });
ar.add(p1);
ar.add(p2);
ar.add(p3);
for (int i = 0; i < ar.size(); i++) {
System.out.println(ar.get(i));
}
}
}
By default, all classes in Java inherit from the Object class. In this case what you are actually printing is Progrm::toString method that is inherited for the Object class and by default is returning the hash. If you would like to print the content of the array(public member ph of the Progrm class) then you should override the toString of Progrm as follows:
public class Progrm {
public long[] ph;
public Progrm(long[] ph) {
this.ph=ph;
}
#Override
public String toString() {
return "Progrm{" +
"ph=" + Arrays.toString(ph) +
'}';
}
}
and the output will be:
Progrm{ph=[942758427, 4298578432, 3425962]}
Progrm{ph=[942758427, 4298578432, 3425962]}
Progrm{ph=[942758427, 4298578432, 3425962]}
For more info on Object::toString, you can refer to :
Why does the default Object.toString() include the hashcode?
You have to override the toString() method in your Program class
now, the System.out.println statements are calling the default implementation of the Object class.
Add this to your Program class:
public String toString() {
StringBuilder b = new StringBuilder("");
for ( long p : ph) {
b.append("Value: " + p + ", ");
}
return b.toString();
}
Afterwards, you can modify it to fit your needs.
Try this:
for (int i = 0; i < ar.size(); i++) {
for(int j = 0; j < ar.get(i).ph.length; j++)
System.out.println(ar.get(i).ph[j]);
}

Issue recalling method. unsure of where im going wrong

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.

How do you use methods from sub classes in the main class in Java?

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.

Elements from a text file not being added to the array

I'm trying to add an Entry object to an array of Entries which consists of a Surname, Initial and Extention number. The first word on the line is the surname etc. however when I print the array using System.out.print(Arrays.toString(entries)); it doesn't print the array or it is empty.
Entry class
public class Entry {
private String surname, initial, extension;
public Entry() {
}
// shadowing
public Entry(String line) {
String[] lines = line.split("\t");
this.surname = lines[0];
this.initial = lines[1];
this.extension = lines[2];
}
public void setSurname(String sur) {
this.surname = sur;
}
public void setInitial(String ini) {
this.initial = ini;
}
public void setExtention(String ext) {
this.extension = ext;
}
public String getSurname() {
return surname;
}
public String getInitial() {
return initial;
}
public String getExtension() {
return extension;
}
}
Array directory class
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.Scanner;
public class ArrayDirectory implements Directory {
Entry[] entries = new Entry[0];
int lines = 0;
public ArrayDirectory() {
try {
Scanner inFile = new Scanner(new FileReader("directory.txt"));
Scanner lCounter = new Scanner(new FileReader("directory.txt"));
while (lCounter.hasNext()) {
lCounter.nextLine();
lines++;
}
entries = new Entry[lines];
for(int i = 0; i < lines; i++){
addEntry(inFile.nextLine());
}
}
catch (IOException e) {
System.out.println(e.getMessage());
}
}
public void addEntry(String l) {
Entry newEntry = new Entry(l);
int i = 0;
while(entries[i] != null) i++;
}
public void printTable(){
System.out.print(Arrays.toString(entries));
}
}
You are not adding anything to your array:
public void addEntry(String l) {
Entry newEntry = new Entry(l);
int i = 0;
while(entries[i] != null) i++;
}
You are missing an eventual entries[i] = newEntry;. Of course, once your array is full you'll get an exception with this code. You must ensure i doesn't grow larger than entries.size -1.
Consider using a list instead of an array.
Your Entry class need to override the toString() method. It is this method that Arrays.toString() will use and unless you implement your own version it will fall back to the default one from java.lang.Object which is not very human friendly.
#Override
public String toString() {
return String.format("%s. %s", this.initial, this.surname);
}
You might be better off using a more flexible storage type too so you do not have to read through the file twice. An ArrayList would be appropriate and you can convert it to an array trivially after you have finished adding new entries to it.
How big is your file? Maybe a BufferedReader would be a better choice?
File file = new File("directory.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
List<Entry> entries = new ArrayList<Entry>()
while ((line = br.readLine()) != null) {
entries.add(new Entry(line));
}
br.close();
Edit: You are not actually adding your Entry objects to the array. You should change this section:
entries = new Entry[lines];
for(int i = 0; i < lines; i++){
addEntry(inFile.nextLine());
}
and this method:
public void addEntry(String l) {
Entry newEntry = new Entry(l);
int i = 0;
while(entries[i] != null) i++;
}
You could add entries[i] = newEntry; just after that final while loop but it is a very poor way to do it. You are iterating through the whole array every time you add a new item. I'd suggest the ArrayList method I describe above.

Java cannot find symbol error - a method from another class

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);

Categories

Resources