I have a class file name serializedObject, I will like to call this class file in another class file and use it's method.
I want to declare the class file became and array to being use in another class file.
Then I declare something like below:
serializedObject[] setData = new serializedObject[10];
and use it into a for loop
for(int i=0; i<clientInfo.length; i++)
{
double locationX = clientInfo[i].getLocation().getX();
double locationY = clientInfo[i].getLocation().getY();
String name = clientInfo[i].getName();
double mood = clientInfo[i].getMood();
double hunger = clientInfo[i].getHunger();
double chargestate = clientInfo[i].getChargestate();
setData[i].setAll(locationX, locationY, name, mood, hunger, chargestate);
System.out.println(setData[i].getName());
}
In the serializedObject class I have the set method and also get method,
but seems like not work for this. What can i do instead of this way to get an array method?
Thanks for any comment and help.
The system seems like cant really set my value into the method,
i cant get the any value from the
System.out.println(setData[i].getName());
but the system doesn't have any compile error.
Here will be my serializedObject class file
public class serializedObject
{
public static double locationX;
public static double locationY;
public static String name;
public static double mood;
public static double hunger;
public static double chargestate;
public serializedObject()
{
}
public void setAll(double locationX,double locationY, String name,double mood,double hunger, double chargestate)
{
this.locationX = locationX;
this.locationY = locationY;
this.name = name;
this.mood = mood;
this.hunger = hunger;
this.chargestate = chargestate;
}
public String getName()
{
return this.name;
}
public double getLocationX()
{
return this.locationX;
}
public double getLocationY()
{
return this.locationY;
}
public double getMood()
{
return this.mood;
}
public double getHunger()
{
return this.hunger;
}
public double getChargestate()
{
return this.chargestate;
}
}
Note that this serializedObject[] setData = new serializedObject[10]; will just create the array. All elements are still null thus calling methods on those elements (like getName()) will result in a NullPointerException. You'd have to initialize the elements first: setData [0] = new serializedObject(); then you call call methods on the element.
First of all, by convention, the initial letter of a class name should be capitalized as such, SerializedObject. In your for-loop, you'll need to do the following:
for(int i = 0; i < clientInfo.length; i++)
{
// Construct new serialized object
setData[i] = new SerializedObject();
// Extract client information
double locationX = clientInfo[i].getLocation().getX();
double locationY = clientInfo[i].getLocation().getY();
String name = clientInfo[i].getName();
double mood = clientInfo[i].getMood();
double hunger = clientInfo[i].getHunger();
double chargestate = clientInfo[i].getChargestate();
// Store information in serialized object
setData[i].setAll(locationX, locationY, name, mood, hunger, chargestate);
// Add serialized object to array
System.out.println(setData[i].getName());
}
Note: At the moment, your program should be throwing a NullPointerException, which should have let you know that the elements within setData are null.
public static double locationX;
public static double locationY;
public static String name;
public static double mood;
public static double hunger;
public static double chargestate;
These properties are all static. That means they will be shared between all instances of serializedObject. Therefore, if you do setAll on one instance, it will seem to change every other instance.
You should make these instance members:
public double locationX;
public double locationY;
public String name;
public double mood;
public double hunger;
public double chargestate;
Fields should usually not be public, but that's a separate discussion.
Related
I have created two classes, when I entered negative quantity and negative price it does not set to be "0" and "0.0" respectively as I assigned condition in setitmprch(int itmprch) and setitmprch(int itmprch) methods. Kindly tell where I did a mistake.
public class INVOICE {
private String pn;
private String pdscp;
private int itmprch;
private double prpitm;
private double amount;
public INVOICE(String pn, String pdscp, int itmprch, double prpitm ){
this.pn=pn;
this.pdscp=pdscp;
this.itmprch=itmprch;
this.prpitm=prpitm;
}
public void setpn(String pn){
this.pn=pn;
}
public void setpdscp(String pdscp){
this.pdscp=pdscp;
}
public void setitmprch(int itmprch){
if (itmprch < 0)
itmprch=0;
}
public void setprpitm(double prpitm){
if(prpitm > 0.0)
this.prpitm=prpitm;
else if(prpitm < 0.0)
this.prpitm=0.0;
}
public String getpn(){
return pn;
}
public String getpdscp(){
return pdscp;
}
public int getitmprch(){
return itmprch;
}
public double getprpitm(){
return prpitm;
}
public double getInvoiceAmount(){
amount= getitmprch()*getprpitm();
return amount;
}
}
public class INVOICETEST {
public static void main(String[] args) {
// TODO code application logic here
INVOICE in= new INVOICE("Mercedez","Arw 777",-3,-2.0);
System.out.printf("Part number is: %s\n",in.getpn());
System.out.printf("Part decription is: %s\n", in.getpdscp());
System.out.printf("Item purchased: %s\n",in.getitmprch());
System.out.printf("Price per item is: %s\n",in.getprpitm());
System.out.printf("Total amount is: %s\n",in.getInvoiceAmount());
}
}
You are assigning values to the method parameters, which will be lost as soon as you exit your method. Add this.itmprch = itmprch to your setitmprch method. Also have a look at some Java programming guidelines to improve code readability.
public void setitmprch(int itmprch){
if (itmprch < 0)
itmprch=0;
this.itmprch = itmprch;
}
Also your constructor should call the setter methods instead of assign values directly. It would look something like this:
public INVOICE(String pn, String pdscp, int itmprch, double prpitm ){
setpn(pn);
setpdscp(pdscp);
setitmprch(itmprch);
setprpitm(prpitm);
}
Don't use all caps for class names.
Use more descriptive variable names - my eyes are bleeding looking at this and it takes 10x longer to understand than it should.
Use automatic properties rather than having private backing fields and void methods to set/get.
Use property for simple calculations such as working out invoice amount.
Don't asssign to private variable then return said variable.
Use unit tests to test your logic rather than a main method. What happens when your code grows, how are you going to test it all using one entry point?
Don't use protected keywords like in for variable names (in your main function).
The following code is in C#, but it should be easily transcribable to Java. Do some research on unit testing frameworks for Java and try and incorporate that into your workflow.
public class Invoice
{
public string ModelName { get; set; }
public double Price { get; set; }
public double Amount { get; set; }
public double InvoiceAmount => Price * Amount;
}
[TestClass]
public class InvoiceTest
{
[TestMethod]
public void TestInvoiceAmount()
{
// Arrange
var testInvoice = new Invoice()
{
ModelName = "Audi R8",
Price = 5000.0,
Amount = 1
};
// Act
double invoiceAmount = testInvoice.InvoiceAmount;
// Assert
Assert.IsTrue(invoiceAmount == 5000.0);
}
}
I want to create a method calculate the percent change of population growth from the years 1994-2013, and prints out each percentage change. I have the data all stored in, but I am not sure how to iterate the ArrayList to accomplish this
import java.io.*;
import java.util.*;
public class USCrimeClass
{
public int year;
public int population;
public int violentCrime;
public double violentCrimeRate;
public int manslaughter;
public double manslaughterRate;
public int rape;
public double rapeRate;
public int robbery;
public double robberyRate;
public int assault;
public double assaultRate;
public int propertyCrime;
public double propertyCrimeRate;
public int burglary;
public double burglaryRate;
public int larcenyTheft;
public double larcenyTheftRate;
public int vehicleTheft;
public double vehicleTheftRate;
public USCrimeClass(String line)
{
String[]split=line.split(",");
year=Integer.parseInt(split[0]);
population=Integer.parseInt(split[1]);
violentCrime=Integer.parseInt(split[2]);
violentCrimeRate=Double.parseDouble(split[3]);
manslaughter=Integer.parseInt(split[4]);
manslaughterRate=Double.parseDouble(split[5]);
rape=Integer.parseInt(split[6]);
rapeRate=Double.parseDouble(split[7]);
robbery=Integer.parseInt(split[8]);
robberyRate=Double.parseDouble(split[9]);
assault=Integer.parseInt(split[10]);
assaultRate=Double.parseDouble(split[11]);
propertyCrime=Integer.parseInt(split[12]);
propertyCrimeRate=Double.parseDouble(split[13]);
burglary=Integer.parseInt(split[14]);
burglaryRate=Double.parseDouble(split[15]);
larcenyTheft=Integer.parseInt(split[16]);
larcenyTheftRate=Double.parseDouble(split[17]);
vehicleTheft=Integer.parseInt(split[18]);
vehicleTheftRate=Double.parseDouble(split[19]);
}
Scanner read = null;
{
try
{
read=new Scanner(new File("C:\\Crime.csv"));
}
catch(FileNotFoundException e)
{
System.out.println("The file can't be opened");
System.exit(0);
}
List<USCrimeClass> crimeClasses = new ArrayList<>();
read.nextLine();
while(read.hasNextLine())
{
crimeClasses.add(new USCrimeClass(read.nextLine()));
}
read.close();
}
}
Some of the items I'm going to point out are more code review items that aren't specifically related to the business logic of what you're trying to do, however, in the long run your code will be more readable and maintainable.
First, it's a good idea to separate your data model from your controller logic. The controller handles the business logic whereas the data model stores the data and provides methods to access and change the data. You should also name the class appropriately - using the name USCrimeClass could be improved because it's obvious that this is a class, you don't have to use the word "class" in the name. You should also create getter and setter methods for your class member variables rather than allowing direct access. In the code sample below I have created a single getter and setter pair for the population field as an example.
public class USCrimeData {
private int year;
private int population;
private int violentCrime;
private double violentCrimeRate;
private int manslaughter;
private double manslaughterRate;
private int rape;
private double rapeRate;
private int robbery;
private double robberyRate;
private int assault;
private double assaultRate;
private int propertyCrime;
private double propertyCrimeRate;
private int burglary;
private double burglaryRate;
private int larcenyTheft;
private double larcenyTheftRate;
private int vehicleTheft;
private double vehicleTheftRate;
public USCrimeData(String line) {
String[] split = line.split(",");
year = Integer.parseInt(split[0]);
population = Integer.parseInt(split[1]);
violentCrime = Integer.parseInt(split[2]);
violentCrimeRate = Double.parseDouble(split[3]);
manslaughter = Integer.parseInt(split[4]);
manslaughterRate = Double.parseDouble(split[5]);
rape = Integer.parseInt(split[6]);
rapeRate = Double.parseDouble(split[7]);
robbery = Integer.parseInt(split[8]);
robberyRate = Double.parseDouble(split[9]);
assault = Integer.parseInt(split[10]);
assaultRate = Double.parseDouble(split[11]);
propertyCrime = Integer.parseInt(split[12]);
propertyCrimeRate = Double.parseDouble(split[13]);
burglary = Integer.parseInt(split[14]);
burglaryRate = Double.parseDouble(split[15]);
larcenyTheft = Integer.parseInt(split[16]);
larcenyTheftRate = Double.parseDouble(split[17]);
vehicleTheft = Integer.parseInt(split[18]);
vehicleTheftRate = Double.parseDouble(split[19]);
}
public int getPopulation() {
return population;
}
public void setPopulation(int population) {
this.population = population;
}
}
Next let's talk about the controller. This is where the business logic will reside. This is where you will use your data model to arrive at the results you desire. Since you want to determine the percent population change you would use the list of crime data to get the population from the year 1994 (I assume this is the first entry in the list - index 0) and then get the last entry in the list (I assume the final entry is 2013) then calculate the value you want. If these assumptions are not correct or if you want to calculate growth for different years you would want to implement a getYear() method in your data model and then loop through your list of data until you find the object with the year you want.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Controller {
public static void main(String[] args) {
Scanner read = null;
try {
// Replace the "..." below with actual path to your data file.
read = new Scanner(new File("..."));
} catch (FileNotFoundException e) {
System.out.println("The file can't be opened");
System.exit(0);
}
List<USCrimeData> crimeClasses = new ArrayList<>();
while (read.hasNextLine()) {
crimeClasses.add(new USCrimeData(read.nextLine()));
}
read.close();
int initialPopulation = crimeClasses.get(0).getPopulation();
System.out.println("initialPopulation: "+initialPopulation);
int latestPopulation = crimeClasses.get(crimeClasses.size()-1).getPopulation();
System.out.println("latestPopulation: "+latestPopulation);
double percentGrowth = (double)(latestPopulation - initialPopulation) / initialPopulation * 100;
System.out.println("percentGrowth: "+percentGrowth);
}
}
You can iterate list like :
Iterator<USCrimeClass> iterator = crimeClasses.iterator();
while(iterator.hasNext()) {
USCrimeClass currentCrime = iterator.next();
// use currentCrime object to calcuate percent increase/decrease.
}
So the specifications are: Create a BankAccount class. It should contain the following information, stored in instance variables.
I need to have a constructor: BankAccount(String firstName, String lastName, double openingBalance). And a public String firstName(), a public String lastName(), and a public double balance() that return the First Name, last name and balance respectively.
And I have this so far...
public class BankAccountAssignmentPart1 {
private String firstName;
private String lastName;
private double openBalance;
BankAccountAssignmentPart1 (String firstName, String lastName, double openBalance) {
firstName = "Alfred";
lastName = "Jones";
openBalance = 1408;
}
public String firstName() {
return firstName;
}
public String lastName(){
return lastName;
}
public double Balance(){
return openBalance;
}
public static void main(String[] args){
BankAccountAssignmentPart1 m = new BankAccountAssignmentPart1();
System.out.println(m.firstName());
System.out.println(m.lastName());
System.out.println(m.Balance());
}
}
So the problem I have is in the line BankAccountAssignmentPart1 m = new BankAccountAssignmentPart1(); in Eclipse it says that the constructor is undefined and goes on to give suggestions to change the code such as removing the String String double or change the modifier to static which can't happen in instances....So I don't know what to do.
Please Help!
You need to specify parameters when you call your constructor:
BankAccountAssignmentPart1 m = new BankAccountAssignmentPart1("1","2",0);
Otherwise it tries to find BankAccountAssignmentPart1() constructor (with no parameters), which is indeed undefined.
I have been tasked to declare variables in a constructor but I am not sure how I can go about with this. The request states:
"In the constructor, create the Startrek Asteroids Resort given in the Appendix(see below)"
Lucozade,3,10
Fanta,5,2
Sprite,1,100
Coco,1,1
And here is my constructor:
public Asteroid(String nam, int rat, int cap)
{
name = nam;
rating = rat;
capacity = cap;
}
I had considered creating a text file and creating a method to read the data but I'm not sure if this is what they want.
If you want to save the parameters that are passed in you can just have variables that are declared in your class before hand and save them to these variables.
public class Asteroid {
private String name;
private int rat;
private int cap;
public Asteroid(String name, int rat, int cap) {
this.name = name;
this.rat = rat;
this.cap = cap;
}
}
I have following homework about computer store:
There are several class include: Monitor, Case, Mouse, Keyboard.
All the classes have common fields: id, name, price, quantity.
Each class has some unique fields.
All most features are: add, update, delete, find, show list, save, load file
-So, first I will create a class named Product have 4 common fields. Above classes will extends from Product.
-Then, I think I maybe create a ComputerStore class which have a field is items type ArrayList. items stores all objects which are instance of 4 above classes But I'm not sure.
Whether it is reasonable? I need some ideas
Before , I always use ArrayList store for only one class like
List <String> list = new ArrayList<String>();
Now they are multi type. I think it's generic in Java, right??
In case, I want to update for 1 items. I must think about how to change information for them. Ex: mouse for some code, keyboard for another code. Anyway, thank for everybody!
Your approach is 100% reasonable.
You are completely on the right track with "generics". First, check out the official enter link description here.
Next, just think about your data in real world terms, like you are already doing: Monitor, case, mouse, and keyboard are products. Your computer store's inventory is a list of products.
Hint: A list of products.
Put that together with what you learn about generics through that tutorial, and you'll be good to go.
You could use java generic.First create a java collection (ex: List) with supper class type, Product. Now you could add any sub classes (Monitor , Keyboard etc) in your collection (List) that extends of class Product.
public class Product{
}
public class Monitor extends Product{
}
public class Keyboard extends Product{
}
List<Product> products = new ArrayList<Product>();
products.add(new Monitor());
products.add(new Keyboard());
Since you have a superclass (Product), you can have the list's type as Product, i.e.
List<Product> list = new ArrayList<Product>();
list.add(new Mouse());
list.add(new Keyboard());
It will allow you to iterate them and list their name and price without caring for the class, but if you intend to take an item out of the list you'll need to check its actual type (depending on what you do with it).
You can do like below
import java.util.List;
import java.util.ArrayList;
class Test{
public static void main(String... args){
List<MultiObj> multiObjs = new ArrayList();
MultiObj ob = new MultiObj(); multiObjs.add(ob);
ResX xOb = new ResX(); multiObjs.add(xOb);
ResY yOb = new ResY(); multiObjs.add(yOb);
ResZ zOb = new ResZ(); multiObjs.add(zOb);
for (int i = 0; i < multiObjs.size(); i++ ) {
System.out.println(multiObjs.get(i).getV());
}
System.out.println("Waoo its working");
}
}
class MultiObj{
public String greet(){
return "Hello World";
}
public String getV(){
return "Hello World";
}
}
class ResX extends MultiObj{
String x = "ResX";
public String getX(){
return x;
}
public String getV(){
return x;
}
}
class ResY extends MultiObj{
String y = "ResY";
public String getY(){
return y;
}
public String getV(){
return y;
}
}
class ResZ extends MultiObj{
String z = "ResZ";
public String getZ(){
return z;
}
public String getV(){
return z;
}
}
You could do this:
public class Item {
public Item(int id, string name, float price, int amount, int ArrayID) {
if (ArrayID == 1) {
ID1 = id;
name1 = name;
price1 = price;
amount1 = amount;
}
if (ArrayID == 2) {
ID2 = id;
name2 = name;
price2 = price;
amount2 = amount;
}
if (ArrayID == 3) {
ID3 = id;
name3 = name;
price3 = price;
amount3 = amount;
}
if (ArrayID == 4) {
ID4 = id;
name4 = name;
price4 = price;
amount4 = amount;
}
}
//ArrayID #1
public static int ID1;
public static String name1;
public static float price1;
public static int amount1;
//ArrayID #2
public static int ID2;
public static String name2;
public static float price2;
public static int amount2;
//ArrayID #3
public static int ID3;
public static String name3;
public static float price3;
public static int amount3;
//ArrayID #4
public static int ID4;
public static String name4;
public static float price4;
public static int amount4;
public static int[] id = ID1, ID2 ID3, ID4;
//so forth...
}