flag always returns 0 to another class - java

import java.util.ArrayList;
import java.util.List;
public class QueryParser {
QueryParameter queryParameter = new QueryParameter();
public static int flag = 0;
public QueryParameter parseQuery(String queryString) {
queryParameter.setGroupByFields(getGroupByFields(queryString));
queryParameter.setAggregateFunctions(getAggregateFunctions(queryString));
return queryParameter;
}
private List<AggregateFunction> getAggregateFunctions(String queryString) {
List<AggregateFunction> aggregateFunctionList = null;
AggregateFunction aggregateFunction;
if (queryString.contains("count") || queryString.contains("sum") || queryString.contains("min")
|| queryString.contains("max") || queryString.contains("avg")) {
flag = flag + 1;
}
return aggregateFunctionList;
}
private List<String> getGroupByFields(String queryString) {
List<String> groupByFieldList = null;
if (queryString.contains("group by")) {
flag = flag+2;
return groupByFieldList;
}
}
this is my code, now i am accessing flag from another class using
int i = queryParser.flag,
but it always returns 0. How to declare flag so that it will hold the values from the inner methods and also can be accessed from other classes. /* if anyone need more details please ask i'll add more details, and what more should i write,my main doubt is only to know how i can utilise my flag in another class, thank you for being patient*/

An MCVE could look like this:
public class QueryParser {
public static int flag = 0;
void getAggregateFunctions(String queryString) {
if (queryString.contains("count") || queryString.contains("sum") || queryString.contains("min")
|| queryString.contains("max") || queryString.contains("avg")) {
flag = flag + 1;
}
}
void getGroupByFields(String queryString) {
if (queryString.contains("group by")) {
flag = flag+2;
}
}
public static void main(String[] args) {
QueryParser q = new QueryParser();
System.out.println(flag); //prints out 0
q.getAggregateFunctions("max"); System.out.println(flag); //prints out 1
q.getAggregateFunctions("aString"); System.out.println(flag); //prints out 1
q.getAggregateFunctions("avgNumber"); System.out.println(flag); //prints out 2
q.getGroupByFields("group by"); System.out.println(flag); //prints out 4
}
}
It helps those who want to help you, and far more important: it is a great debugging tool.
Making on helps you isolate the problem, and focus on it.
Like in this case: you can see that the problem is not in the declaration of flag, nor changing its value, but maybe with the input values.

Related

Why does the counter inside if statement not work?

Hello friends I am trying to build a class Car for a project. There are many methods inside the following code as well as an if statement that I am having trouble building, consider the following code
public class Car extends Vehicle {
private boolean isDriving;
private final int horsepower;
private boolean needsMaintenance = false;
private int tripsSinceMaintenance = 0;
Car() {
super();
this.horsepower = 0;
this.isDriving = false;
this.needsMaintenance = false;
this.tripsSinceMaintenance = 0;
}
public int getHorsepower() {
return this.horsepower;
}
public boolean getDrive() {
return this.isDriving;
}
public boolean getMain() {
return this.needsMaintenance;
}
public int getTRIP() {
return this.tripsSinceMaintenance;
}
public void drive() {
this.isDriving = true;
}
public void stop() {
this.isDriving = false;
}
public void repair() {
this.needsMaintenance = false;
this.tripsSinceMaintenance = 0;
}
/**
* #param args
*/
public static void main(String[] args) {
Car auto = new Car();
auto.drive();
auto.stop();
if (auto.isDriving == true) {
if (auto.isDriving == false)
auto.tripsSinceMaintenance = auto.tripsSinceMaintenance + 1;
}
if (auto.tripsSinceMaintenance > 100)
auto.needsMaintenance = true;
System.out.println("Drive: " + auto.getDrive());
System.out.println("trip: " + auto.getTRIP());
}
}
What I want to do is whenever the attribute isDriving goes from true to false the tripsSinceMaintenance should increase by 1 and also when tripsSinceMaintenanceis greater than 100,needsMaintenanceshould becometrue`.
here I expected trips to be 1 but the result is the following:
Drive: false
trip: 0
I have tried this.isDriving==true; and basicaly wherever auto is inside the if statement I put this but the following error appears
non static variable cannot be referenced from static context
help me please!
What i want to do is whenever the attribute isDriving goes from true to false the tripsSinceMaintenance should increase by 1 and also when tripsSinceMaintenance is greater than 100 needsMaintenance should become true
Do this inside stop() method
fun stop() {
if (isDriving) {
tripsSinceMaintenance++;
}
if (tripsSinceMaintenance > 100) {
needsMaintenance = true;
}
isDriving = false;
}
You don't need to put == true inside of an if statement, it's doing that already,
if(someCondition) { // <-- this executes if the condition is true.
Also, you have conflicting conditions nested, meaning...
if (thisIsTrue) {
if (!thisIsTrue) {
// <--- unreachable statements
where you should be incrementing your variable is where you're setting "isDriving = true"
So your code would look like this:
public void drive() {
this.isDriving=true;
auto.tripsSinceMaintenance++;
}

Problems creating an object using a class and then putting it on a array

So I'm trying to do a User class and then trying to do an array for it
however every time I create a student it don't add to the array.
I tried to change names etc but its really a problem in code.
public class UsersList {
User student;
User[] studentList = new User[49];
public UsersList() {
}
public void createUser(int userNumber) {
String numberToString = String.valueOf(userNumber);
if (numberToString.length() == 9) {
for (int i = 0; i < 49; i++) {
if (studentList[i] == null) {
studentList[i] = new User(userNumber);
}
}
}
}
}
public class User {
public int userNumber;
private boolean isolation;
private String state;
public User(int number) {
userNumber = number;
isolation = false;
}
}
If someone can help me I would be greatful.
I added the following simple test method to UsersList class to demonstrate that the code is fine and you need to provide appropriate userNumber value when calling createUser method:
public static void main(String[] args) {
UsersList list = new UsersList();
int userNumber = 1;
list.createUser(userNumber); // insufficient length
System.out.printf("all nulls for %d? %s%n", userNumber, Arrays.stream(list.studentList).filter(Objects::isNull).count() == list.studentList.length);
userNumber = 123_456_789;
list.createUser(userNumber); // length of the number is 9
System.out.printf("no nulls for %d? %s%n", userNumber, Arrays.stream(list.studentList).filter(Objects::nonNull).count() == list.studentList.length);
}
Output:
all nulls for 1? true
no nulls for 123456789? true
However, you may want also to initialize the instance variable student.

Trying to assign value to array elements and return it in another class to work with but not working

I am having diffculty with trying to assign value to array elements based on a userinput and checking the array element's value in another class. When I do that I get null and I am not sure why and how to fix it.
I have no expereince with java, just started learning it and doing it as part of uni course.
Any help is appreciated and thank you.
Class 1
public class ErrorHandling {
String[] errorMessage = new String[4];
public void inputCheck() {
UserInterface input = new UserInterface();
int[] checkUserInput = input.getInput();
if (checkUserInput[0] < 20 || checkUserInput[0] > 80) {
errorMessage[0] = "Hello";
}
if (!(checkUserInput[1] <= 10 && checkUserInput[1] % 2 == 0)) {
errorMessage[2] = "Hey";
}
}
public String[] getError() {
return errorMessage;
}
}
Class 2
public class MainProgram {
public static void main(String[] args) {
UserInterface input = new UserInterface();
input.askZigZag();
ErrorHandling checkError = new ErrorHandling();
String check[] = checkError.getError();
if (check[0] == ("Hello")) {
System.out.println("yh");
}
}
}
I think you're confusing your method calls a bit. In class 2, you have a line:
String check[] = input.getError();
That should probably be:
String check[] = checkError.getError();
As the getError() method is in your first class (ErrorHandling) and not the UserInterface class.
Also, you assign Hello to errorMessage[0] and not hey, so that might be failing in your last few lines in class 2.
If you're just starting out with Java I recommend reading up on Class Structure to understand this (as well as Arrays).
**EDIT
String comparison in Java doesn't work using the == operator. As they are objects and not primitive data types, you must use .equals.
check[0].equals("Hello")
Invoke checkError.inputCheck() in the main program otherwise errorMessage will not get initialized.
Some tweaks in your code that will help to execute:
Class 1
public class ErrorHandling {
String[] errorMessage = new String[4];
public void inputCheck() {
UserInterface input = new UserInterface();
int[] checkUserInput = input.getInput();
// If you want to use askZigZag... use it somewhere inside this function
// since you have already declared the object of UserInterface.
if (checkUserInput[0] < 20 || checkUserInput[0] > 80) {
errorMessage[0] = "Hello";
}
if (!(checkUserInput[1] <= 10 && checkUserInput[1] % 2 == 0)) {
errorMessage[2] = "Hey";
}
}
public String[] getError() {
return errorMessage;
}
}
Class 2
public class MainProgram {
public static void main(String[] args) {
// UserInterface input = new UserInterface();
// input.askZigZag();
ErrorHandling checkError = new ErrorHandling();
checkError.inputCheck();
String check[] = checkError.getError();
if (check[0].equals("Hello")) {
System.out.println("yh");
}
}
}

Round robin a list in multithreaded environment

I wrote a method which behaves as a round robin. Everytime someone calls it, it returns an integer from a list. When the end of the list is reached, it starts serving from the beginning.
I call this method from a stateless session bean.
The method is written in a util class like below
public final class MyUtil {
private static int index;
private MyUtil() {}
public synchronized static int getNextInt() {
Properties p = DBconfigModule.getProperties("key");
List<String> list = Arrays.asList(((String) p.get("key")).split(","));
try {
if(index>=list.size()) {
index = 0;
next = list.get(0);
index++;
} else {
next = list.get(index):
index++;
}
} catch(final Exception e) {
// log
index = 0;
next = list.get(0);
index++;
}
return Integer.parseInt(next);
}
#Stateless
public class Usage {
public int getNextInt() {
return MyUtil.getNextInt();
}
}
I am not sure how far what i have written is right and will work.
Can anyone tell me is this right and suggest me if it can be improved?
I do not want to use any 3pp libraries for this.
Thank you.
Your code is correct only if list is never changed or if access to list is synchronized with the same monitor.
Imagine what happens when the following code is executed:
Thread 1 Thread 2
------------------- -----------------------
// index = 2
// list.size() = 3
if (index == list.size()) {
// Removes first element
// now list.size() = 2
list.remove(0);
} else {
// Will throw an exception
// Because now list has size 2
// and the third element (index 2)
// doesn't exists
next = list.get(index);
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class Counter {
private ReadWriteLock listLock = new ReentrantReadWriteLock();
private List<Integer> list = new ArrayList<>();
private AtomicInteger indexCounter = new AtomicInteger(0);
Integer getNextInt() {
Lock readLock = listLock.readLock();
try {
if(list==null || list.size() == 0) {
throw new IllegalStateException("Call setList() with some values first.");
}
int index = indexCounter.incrementAndGet() % list.size();
return list.get(index);
} finally {
readLock.unlock();
}
}
void setList(List<Integer> newList) {
Lock writeLock = listLock.writeLock();
try {
this.list = newList;
} finally {
writeLock.unlock();
}
}
}
Something like that, very roughly.

Java J-unit tests

I am testing a class that was implemented from an interface.
In my test class, I have created objects (Humains) that have a name and bank account value.
One of my methods to test takes an arrayList and compares with another list and if the person already exists, the amount will be added.
Code is something like that:
TEST CLASS
HumainImpl<Humain> humain = new HumainImpl<Humain>();
private Humain h1 = new Humain("AAA" , 2200);
private Humain h2 = new Humain("DDD" , 500);
#Test
public void testAddAmount(){
List<Humain> testing = new ArrayList<Humain>();
testing.add(h1);
testing.add(h2);
humain.placeList(testing);
}
the placeList(testing) method is in the HumainImpl class which calls another method in the Humain class that does the addition.
In the HumainImpl class there is also a list called implList.
Once this method placeList is called, the numbers for h1 and h2 in the test class are changing.
What I want, is that only the number for the implList to change.
Is it something normal that when adding up numbers or making changes while passing the h1 and h2 as parameter they will get effected ?
I have tried too many ways and I don't get it. I tried going through the list passed as a parameter copy the element in that list into another attribut and do the addition but it didn't help.
This works fine when I test another similar method that takes an element as a attribut, place(h1).
Test Class:
HumainImpl<Humain> humain = new HumainImpl<Humain>();
private Humain h1 = new Humain("AAA" , 2200);
private Humain h2 = new Humain("DDD" , 500);
#Test
public void testAddAmount(){
List<Humain> testing = new ArrayList<Humain>();
testing.add(h1);
testing.add(h2);
humain.placer(testing); //placer(testing) is the method placer with a list parameter
}
HumainImpl:
private boolean existe(T elt){
boolean result = false;
index = uneListe.indexOf(elt);
if(index >= 0){
result = true;
}
return result;
}
#Override
public boolean placer(T elt) {
boolean result = false;
boolean found = false;
int i = -1;
int nbExemple;
if(elt != null){
boolean existe = existe(elt);
nbExemple = nbExemplaires(elt);
if(uneListe.size() > 0 && existe){
while(!found && i < uneListe.size()){
i++;
if(elt.equals(uneListe.get(i))){
found = true;
}
}
T element = uneListe.get(i);
nbExemple = element.retournerNbExemplaires();
elt.additionner(nbExemple);
result = false;
} else if(!existe && nbExemple >= 1 &&
uneListe.size() < nbPlacesMaximum) {
uneListe.add(elt);
result = true;
}
}
return result;
}
#Override
public void placer(List<T> liste) {
iterateur(liste);
while(liste != null && liste.size() > 0 && itList.hasNext()){
placer(itList.next());
}
}
In the class Humain:
#Override
public void additionner(int nbExemplaires) {
this.nbExemplaires += nbExemplaires;
}
#Override
public int retournerNbExemplaires() {
return nbExemplaires;
}

Categories