Update field value in object - java

I need to update a fields value inside one of my object, just update the String. The object is inside of an array. But I will target the object by typing in the objects "regNum" in the parameter.
This is what I tried, I really don't know how to use the set() method when I need to enter the list and the objects specific value.
public boolean doesNotWork( String regNumInput ){
for(int i = 0; i < meterList.size(); i++){
if(regNumInput == meterList.get(i).getRegNum()){
meterList.set(meterList.get(i).getWorkOrNot(), new String ("No"));
}
}
return true;
}
This Is the whole MeterArchive class that stores the meters and have some methods to it.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class MeterArchive
{
// instance variables - replace the example below with your own
ArrayList<Meter> meterList = new ArrayList<Meter>();
public void createClocks(){
Clock clockOne = new Clock("KH001", "Yes", "ClassRoom005", 0.0);
meterList.add(clockOne);
Clock clockTwo = new Clock("KH002", "Yes", "ClassRoom006", 0.0);
meterList.add(clockTwo);
}
public boolean doesNotWork( String regNumInput ){
for(int i = 0; i < meterList.size(); i++){
if(regNumInput == meterList.get(i).getRegNum()){
meterList.set(meterList.get(i).getWorkOrNot(), new String ("No"));
}
}
return true;
}
public void showAllMeter(){
for(Meter meter : meterList){
System.out.println(meter);
}
}
}
This is the clock class that has specific clock values that you can add.
public class Clock extends Meter
{
/**
* Constructor for objects of class Clock
*/
public Clock(String regNum, String workOrNot, String location, double minTime)
{
// initialise instance variables
super(regNum, workOrNot, location);
setMinTime(minTime);
}
//MINNIMUM TIME
public void setMinTime(double minTime){
this.minTime = minTime;
}
public double getMinTime(){
return minTime;
}
//EQUALS METHOD --- NOT SURE WHAT IT SHOULD DO... YET!
public boolean equals (Clock other){
return location.equals(other.location);
}
public String toString(){
String retur = super.toString() + "regNum: " + regNum +
"Does it work: " + workOrNot +
"Location: " + location +
"Min time value: " + minTime;
return retur;
}
}
This is the super class that has more general input for the different meters.
public class Meter
{
public String regNum;
public String workOrNot;
public String location;
/**
* Constructor for objects of class Clock
*/
public Meter(String regNum, String workOrNot, String location)
{
// initialise instance variables
setRegNum(regNum);
setWorkOrNot(workOrNot);
setLocation(location);
}
//REGISTRATION NUMBER
public void setRegNum(String regNum){
this.regNum = regNum;
}
public String getRegNum(){
return regNum;
}
//WORK OR NOT
public void setWorkOrNot(String workOrNot){
this.workOrNot = workOrNot;
}
public String getWorkOrNot(){
return workOrNot;
}
//LOCATION
public void setLocation(String location){
this.location = location;
}
public String getLocation(){
return location;
}
}
So in the MeterArchive class I want to change the field value "workOrNot" from whatever it is (most likely "Yes") to "No". I found out that set() is usually the way to go, but in this program I want the user to add the specific "regNum" and then the method will change to String inside the "workOrNot" field to "No". As I said earlier I dont know how to target the specific field inside the object. Can someone explain how to do this?

You need to use setter method setWorkOrNot() to update field workOrNot on the desired Meter object.
Use the below code:
public boolean doesNotWork( String regNumInput ){
for(int i = 0; i < meterList.size(); i++){
if(regNumInput.equals(meterList.get(i).getRegNum())){
meterList.get(i).setWorkOrNot("No");
}
}
return true;
}

Related

I have created two classes, when I entered negative quantity and negative price it does not set to be "0" and "0.0"

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

get several method's return values from a class in one statement

