Breaking out of a method in a loop [closed] - java

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I have a method with a break statement in its if statement. The method is in a while loop. Will it break out of the while loop if I use break within the method's if statement or do I have to use nested loops?
public int x=0;public int y=0;
public boolean endCondition = true;
public void someMethod()
{
if(x!=y) {//do something}
else break;
}
while(endCondition==true)
{
this.someMethod();
}
System.out.println("Bloke");

You can not use break without a loop or a switch . You need to use return. But it seems a endless method calling which would cause StackOverflow exception.

To break out from a function you have to use return. break will break you out from only the inner loop inside which you are calling it.

You probably need to return a boolean value from the method, which you can then use to decide whether to break the loop.
It's not important in this simple example, but it's usually a good idea to label your loops when using break, so it's clear what you are breaking out of, especially when using nested loops. See the label FOO below.
public boolean someMethod()
{
if(x!=y)
{
//do something
return false;
}
return true; // break
}
FOO:while(true)
{
if(someMethod()) break FOO;
}

Related

Conditional Logic to Determine Correct Status String [closed]

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.

Calling a Method Once [closed]

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()

Get all field values java program [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
I am building a Tetris game. I am currently debugging the game and in order to do this I need to see the values of all the variables and the variables variables and so on. With reflection I can get all a classes fields by doing this:
try
{
for(Field field : this.getClass().getDeclaredFields())
{
field.setAccessible(true);
System.out.println(field.get(this));
}
}
catch(Exception e)
{
}
What I don't know how to get all the field values of each field object.
There are two things you need to do:
Create a set of reachable objects. You don't want to recursively traverse your object graph forever.
Print values for every object.
For the first one, you need to use something like IdentityHashMap:
import java.util.IdentityHashMap;
class MyObjectCache
{
final IdentityHashSet objects = new IdentityHashSet ();
...
}
To traverse objects you can use recursive function (it is simpler, but has a stack restriction):
class MyObjectCache
{
....
void registerObject(Object o)
{
if (objects.contains(o))
{
return;
}
objects.add(o);
for(Field field : o.getClass().getDeclaredFields())
{
field.setAccessible(true);
registerObject(field.get(o));
}
}
...
}
And then you can start printing collected objects...

Why do I get this error when trying to read integers from a file and copy them into an array? [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
I have a text file named "hours.txt" that has lines of integers that I would like to read and copy them into an array.
The integers are the number of hours worked by 8 employees in a week. So I created a two-dimensional array with the rows being the employees and the columns being the days of the week.
public static void read()
{
Scanner read = new Scanner(new File("hours.txt"));
int[][] hours = new int[8][7];
for(int r=0; r<hours.length; r++)
{
for(int c=0; c<hours[0].length; c++)
{
while(read.hasNextInt())
{
hours[r][c]= read.nextInt();
}
}
}
}
When I try to compile this, I get the following error:
EmployeeHours.java:16: error: unreported exception FileNotFoundException; must be caught or declared to be thrown
Why is that?
Because FileNotFoundException is a checked exception. You must either catch and handle it, or throws it in the method declaration. And don't just swallow the exception; that's almost never the right way to "handle" them.
Lots more reading on exactly this topic can be found in the official Java Tutorial.
try {
//block of code
} catch (FileNotFoundException fnfe) {
}
or
public static void read() throws FileNotFoundException
The exception FileNotFoundException must be declared as part of your method signature, to tell the Java compiler that your method can throw that particular exception. You must change your method definition to:
public static void read() throws FileNotFoundException
{
... code here ...
}

Basic debugging with Java [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I don't know how to fix these errors:
class or interface expected errors
package doesn't exists
cannot find symbol
illegal start of type
cannot access java.lang
How can I better understand where the problems in my code are occurring? How can I debug these issues?
Here is my code:
import java.io.*;
public class ResourcesTesterApp {
public static void main(String[] args) {
String s1 = readLineWithResources();
String s2 = readLineWithFinally();
}
public static String readLineWithResources() {
System.out.println("Starting readLineWithResources method.");
try (RandomAccessFile in = new RandomAccessFile("products.ran", "r")) {
return in.readLine();
}} catch (IOException e) {
System.out.println(e.toString());
}
}
public static String readLineWithFinally() {
System.out.println("Starting readLineWithFinally method.");
RandomAccessFile in = null;
String s = null;
try {
in = new RandomAccessFile("products.ran", "r");
s = in.readLine();
} catch (IOException e) {
System.out.println(e.toString());
} finally {
if (in != null) {
try {
in.close();
System.out.println("RandomAccessFile closed");
} catch (IOException e) {
System.out.println("RandomAccessFile " + e.getMessage());
}
}
}
return s;
}
You question is how to better understand and debug these errors. Well all I can say is, look at the actual error message output, it will normally include a line number. Now you can look at the specific line of code and see if you can spot what is wrong.
I don't know if the formatting of the code in your question comes from a failed attempt at pasting it into stackoverflow.com or if that is also how you are working with it, but you should format it properly and that will help with spotting problems. For example, when I formatted your code above straight away you can see an additional closing curly brace.
Once you have the actual error messages and line numbers etc. your best bet is to google the error and try to understand what it means. Once you have exhausted that avenue come back here and formulate a specific question showing exactly what the error message is and the code you are running. Avoid grouping many problems into one question like you have done here.
this usually means you are writing code outside of a method.
this simply means you referenced a package that the java compiler cannot find.
this means you wrote a nonexistant variable.
this usually means you did not complete a statement, and you started writing the next one.
I dont know about this one, maybe be more specific?
I strongly suggest you take a look at the java tutorials, and follow their examples.
you can find them at http://docs.oracle.com/javase/tutorial/

Categories

Resources