using loop variables with object variables - java

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

Related

How to get user input and store in custom object? JAVA

Henlo,
Basically what im trying to do is get user inputs and store in a custom object but I have no idea on how to go about it. I have created a loadDataFromConfig() method? that works fine when creating the object SmartHome app = new SmartHome(loadDataFromConfig());.
But I am completely stumped on how to get user inputs and store them in this format: dev[0] = new SmartDevice("device 1",1.3,true);.
All the code that is meant to run should be inside the main method in Step1.java
Here are the 3 classes used for the code (ignore comments they are just notes for me):
package SmartHomeApp;
public class SmartDevice {
private String name;
private double location;
private boolean switchedOn;
public SmartDevice(String val1, double val2, boolean val3) {
setName(val1);
setLocation(val2);
setSwitchedOn(val3);
}
//YOU CANT ACCESS the 'private classes' so you need to GET them
public void setName(String value) {name = value;}
public void setLocation(double value) {location = value;}
public void setSwitchedOn(boolean value) {switchedOn = value;}
public String getName() {return name;}
public double getLocation() {return location;}
public boolean getSwitchedOn() {return switchedOn;}
}
package SmartHomeApp;
public class SmartHome
{
private SmartDevice[] smrtDev;
public SmartHome(int size) {
smrtDev = new SmartDevice[size];
}
public SmartHome(SmartDevice[] values) {
smrtDev = values;
}
public int size() {return smrtDev.length;}
// can't do toString() for some reason??
public void ToString() {
for(int i=0; i<size();i++)
{
if(smrtDev[i] != null ){
System.out.println("----------");
System.out.println("-DEVICE "+(i+1)+"-");
System.out.println("----------");
System.out.println("Name: "+smrtDev[i].getName());
System.out.println("Location: "+smrtDev[i].getLocation());
System.out.println("Switched On: "+smrtDev[i].getSwitchedOn());
}
}
}
}
package SmartHomeApp;
import java.util.*;
public class Step1 {
public static void main(String args[]) {
SmartHome app = new SmartHome(loadDataFromConfig());
app.ToString();
}
public static SmartDevice[] loadDataFromConfig()
{
SmartDevice[] dev = new SmartDevice[20];
dev[0] = new SmartDevice("device 1",1.3,true);
dev[1] = new SmartDevice("device 2",2.3,false);
dev[2] = new SmartDevice("device 3",3.3,true);
dev[4] = new SmartDevice("device 5",4.3,false);
dev[19] = new SmartDevice("device 20",5.3,false);
return dev;
}
}
Some of the improvements required in your code are as follows:
Follow Java naming conventions e.g. ToString() should be toString(). Check this to learn more about toString(). Most of the IDEs (e.g. eclipse) provide a feature to generate toString() method on click of a button. Whatever way (either manual or with the help of your IDE) you generate it, it must return a String.
You should do away with using next(), nextInt(), nextDouble() etc. and use nextLine() instead. Check this to learn more it. To give you an idea what problems next(), nextDouble() can cause, try entering a name with a space e.g.
Enter size:
2
Name:
Light Amplification by Stimulated Emission of Radiation
Location:
Exception in thread "main" java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Scanner.java:939)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextDouble(Scanner.java:2564)
at Main.main(Main.java:83)
Given below is a sample code incorporating the improvements mentioned above:
import java.util.Scanner;
class SmartDevice {
private String name;
private double location;
private boolean switchedOn;
public SmartDevice(String val1, double val2, boolean val3) {
setName(val1);
setLocation(val2);
setSwitchedOn(val3);
}
// YOU CANT ACCESS the 'private classes' so you need to GET them
public void setName(String value) {
name = value;
}
public void setLocation(double value) {
location = value;
}
public void setSwitchedOn(boolean value) {
switchedOn = value;
}
public String getName() {
return name;
}
public double getLocation() {
return location;
}
public boolean getSwitchedOn() {
return switchedOn;
}
#Override
public String toString() {
return "SmartDevice [name=" + name + ", location=" + location + ", switchedOn=" + switchedOn + "]";
}
}
class SmartHome {
private SmartDevice[] smrtDev;
public SmartHome(int size) {
smrtDev = new SmartDevice[size];
}
public SmartHome(SmartDevice[] values) {
smrtDev = values;
}
public int size() {
return smrtDev.length;
}
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
for (SmartDevice smartDevice : smrtDev) {
sb.append(smartDevice.toString()).append("\n");
}
return sb.toString();
}
}
public class Main {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in);
int size = getPositiveInt(myObj, "Enter size: ");
SmartDevice[] newList = new SmartDevice[size];
for (int i = 0; i < newList.length; i++) {
System.out.print("Name: ");
String x = myObj.nextLine();
double y = getFloatingPointNumber(myObj, "Location: ");
boolean z = getBoolean(myObj, "Is on?: ");
newList[i] = new SmartDevice(x, y, z);
}
SmartHome newDevice = new SmartHome(newList);
System.out.println(newDevice);
}
static int getPositiveInt(Scanner in, String message) {
boolean valid;
int n = 0;
do {
valid = true;
System.out.print(message);
try {
n = Integer.parseInt(in.nextLine());
if (n <= 0) {
throw new IllegalArgumentException();
}
} catch (IllegalArgumentException e) {
System.out.println("This in not a positive integer. Please try again.");
valid = false;
}
} while (!valid);
return n;
}
static double getFloatingPointNumber(Scanner in, String message) {
boolean valid;
double n = 0;
do {
valid = true;
System.out.print(message);
try {
n = Double.parseDouble(in.nextLine());
} catch (NumberFormatException | NullPointerException e) {
System.out.println("This in not a number. Please try again.");
valid = false;
}
} while (!valid);
return n;
}
static boolean getBoolean(Scanner in, String message) {
System.out.print(message);
return Boolean.parseBoolean(in.nextLine());
}
}
A sample run:
Enter size: x
This in not a positive integer. Please try again.
Enter size: -2
This in not a positive integer. Please try again.
Enter size: 10.5
This in not a positive integer. Please try again.
Enter size: 2
Name: Light Amplification by Stimulated Emission of Radiation
Location: 123.456
Is on?: true
Name: Vacuum Diode
Location: 234.567
Is on?: no
SmartDevice [name=Light Amplification by Stimulated Emission of Radiation, location=123.456, switchedOn=true]
SmartDevice [name=Vacuum Diode, location=234.567, switchedOn=false]
So as suggested I tried to do the following:
public static void main(String args[]) {
Scanner myObj = new Scanner(System.in);
System.out.println("Enter size: ");
int size = myObj.nextInt();
SmartDevice[] newList = new SmartDevice[size];
for(int i =0; i<newList.length;i++) {
System.out.println("Name: ");
String x = myObj.next();
System.out.println("Location: ");
double y = myObj.nextDouble();
System.out.println("Is on?: ");
boolean z = myObj.nextBoolean();
newList[i] = new SmartDevice(x,y,z);
}
SmartHome newDevice = new SmartHome(newList);
newDevice.ToString();
}
Got it working but not sure if this is the most efficient way to do so??