Item searchByPattern(String pat)
{
for(Iterator iter = items.iterator(); iter.hasNext(); )
{
Item item = (Item)iter.next();
if ((xxxxxxxxxxxx).matches(".*"+pat+".*"))
{
return item;
}
}
}
The above code is part of a class from my java program
public class Item
{
private String title;
private int playingTime;
private boolean gotIt;
private String comment;
/**
* Initialise the fields of the item.
*/
public Item(String theTitle, int time)
{
title = theTitle;
playingTime = time;
gotIt = true;
comment = "";
}
public String getTitle() {
return title;
}
/**
* Enter a comment for this item.
*/
public void setComment(String comment)
{
this.comment = comment;
}
/**
* Return the comment for this item.
*/
public String getComment()
{
return comment;
}
/**
* Set the flag indicating whether we own this item.
*/
public void setOwn(boolean ownIt)
{
gotIt = ownIt;
}
/**
* Return information whether we own a copy of this item.
*/
public boolean getOwn()
{
return gotIt;
}
public int getPlayingTime()
{
return playingTime;
}
/**
* Print details about this item to the text terminal.
*/
public void print()
{
System.out.println("Title: " + title);
if(gotIt) {
System.out.println("Got it: Yes");
} else {
System.out.println("Got it: No");
}
System.out.println("Playing time: " + playingTime);
System.out.println("Comment: " + comment);
}
}
I want to access all the methods that return values from class Item and once it matches the statement in Item searchByPattern, it will return the object.
I knew that I can do it by or operator like item.getTitle().matches(".*"+pat+".*") ||item.getComment().matches(".*"+pat+".*")||.......
but is it possible to get the same result by using a method in (xxxxxxxxxx)?
This isn't directly possible to do, however there are a few things you can try (from easiest to hard):
Just check all String type methods yourself in your code.
Add a special method in Item that does the match so Item class can decide itself when it matches. Here again you will need to make check all Strings manually.
You could add a method to Item that returns all methods that return a String as functions:
Code:
List<Supplier<String>> getAllStringMethods() {
return Arrays.asList(this::getComment, this::getTitle);
}
You can then use that to check all Strings one at a time by doing:
boolean match = item.getAllStrings().stream()
.map(Supplier::get)
.anyMatch(s -> s.matches("pattern"));
You can use Reflection to inspect the Item.class to find all methods that take no parameters and return a String, and then invoke them one by one. This is complicated and slow, and beyond the scope of this answer to explain further.

Fix override mistake

I try to run a programm but i get those four errors.
TestCusomer.java:25: error: toString() in Invoice cannot override toString() in Object (same thing at line 49)
and
line 59 cannot find symbol . myCustomer.setTrn(112233778)
line 60 cannot find symbol . myCustomer.setPersentage(150)
My programm is the following:
class Invoice
{
int trn; //TAX REGISTRATION NUMBER
int persentage;
public Invoice{}
public int setTrn(int trn){
this.trn = trn;
}
public int getTrn(){
return trn;
}
public void setPersentage(int persentage){
this.persentage = persentage;
}
public int getPersentage(){
return persentage;
}
String toString(){
System.out.println(trn+" : "+persentage);
}
}
class Customer{
int trn;
int charging= 0;
public Customer(int trn){
this.trn = trn;
}
public int charge(int amount){
charging = charging + amount;
}
public int charge(int amount , int trn){
if (this.trn == trn){
charging = charging + amount;
}
}
String toString(){
System.out.println(trn+" : "+charging);
}
}
class TestCustomer
{
public static void main(String[] args){
Customer myCustomer = new Customer(112233778);
myCustomer.charge(100);
myCustomer.setTrn(112233778);
myCustomer.setPersentage(150);
System.out.println(myCustomer);
}
}
few things,
You need to declare the toString method public
You need to return a String in your toString methods
I strongly suggest you add the #Override notation when you override a method to ensure that you actually override the method
The cannot find symbol... happen because those methods are not defined in Customer, you have those in Invoice
Your toString() methods need to return String objects. You are outputting a string in them but not returning a string. Also make them public.
For example, your toString() method for the Invoice class should be:
public String toString()
{
return trn + " : " + persentage;
}
And for your second problem (cannot find symbols), those methods are in the Invoice class and not in the Customer class so they cannot be called on a Customer object.

Update a single variable of a class in an ArrayList of class in java

