Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I am having a problem of how to call a method once when the condition achieves many times! for example:
public void onLocaitonChanged(Location location){
// this if statement may achieve the condition many times
if(somethingHappened){
callAMethodOnce();// this method is called once even if the condition achieved again
}
}
Please help with that
public void onLocaitonChanged(Location location){
// this if statement may achieve the condition many times
if(somethingHappened){
if (!isAlreadyCalled){
callAMethodOnce();// this method is called once even if the condition achieved again
isAlreadyCalled = true;
}
}
}
boolean isHappendBefore = false;
public void onLocaitonChanged(Location location){
// this if statement may achieve the condition many times
if(somethingHappened && (! isHappendBefore) ){
isHappendBefore = true;
callAMethodOnce();// this method is called once even if the condition achieved again
}
}
You could simply set a flag. If you just need it to only happen once with each instance of the Activity then set a member variable.
public class MyActivity extends Activity
{
boolean itHappened = false;
...
public void onLocaitonChanged(Location location)
{
// this if statement may achieve the condition many times
if(somethingHappened && !itHappened)
{
callAMethodOnce();// this method is called once even if the condition achieved again
itHappened = true;
}
}
If you want it to only happen once ever in the life of the application then set that variable as a SharedPreference
set a class wide boolean
if(!hasRun){
callAMethodOnce();
hasRun = true;
}
Maybe I don't understand your question correctly but from your problem definition I would suggest using a boolean variable something like.
boolean run = false;
public void onLocaitonChanged(Location location){
// this if statement may achieve the condition many times
if(somethingHappened && run == false){
run = true;
callAMethodOnce();// this method is called once even if the condition achieved again
}
}
Once the code under if statement gets executed once run would be true and there won't be any subsequent calls to callAMethodOnce()
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I have a Time class which has a comparison method called lessThan
public boolean lessThan(Time t1, Time t2) {
if (t1.getHours() > t2.getHours()) {
return false;
} else if (t1.getHours() == t2.getHours()) {
if (t1.getMinutes() >= t2.getMinutes()) {
return true;
} else
return true;
} else
return true;
}
I want to use this method inside my main class to compare to Time objects passed to sort my Time objects.
public static void sortAppointments(ArrayList < Time > appointments) {
Time val;
for (int i = 0; i < appointments.size(); i++) {
if (!lessThan(appointments.get(i), appointments.get(i + 1))) {
val = appointments.get(i + 1);
appointments.set(i + 1, appointments.get(i));
appointments.set(i, val);
}
}
}
But I get a cannot find symbol error when I compile. What am I doing wrong? How can I use my own method inside main class?
You write,
I have a Time class which has a comparison method called lessThan
and
I want to use this method inside my main class
, where apparently you attempt to realize the latter with
if( !lessThan( appointments.get( i ), appointments.get( i + 1 ) ) ) {
But that invocation of lessThan(), appearing as it does in a static method of the main class, will resolve method name lessThan against the main class. The method you want is not there, but rather in the Time class.
Moreover, you have implemented Time.lessThan(Time, Time) as an instance method, so it needs to be invoked on an instance of Time, yet it does not appear to make any use of that instance. It would make more sense as an instance method of class Time if it accepted only one argument, and evaluated whether the instance it is invoked on is less than the argument. As it presently stands, the method would be more useful if it were static.
The smallest set of changes that would resolve this issue would be to
Make the method static:
// In class Time
public static boolean lessThan( Time t1, Time t2 ) { // ...
AND
invoke it as such in your main class:
if( !Time.lessThan( appointments.get( i ), appointments.get( i + 1 ) ) ) {
Either make your method a static helper function and call it in a static fashion or change the signature of your method to utilise the instance of Time that the method exists in using this i.e.
public boolean lessThan( Time other ) {
if (this.getHours() > other.getHours()) {
return false;
}
}
then utilise the instance method in your test class
boolean less = appointments.get(i).lessThan(appointments.get( i + 1 ));
Also for sorting a list, an easier way is to make your Time implement Comparable<Time> and then use Collections.sort(list)
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
There is a status variable in a Java application that can be set to one of many statutes, depending on many conditions. The status field is a String. When a condition is met, the status should be returned immediately, as follows:
e.g
String status = "";
if (condition1) {
return "STATUS_1";
} else if (condition2) {
return "STATUS_2";
} else if (condition3) {
return "STATUS_3";
} else if (condition4) {
return "STATUS_4";
}
...
else if (condition10) {
return "STATUS_10";
}
I've considered which pattern would be best to make this code more SOLID... e.g. if a new condition is required then this class would need to edited to add the new condition, which would break the open / closed SOLID principle
I've looked at the Strategy Pattern, in particular "Replace Conditional Logic with Strategy", however that seems more appropriate when you want to decide on just one calculation / operation to use... My scenario does not seem to fit the Strategy Pattern as my logic determines the status, rather than determining which individual operation to execute - I need to run all the conditions until one is true
I wondered if the following pattern could work...
Have an interface as follows
public interace StatusCondition {
boolean condition(Context context);
String getStatus();
}
With an implementation as follows:
public class StatusAStatusCondition implements StatusCondition {
boolean condition(Context context){
return context.getValue1() == 0 && context.getValue2().equals("A");
}
String getStatus(){
return "STATUS_A";
}
}
This would allow a list of StatusCondition classes to be executed in order and return the status of the first StatusCondition where the condition() method returns true. e.g:
public String getStatus(List<StatusCondition> statusConditions) {
for (StatusCondition statusCondition : statusConditions) {
if (statusCondition.condition()) {
return statusCondition.getStatus();
}
}
return "";
}
usage:
List<StatusCondition> statusConditions = new ArrayList<>();
statusConditions.add(statusAStatusCondition);
statusConditions.add(statusBStatusCondition);
statusConditions.add(statusCStatusCondition);
statusConditions.add(statusDStatusCondition);
statusConditions.add(statusEStatusCondition);
statusConditions.add(statusFStatusCondition);
...
String status = getStatus(statusConditions);
To me this solves the open closed principle issue and also ensures the implementations are single responsibility... My question is, how could this pattern i've suggested be improved, or is there a pattern better suited to my scenario?
First, you are absolutely correct that the original if/else ladder violates the Open/Closed Principle. Second, converting the status value to an interface is exactly the right step to take, to move away from stringly-typed programming. Third, your solution is essentially the Chain of Responsibility Pattern. It's an excellent solution to this problem. In summary, your instincts are spot on.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I declared my boolean variable, but it seems to be doing the opposite of what I want it to do. When I click on a button, it deletes itself, when the boolean variable was false. How could I fix it so that whenever I click on the 'delete' button is turns the 'deleteNow' variable to true? Because it seems that deleteNow is always true. Here is a snippet of my code:
public class deleteButton
{
public boolean deleteNow = false;
class ClickListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
deleteNow = true;
}
}
ActionListener deleteButtonClicked = new ClickListener();
deleteButton.addActionListener(deleteButtonClicked);
class ClickListenerTwo implements ActionListener
{
public void actionPerformed(ActionEvent f)
{
if (deleteNow = true)
{
JButton buttonThatWasClicked = (JButton) e.getSource();
Container parent = buttonThatWasClicked.getParent();
parent.remove(buttonThatWasClicked);
parent.revalidate();
parent.repaint();
}
else
{
System.out.println("The button wasn't deleted");
}
}
}
}
if (deleteNow = true) needs to be changed to if (deleteNow == true)
= operator assigns the value true to the variable whereas == operator just performs the comparison.
the following line is your error:
if (deleteNow = true)
needs to be
if (deleteNow == true)
To make it work.
Instead of checking for equality, you do an assignment in your case, which will always result in the condition being true, so delete your button.
Since your code is pseudocode and invalid java, my guess is that the error #Darshan Mehta mentions is not the real problem.
From your code the real problem is that you have two event listeners operating on the same state. Then the result will depend on whether the first event listener has changed the state of the button before the other has a chance to read its value. It seems as if the simple logic here is that the event listeners are called in the order added. A quickfix would then be to simply reverse the order of the event listeners.
A better approach would be to not have to different event listeners operating on the same state. Combine them into one if they are really meant to operate in tandem - as they do here. Then you can more easily control the flow of operations.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I'd like to make this into a boolean that will return true or false.
I simply got no idea how to , so I need some help.
public static void checkUSPASS(String a,String b) {
try {
con = DriverManager.getConnection(url,username, password);
stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
String sql;
sql = "SELECT * FROM db Where Email='"+a+"' and Password='"+b+"'";
ResultSet rs = stmt.executeQuery(sql);
if(rs.next())
{
//return true
}
else
{
//return false
}
}
catch (SQLException ex) {
ex.printStackTrace(); }
}
I should probably get all declarations out , but I'd like to hear what do you think guys.
While this is not the answer to your question, but I believe it will help you to make your method better. Probably comment will be more suitable, but comments with large piece of text are hard to read.
Don't use SQL query string composition like you do. Use PreparedStatement instead of that.
Process exceptions inside of your method or throw them further. Printing stack trace is not the exception processing, it hides the problem from the end-user.
To throw the exception further add throws SQLException to your method declaration, and remove try/catch construction from the method body. It will allow the caller to process the exception and will avoid many hard-to-catch bugs later.
Don't store passwords as Strings, it is a bad practice. Hash passwords with salt and store password hashcode.
And finally your method declaration should look like that:
public static boolean checkUSPASS(String username,String hashCode) throws SQLException
First change the method signature to return a value:
public static boolean checkUSPASS(String a,String b)
Then return a value from within the method:
return true;
or:
return false;
Note that all code paths must return some value. So you have this in your try block:
if (rs.next()) {
return true;
}
else {
return false;
}
But in the event of reaching your catch block, something must still be returned:
catch (SQLException ex) {
ex.printStackTrace();
return false;
}
To change a function to boolean in java all you have to do is change void to boolean in your function definition and return true or false at all end points.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
This is my code:
public class Outline {
int rowIndex=62;//hsample number
int colIndex=2;//sample number, will be determined by RNG when I'm done
String val=read1(rowIndex,colIndex);
System.out.print(val);//This is where the error is, I don't know what's wrong with it.
public static final String FILE_NAME = "Copy_of_Words.xls";
public static String read1(int rowIndex, int colIndex){
String value = new String();
HSSFWorkbook wb = null;
try {
wb= new HSSFWorkbook(new FileInputStream(FILE_NAME));
} catch (Exception e){//in here, say what needs to be done
}
HSSFSheet sheet=wb.getSheet("SAT"); //here, user input will determine sheet
HSSFRow row=sheet.getRow(rowIndex-1);
HSSFCell cell=row.getCell(colIndex-1);
DataFormatter formatter = new DataFormatter();
value = formatter.formatCellValue(cell);
return value;
}
}
What exactly is the problem with system.out.print(val)? I can't figure it out. I'm using apache and excel in the program, but I don't think that should cause problems.
You can't use
System.out.print(val);
Out side a method. You should put System.out.print(val); inside a method.
public void myMethod(){
System.out.print(val);
}
You try to execute a statement in the class body. You can't do that.
Every statement must be inside a method (or a constructor or an initializer block).
Only declarations (method/field/constructor/...) can be directly in the class body.
Your
System.out.print(val);
is out side the method scope.
System.out.print(val);
This statement must be present in some function.
Classes are defined this way:
class MyClass {
// field, constructor, and
// method declarations
}
You can't execute statements there. They should be located inside a method. See Declaring Classes.
You cant invoke
System.out.print(val);
on class level. If you want to execute some code then you need to place it in
methods (like public static void main(String[] args){...}),
constructors,
or initializing blocks
Write ur statement
System.out.print(val);
either in Function or main function.