Sorting an ArrayList of Names using a Comparator that sorts by length

I'm having trouble with my code. I tried using Strings for the arraylist but it doesn't work. When I put the class name in the arraylist, it only prints a different value. I made a class to get the length because doing it in the comparator didn't work; it just gives me a cannot find symbol error.
import java.util.*;
import java.io.*;
class StringLengthComparator implements Comparator<Name>
{
public int compare(Name n1, Name n2)
{
return n1.getLength()-n2.getLength();
}
}
public class Name implements Comparable<Name>
{
public static String name;
public Name(String n)
{
this.name = n;
}
public int compareTo(Name that)
{
return this.name.compareTo(that.name);
}
public String getName()
{
return this.name;
}
public int getLength()
{
return this.name.length();
}
public static void main(String[] args) throws Exception
{
ArrayList<Name> N = new ArrayList<>(5);
BufferedReader keyIn = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Please Enter Name: ");
//String n = keyIn.readLine();
for(int i=0;i<5;i++)
{
String n = keyIn.readLine();
N.add(new Name(n));
}
System.out.print("\n");
Collections.sort(N);
for(int i=0;i<N.size();i++)
{
System.out.println(N.get(i));
}
System.out.print("\n");
Collections.sort(N, new StringLengthComparator());
for(int i=0;i<N.size();i++)
{
System.out.println(N.get(i));
}
}
}
Error #1 for ArrayList<\String> N = new ArrayList<\String>
Error #2 for ArrayList <\Name> N = new ArrayList<>(5)
If you want to sort by length and alphabetically by choice you need 2 comperators and choose each time which one to use, by N.sort(new X), where X is the name of the comperator class you want.
You don't need Collections.sort():
class StringLengthComparator implements Comparator<Name> {
public int compare(Name n1, Name n2) {
return n1.getLength()-n2.getLength();
}
}
class StringCommonComparator implements Comparator<Name> {
public int compare(Name n1, Name n2) {
return n1.getName().compareTo(n2.getName());
}
}
public class Name {
private String name;
public Name(String n) {
this.name = n;
}
public String getName() {
return this.name;
}
public int getLength() {
return this.name.length();
}
public static void main(String[] args) throws Exception {
ArrayList<Name> N = new ArrayList<>(5);
BufferedReader keyIn = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Please Enter Name: ");
String n = keyIn.readLine();
N.add(new Name(n));
for(int i=0; i<5; i++) {
String name = keyIn.readLine();
N.add(new Name(name));
}
System.out.println();
System.out.println("Compare by Length");
N.sort(new StringLengthComparator());
for(int i=0;i<N.size();i++) {
System.out.println(N.get(i).name);
}
System.out.println();
System.out.println("Compare by String");
N.sort(new StringCommonComparator());
for(int i=0;i<N.size();i++) {
System.out.println(N.get(i).name);
}
}
}
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
class StringLengthComparator implements Comparator<Name> {
#Override
public int compare(Name n1, Name n2) {
return n1.getLength() - n2.getLength();
}
}
public class Name implements Comparable<Name> {
public static String name;
public Name(String n) {
this.name = n;
}
#Override
public int compareTo(Name that) {
return this.name.compareTo(that.name);
}
public String getName() {
return this.name;
}
public int getLength() {
return this.name.length();
}
public static void main(String[] args) throws Exception {
ArrayList<Name> N = new ArrayList<>(5);
BufferedReader keyIn = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Please Enter Name: ");
for (int i = 0; i < 5; i++) {
String n = keyIn.readLine();
N.add(new Name(n));
}
System.out.print("\n");
Collections.sort(N);
for (Name name : N) {
System.out.println(name.getName());
}
System.out.print("\n");
Collections.sort(N, new StringLengthComparator());
for (int i = 0; i < N.size(); i++) {
System.out.println(N.get(i));
}
}
}

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.