I have a class Components:
public class Components {
int numberOfNets;
String nameOfComp;
String nameOfCompPart;
int numOfPin;
public components(int i, String compName, String partName, int pin) {
this.numberOfNets = i;
this.nameOfComp = compName;
this.nameOfCompPart = partName;
this.numOfPin = pin;
}
}
Inside another class I created an arraylist of Components class:
List<Components> compList = new ArrayList<Components>();
Later in the code, I am adding the elements in List in this way:
compList.add(new Components(0,compName,partName,0));
See, here numberOfNets and numOfPin variables in Components class are initiated with 0 values. But these values are getting calculated/incremented in a later part of code and hence I need to update the new values of only these two variables in each list element. Now from ArrayList doc I get the idea of updating a list element using its index by set operation. But I am confused how to set/update a particular variable of a class in an ArrayList of a class. I need to update only these two mentioned variables, not all of the four variables in Components class. Is there any way to do that?
You should add getter/setter to your component class so that outer class can update component's members
public class Components {
private int numberOfNets;
private String nameOfComp;
private String nameOfCompPart;
private int numOfPin;
public components(int i, String compName, String partName, int pin) {
setNumberOfNets(i);
setNameOfComp(compName);
setNameOfCompPart(partName);
setNumOfPin(pin);
}
public void setNumberOfNets(int numberOfNets) {
this.numberOfNets = numberOfNets;
}
// Similarly other getter and setters
}
You can now modify any data by using following code because get() will return reference to original object so modifying this object will update in ArrayList
compList.get(0).setNumberOfNets(newNumberOfNets);
Example code.
public class Main {
public static void main(String[] args) {
List<Components> compList = new ArrayList<Components>();
compList.add(new Components(0, "compName", "partName", 0));
System.out.println(compList.get(0).toString());
compList.get(0).numberOfNets = 3;
compList.get(0).numOfPin = 3;
System.out.println(compList.get(0).toString());
}
}
Your class.
public class Components {
int numberOfNets;
String nameOfComp;
String nameOfCompPart;
int numOfPin;
public Components(int i, String compName, String partName, int pin) {
this.numberOfNets = i;
this.nameOfComp = compName;
this.nameOfCompPart = partName;
this.numOfPin = pin;
}
public String toString() {
return this.numberOfNets + " " + nameOfComp + " " + nameOfCompPart
+ " " + numOfPin;
}
}
The output:
0 compName partName 0
3 compName partName 3

Using Arrays.binarySearch on an array of Objects and looking for a String within the object

OK so I have the following Object class:
public class IntoleranceFood implements Comparable<IntoleranceFood>{
private int scoreInt;
public String foodName;
public IntoleranceFood(String food, int score) {
super();
this.foodName = food;
this.scoreInt = score;
}
//getters and setters
public String getFood() {
return foodName;
}
public void setFood(String food) {
this.foodName = food;
}
public int getScore() {
return scoreInt;
}
public void setScore(int score) {
this.scoreInt = score;
}
#Override
public String toString() {
return "Intolerance Food [Name=" + foodName + ", Score=" + scoreInt + "]";
}
#Override
public int compareTo(IntoleranceFood arg0) {
return toString().compareTo(arg0.toString());
}
}
And then in my Activity I have created an array for these objects to go into, and filled up the array with "IntoleranceFood" Objects:
int numFoodItemTypes = db.intoleranceFoodItemTypesTotal();
IntoleranceFood[] foodArray = new IntoleranceFood[numFoodItemTypes];
Cursor cAllFoodTypes = db.intoleranceFoodTypesList();
int foodItem = 0;
do{
foodArray[foodItem] = new IntoleranceFood(cAllFoodTypes.getString(0), 0);
foodItem++;
}while(cAllFoodTypes.moveToNext());
I managed to sort the array by implementing Comparable and the compareTo method in my Object class:
Arrays.sort(foodArray);
But I want to then search the array using binary search, and look for the position in the array where a certain Object with a specific food name (String) resides. But I dont know how to get the following code working, and specifically in terms of:
-binarySearch(Object[] array, Object value)
I don't know what to put in "Object value" so this:
Arrays.binarySearch(foodArray, "Cereal");
Is clearly wrong! But I'm not sure how to search the Object array for an Object containing the String food name "Cereal".
Thanks.
Yes so after the very useful reply below, I realsied what I need to be doing is:
IntoleranceFood searchOb = new IntoleranceFood("Cereal",0);
int searchIndex = Arrays.binarySearch(foodArray, searchOb);
And that works!
In my opinion your mistake is
Arrays.binarySearch(foodArray, "Cereal");
because "Cereal" is not the Object you are looking for and your array doesnt contain this object. The second parameter should be an instance of the IntoleranceFood class and "Cereal" is just a property of that class.
For your problem i would use a HashMap or another Map who fits your problem best!
Maybe this article will help you : How to sort a HashMap in Java

Categories

Resources