Setter which has class instance is this possible? - java

private int Li_WtVal;
List <Integer> ValueList = new ArrayList<Integer>();
CsReader csReader = new CsReader();
public void setLi_WtVal(int li_WtVal) {
ValueList = csReader.GetAllcsValues();
li_WtVal = ValueList.get(0);
}
public int getLi_WtVal() {
return Li_WtVal;
}
}
And I have a while loop inside it I'm calling the setter and getter but evrytime It returns 0.
public int CtrlWeight(String CodeLine) {
Scanner scanner = new Scanner(CodeLine);
int Li_Wtcs = 0;
while (scanner.hasNext()) {
token1 = scanner.next();
if (token1.contains("if")){
setLi_WtVal(Li_WtVal);
Li_Wtcs = Li_Wtcs + getLi_WtVal() ;
}
}
Can setter has other class instances and object ref inside it?

You set the value to the parameter not to the property:
public void setLi_WtVal(int li_WtVal) {
ValueList = csReader.GetAllcsValues();
Li_WtVal= ValueList.get(0);
}
public int getLi_WtVal() {
return Li_WtVal;
I think the reason is because your teriable naming of the variables.
Also Looks like your code doesn't make much.

Related

Getter, Setter & NullPointerException

Firstly, I am trying to assign the value for array I initialized locally. The class type of the array is stored inside another class and the variable is private so I am using getter and setter to set the value. But it showing "Exception in thread "main" java.lang.NullPointerException at room.Test.main(Test.java:26)", below is my code for the test.java:
public class Test {
public static void main(String[] args) {
Room[] room = new Room[72];
Integer i = 0;
try {
File RoomTxt = new File("Room.txt");
Scanner read = new Scanner(RoomTxt);
while (read.hasNextLine()) {
room[i].setRoomID(read.next());
room[i].setRoomType(read.next() + " " + read.next());
room[i].setFloor(read.nextInt());
room[i].setRoomStatus(read.nextInt());
read.nextLine();
i++;
}
read.close();
} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
Below is the class I used to store the Room type:
public class Room {
private String roomID;
private String roomType;
private Integer floor;
private Integer roomStatus;
//Setter
public void setRoomID(String roomID) {
this.roomID = roomID;
}
public void setRoomType(String roomType) {
this.roomType = roomType;
}
public void setFloor(Integer floor) {
this.floor = floor;
}
public void setRoomStatus(Integer roomStatus) {
this.roomStatus = roomStatus;
}
//Getter
public String getRoomID() {
return this.roomID;
}
public String getRoomType() {
return this.roomType;
}
public Integer getFloor() {
return this.floor;
}
public Integer getRoomStatus() {
return this.roomStatus;
}
}
PS. The records stored inside my Room.txt is like
RS11 Single Room 1 1
RD12 Double Room 1 0
You need to write room[I] = new Room(); before you start calling its setters.
Initializing an array only assigns the array reference to a new array object of the given type and allocates the array memory space.
Array elements reference is initialized to default element type values i.e.:
null for Object and String types
0 for numeric values
false for boolean ones
Hence all the room[i] elements refers to null.
You should be assigning element values before calling any method over these (including setters):
public class Test {
public static void main(String[] args) {
Room[] room = new Room[72];
Integer i = 0;
try {
File RoomTxt = new File("Room.txt");
Scanner read = new Scanner(RoomTxt);
while (read.hasNextLine()) {
room[I] = new Room();
// set the field values
}
read.close();
} catch (FileNotFoundException e) {
// ...
}
}

Change element in arraylist to true from user input

package issue;
import java.util.*;
public class Issue {
private static ArrayList<Object> list = new ArrayList<Object>();
public static ArrayList<Object> getArrayStringList(){
for (Object o : list)
System.out.println("["+o+"]");
return list;
}
public static void removeIssue(){
for (int i = 0; i<list.size(); i++){;
System.out.println("["+"["+i+"] "+list.get(i)+"]");
}
Scanner scan = new Scanner(System.in);
System.out.println("Which one would you like to mark as solved?");
int choice = scan.nextInt();
##This is where my problem is ##
Object issue = list.get(choice);
issue
}
public static void addIssue(){
Scanner scan = new Scanner(System.in);
String text= scan.nextLine();
newIssue issue = new newIssue(text);
list.add(issue);
}
}
I want the user input to choose the appropriate element in the ArrayList and then set it to true using the newIssue class. But I can't figure out how to
package issue;
public class newIssue {
public String issueText;
public boolean returned = false;
public newIssue(String issueText){
this.issueText = issueText;
}
public String toString(){
return issueText + returned;
}
}
Try this.
if(list.size() > 0 && choice <= list.size()-1) {
newIssue issue = (newIssue)list.get(choice);
issue.returned = true;
System.out.println("newIssue = "+ issue.toString())
}
Create list as:
private static ArrayList<newIssue> list = new ArrayList<>();
Then you can do:
newIssue issue = list.get(choice);
issue.returned = true;

Filtering an ArrayList<MyClass> on the basis of a MyClass.MyString and summing up a MyClass.MyCount

I've a Bean Class MyClass as
public class MyClass {
String myString;
int myCount;
public MyClass() {
}
public MyClass(String myString, int myCount) {
super();
this.myString = myString;
this.myCount = myCount;
}
public String getMyString() {
return myString;
}
public void setMyString(String myString) {
this.myString = myString;
}
public int getMyCount() {
return myCount;
}
public void setMyCount(int myCount) {
this.myCount = myCount;
}}
I have an ArrayList as
MyClass obj1 = new MyClass("1-ABC_2-PQR_1-PQR_1-DEF", 4);
MyClass obj2 = new MyClass("1-ABC_2-PQR_3-XYZ_1-PQR_1-DEF", 12);
MyClass obj3 = new MyClass("1-ABC_1-PQR_1-DEF", 3);
MyClass obj4 = new MyClass("3-ABC_2-PQR_1-DEF", 3);
ArrayList<MyClass> rawList = new ArrayList<MyClass>();
rawList.add(obj1); rawList.add(obj2); rawList.add(obj3); rawList.add(obj4);
For the whole ArrayList I am picking out the MyClass.myString iteratively and based on a selection criteria tailoring them and setting them back to their respective objects. After this, I need to create a New ArrayList in which if myString for one object matches that of the other then I need to add the MyClass.myCount for them both and delete of one of the objects.
For example, in the values I've taken, if after tailoring obj1.getMyString() matches obj3.getMyString() as 1-ABC_1-PQR_1-DEF then I need to add obj1.getMyCount() and obj3.getMyCount() and save only one of them in the new ArrayList.
I am doing this in the following way, but I am hoping to get a efficient and fail proof way to do this.
int j = 0;
if (rawList.size() > 0)
list.add(rawList.get(0));
for (int i = 1; i < rawList.size(); i++) {
if (rawList.get(i).getMyString()
.equals(list.get(j).getMyString())) {
list.get(j).setMyCount(
list.get(j).getMyCount()
+ rawList.get(i)
.getMyCount());
} else {
j++;
list.add(rawList.get(i));
}
}
I guess you could use a map:
Map<String,MyClass> map = new LinkedHashMap<>();
for (MyClass obj: rawList) {
MyClass other = map.get(obj.getMyString());
if (other != null) {
other.setMyCount(other.getMyCount() + obj.getMyCount());
} else {
map.put(obj.getMyString(), obj);
}
}
List<MyClass> list = new ArrayList<>(map.values());

Passing dynamic primitive type (int) to a method

In Java, the output of s is 0. I do not understand why and would it be possible to somehow get the correct value of s (1000 here)?
public static void main(String args) {
int s = 0;
List<Integer> list = getList(s);
System.out.println("s = " + s);
}
public static List<Integer> getList(int s) {
List<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < 1000; i++) {
list.add(i); s++;
}
}
In C# there were out descriptors to indicate that the variable is going to change if I'm not mistaken..
I'm not going to get the list.size() in general!
In Java, all method arguments are passed by value, i.e. copy. So, changes to the copy are not visible to the caller.
To address your second question, you can just use list.size() on the caller side.
I see two ways
1) Make 's' as static variable and move it to class level
2) Create class with getter/setter for list and int and return the object for getList call
public static MyWrapperObj getList(int s) {
......
return wrapperObj
}
class MyWrapperObj
{
private List<Integer>;
private countS;
....
//getter/setters.
}
Java doesn't allow for passing parameters by reference - but you could wrap it in an object like this:
class IntHolder {
private int s;
IntHolder(int s){
this.s = s;
}
public void setS(int s){
this.s = s;
}
public int getS(){
return s;
}
public void increment(){
s++;
}
}
class Test{
public static void main(String[] args) {
IntHolder s = new IntHolder(0);
List<Integer> list = getList(s);
System.out.println("s = " + s.getS());
}
public static List<Integer> getList(IntHolder s) {
List<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < 1000; i++) {
list.add(i); s.increment();
}
return list;
}
}
In java, arguments passed to methods are passed by value.. you will need to make s a global or instance variable in order to modify it in other methods. This is just the way java works. e.g.
public class Test{
private int s;
public Test(){
s=0;
increment();
//print now will be 1000.
}
private void increment(){
s = 1000;
}
}

static factory builder trouble

Needing to create an unspecified number of objects, I tried to create a builder that do that. All was well until I realized that my builder creates all objects with their properties having the same values.
So when I call the builder:
ValidationHelper v = new ValidationHelper.HelperBuilder()
.addHelper("ICAO Identifier", icaoIdentifier, rulesICAO)
.addHelper("Long Name", longName, rulesLongName)
.build();
... I'll have 2 objects and their properties will have values of the last object the builder was asked to create.
To start with, is factory builder the prudent approach to this? Secondly, is my builder salvageable?
Builder:
public class ValidationHelper {
private static ArrayList<HelperBuilder> validatorHelpers = new ArrayList();
public static class HelperBuilder {
private String txtFieldName;
private String txtFieldValue;
private List<Integer> valCodes = new ArrayList<Integer>();
private ArrayList<HelperBuilder> innerValidatorHelpers = new ArrayList<HelperBuilder>();
public HelperBuilder() {}
public final HelperBuilder addHelper(String txtFieldName, String txtFieldValue, int[] validationCodes) {
this.txtFieldName = txtFieldName;
this.txtFieldValue = txtFieldValue;
for( int i = 0; i < validationCodes.length; i++ ){
getValCodes().add((Integer) validationCodes[i]);
}
innerValidatorHelpers.add(this);
return this;
}
public final ValidationHelper build() {
return new ValidationHelper(this);
}
public String getTxtFieldName() {
return txtFieldName;
}
public String getTxtFieldValue() {
return txtFieldValue;
}
public List<Integer> getValCodes() {
return valCodes;
}
}//end HelperBuilder
private ValidationHelper(HelperBuilder helperBuilder) {
validatorHelpers = helperBuilder.innerValidatorHelpers;
}
public void setHelpers(ArrayList validatorHelpers) {
validatorHelpers = validatorHelpers;
}
public ArrayList getHelpers() {
return validatorHelpers;
}
}
EDIT/FIXED:
So for what it's worth, here's the revised builder. It needed another constructor that could properly initialize an instance of what it's supposed to build.
public class ValidationHelper {
private static ArrayList<HelperBuilder> validatorHelpers = new ArrayList();
public static class HelperBuilder {
private String txtFieldName;
private String txtFieldValue;
private List<Integer> valCodes = new ArrayList<Integer>();
private ArrayList<HelperBuilder> innerValidatorHelpers = new ArrayList<HelperBuilder>();
public HelperBuilder() {}
public HelperBuilder(String txtFieldName, String txtFieldValue, int[] validationCodes) {
this.txtFieldName = txtFieldName;
this.txtFieldValue = txtFieldValue;
for (int i = 0; i < validationCodes.length; i++) {
valCodes.add((Integer) validationCodes[i]);
}
}
public final HelperBuilder addHelper(String txtFieldName, String txtFieldValue, int[] validationCodes) {
innerValidatorHelpers.add( new HelperBuilder(txtFieldName, txtFieldValue, validationCodes) );
return this;
}
public final ValidationHelper build() {
return new ValidationHelper(this);
}
public String getTxtFieldName() {
return txtFieldName;
}
public String getTxtFieldValue() {
return txtFieldValue;
}
public List getValCodes() {
return valCodes;
}
}//end HelperBuilder
private ValidationHelper(HelperBuilder helperBuilder) {
validatorHelpers = helperBuilder.innerValidatorHelpers;
}
public ArrayList getHelpers() {
return validatorHelpers;
}
}
Each time you just overwrite the values in
private String txtFieldName;
private String txtFieldValue;
and the last one winns. So you create only 1 HelperInstance here
ValidationHelper v = new ValidationHelper.HelperBuilder()
and the fields name and value are overwritten each time you call addHelper(). But you need to create an instance for each "configuration". So addHelper should create a new Instance and add it into
private ArrayList<HelperBuilder> innerValidatorHelpers = ...;
If you want to build objects with different values you have to either
alter the builder between creating the objects so it will build something different.
instruct the builder to change the values automatically e.g. use a counter, or filename based on the date, or provide a list of values.

Categories

Resources