Creating an ArrayList of Employees

I have three classes
employee
production workers
shift supervisor class
My idea is to make production and shift supervisor extend the employee class and then create another class, EmployeeList to fill it with information about production workers and shift supervisors.
How can i get the names and info from employee class to iterate into an arraylist?
How can i add a random list of employees more than half being prod. workers and the rest shift supervisors?
Employee:
public class Employee {
public String EmployeeName;
public String EmployeeNumber;
public int hireyear;
public double WeeklyEarning;
public Employee()
{
EmployeeName = null;
EmployeeNumber = null;
hireyear = 0;
WeeklyEarning = 0;
}
public static final String[] Enum = new String[] {
"0001-A", "0002-B","0003-C","0004-D","0002-A",
"0003-B","0004-C","0005-D","0011-A", "0012-B",
"0013-C","0014-D","0121-A", "0122-B","0123-C" };
public static final String[] Ename = new String[] {
"Josh", "Alex", "Paul", "Jimmy", "Josh", "Gordan", "Neil", "Bob",
"Shiv", "James", "Jay", "Chris", "Michael", "Andrew", "Stuart"};
public String getEmployeeName()
{
return this.EmployeeName;
}
public String getEmployeeNumber()
{
return this.EmployeeNumber;
}
public int gethireyear()
{
return this.hireyear;
}
public double getWeeklyEarning()
{
return this.WeeklyEarning;
}
public String setEmployeeName(String EName)
{
return this.EmployeeName = EName;
}
public String setEmployeeNumber(String ENumber)
{
return this.EmployeeNumber = ENumber;
}
public int setEmployeehireyear(int Ehireyear)
{
return this.hireyear = Ehireyear;
}
public double setEmployeeweeklyearning(double Eweeklyearning)
{
return this.WeeklyEarning = Eweeklyearning;
}
}
ProductionWorker:
import java.util.Random;
public class ProductionWorker extends Employee {
public double HourlyRate;
public ProductionWorker()
{
super();
HourlyRate = 0;
}
public static void main(String[] args) {
ProductionWorker pw = new ProductionWorker();
Random rnd = new Random();
int count =0;
// adding random Employees.....
while(count<5)
{
int num= rnd.nextInt(Enum.length);
int decimal = rnd.nextInt(10);
double dec = decimal/10;
pw.setEmployeeName(Ename[num]);
pw.setEmployeeNumber(Enum[num]);
pw.setEmployeehireyear(rnd.nextInt(35) + 1980);
pw.setEmployeeweeklyearning(rnd.nextInt(5000) + 5000);
pw.setHourlyRate(rnd.nextInt(44) + 6 + dec);
System.out.println("EmployeeName: " + pw.getEmployeeName() + "\nEmployeeNumber: " + pw.getEmployeeNumber() +
"\nHireYear: " + pw.gethireyear() + "\nWeeklyEarning: " + pw.getWeeklyEarning() +
"\nHourlyRate: " + pw.getHourlyRate() +"\n");
count++;
}
}
public double getHourlyRate()
{
return this.HourlyRate;
}
public void setHourlyRate(double hourlyrate)
{
this.HourlyRate = hourlyrate;
}
}
ShiftSupervisor:
import java.util.Random;
public class ShiftSupervisor extends Employee{
public double YearlySalary;
public int GoalsCleared;
public ShiftSupervisor()
{
super();
YearlySalary = 0;
}
public static void main(String[] args) {
ShiftSupervisor S = new ShiftSupervisor();
Random rnd = new Random();
int count =0;
// adding random Employees.....
System.out.println("Adding Employees..");
while(count<5)
{
int num= rnd.nextInt(Enum.length);
S.setEmployeeName(Ename[num]);
S.setEmployeeNumber(Enum[num]);
S.setEmployeehireyear(rnd.nextInt(35) + 1980);
S.setEmployeeweeklyearning(rnd.nextInt(100) * 100);
S.setYearlySalary(rnd.nextInt(40000) + 40000);
System.out.println("EmployeeName:" + S.getEmployeeName() + "\nEmployeeNumber: " + S.getEmployeeNumber() +
"\nHireYear: " + S.gethireyear() + "\nWeeklyEarning: " + S.getWeeklyEarning() +
"\nearlySalary: " + S.getYearlySalary() +"\n");
count++;
}
}
// returns yearly salary
public double getYearlySalary()
{
return this.YearlySalary;
}
// returns goals cleared
public int getGoalsCleared()
{
return this.GoalsCleared;
}
// set yearly salary
public void setYearlySalary(double yearlysalary)
{
this.YearlySalary = yearlysalary;
}
}
The first thing I would do is have all necessary fields set in the constructor. If an Employee doesn't "exist" until it has a name, then that should be part of the constructor.
Then, I would suggest you consider renaming some of your fields. When I first saw Enum as a String[] and highlighted as a type, it took me a moment to figure out what exactly was going on. Renaming it to employeeNumbers could solve this.
Next, I think you should have an EmployeeGenerator class whose sole purpose is generating Employees.
public class EmployeeGenerator {
public ProductionWorker generateProductionWorker() {
Random rng = new Random();
int numberOfEmployeeNames = employeeNames.length;
String employeeName = employeeNames[rng.nextInt(numberOfEmployeeNames)];
int numberOfEmployeeNumbers = employeeNumbers.length;
String employeeNumber = employeeNumbers[rng.nextInt(numberOfEmployeeNumbers)];
ProductionWorker worker = new ProductionWorker(employeeName, employeeNumber);
int yearHired = rng.nextInt(100) + 1900;
worker.setHireYear(yearHired);
int hourlyRate = rng.nextInt(20) + 10;
worker.setHourlyRate(hourlyRate);
// any other fields...
return worker;
}
// method to generate shift supervisor
}
And then you can simply do
public static void main(String[] args) {
Random rng = new Random();
int numberOfEmployeesToGenerate = 1000;
int minimumNumberOfProductionWorkers = numberOfEmployeesToGenerate / 2;
int numberOfProductionWorkersToGenerate =
minimumNumberOfProductionWorkers + rng.nextInt(100);
int numberOfSupervisorsToGenerator =
numberOfEmployeesToGenerate - numberOfProductionWorkersToGenerate;
List<Employee> employees = new ArrayList<>();
EmployeeGenerator generator = new EmployeeGenerator();
for (int i = 0; i < numberOfProductionWorkersToGenerate; i++) {
ProductionWorker worker = generator.generateProductionWorker();
employees.add(worker);
}
for (int i = 0; i < numberOfSupervisorsToGenerate; i++) {
Supervisor supervisor = generator.generateSupervisor();
employees.add(supervisor);
}
}
This should hopefully give you a point in the right direction. This isn't perfect code, and there are other ways to refactor this to make it more maintainable and performant.
When you say you want to add a random list of employees, What do you mean exactly?
Currently you instantiate only one ProductionWorker and one ShiftSupervisor, change the values of the member variables, and print some text to StdOut.
Do you want to store instances in a list or is the console output sufficient?
Also, you have two main-methods. Which one will be performed? It might be better to have one Main class as an entry point for your application and from there create the instances.
In general you can do something like that:
public class Main {
public static void main(String[] args) {
List<Employee> emps = new ArrayList<>();
for (int i = 0; i < 5; i++) {
//create new employee
emps.add(newEmployee);
}
//do something with list
}
}

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