Try code not getting executed? [duplicate] - java

This question already has answers here:
What does a "Cannot find symbol" or "Cannot resolve symbol" error mean?
(18 answers)
Closed 5 years ago.
So, I have a problem but I do not really know what exactly is causing it. I had a program that inicially worked, but it couldn't afford every entry. In order to fix this I added a try - catch block. Before the change, I only had the two lines you can see inside the try block, instead of all the try - catch code.
Until now, I think everything should be right. But as I tried to compile my code, I got an ""error: cannot find symbol (variable: workedPer)"". I thought the try block was always executed, so why is that variable not being defined? I have looked into other similar questions, but couldn't find a solution.
NOTE: This is a portion of the code, I only put this in order to make the problem easier to see. But if you need more code please let me know.
try
{
String[] workedPer = newPer.split("=");
workedPer[1] = workedPer[1].substring(0, workedPer[1].length() -1);
}
catch (ArrayIndexOutOfBoundsException ex)
{
System.out.println("Invalid Entry. Program will stop now...");
System.exit(1);
}
for (Material mat : readyContent)
{
if ((mat.category).equals(workedPer[0]))
{
checker = true;
}
}

Because, scope of workedPer variable is limited to try block.
You need to change your code to
String[] workedPer = null;
try
{
workedPer = newPer.split("=");
workedPer[1] = workedPer[1].substring(0, workedPer[1].length() -1);
}
So that, it can be accessible inside for loop
for (Material mat : readyContent)
{
if ((mat.category).equals(workedPer[0])) // you are using it here
{
checker = true;
}
}

Related

How can I stop Java catch block executing [duplicate]

This question already has answers here:
How to handle infinite loop caused by invalid input (InputMismatchException) using Scanner
(5 answers)
try/catch with InputMismatchException creates infinite loop [duplicate]
(7 answers)
Catching an InputMismatchException until it is correct [duplicate]
(4 answers)
Closed 3 years ago.
Here's a part of me code. Well, my question is how can I skip catch block when I enter wrong values? For example, as you can see I need coordinates to be double or Float but when I enter String it starts infinite while looping. How can I prevent it and make program start from the begining until user enters right values?
main_loop:
while (true) {
int i = 3;
System.out.println("Attemts left: " + i);
loop_label:
while (true) {
try {
temp_coords.setX(temp_scn.nextDouble());
temp_coords.setY(temp_scn.nextFloat());
break main_loop;
} catch (Exception e) {
System.out.println("wrong format!");
} finally {
break loop_label;
}
}
i--;
if(i == 0){
break;
}
}
This is my code without loops and labels
How can I can make this code work until right data coming in
try {
temp_coords.setX(temp_scn.nextDouble());
temp_coords.setY(temp_scn.nextFloat());
} catch (Exception e) {
System.out.println("wrong format!");
}
break loop_label
Should be in the catch block. Do not use finally because the code inside it will be run even if no error is thrown.
And as Andy said, it seems i will never be equal to 0

How should I handle NumberFormatException in java? [duplicate]

This question already has answers here:
What is a NumberFormatException and how can I fix it?
(9 answers)
Closed 6 years ago.
Is there a way to handle the number(order) of NumberFormatException? I made a calculator using Double operand[], and like below, I want to write when did error occurred. When I put the input "2+k", the message saying that "operand[1] has the wrong input." should come out. How should I do like that?
First, replace the line
System.out.println("operand[] has the wrong input.");
with the line
System.out.println(e.getMessage());
Now you can pass a message when you throw the exception in the MyCalculator.calculate() method using the NumberFormatException(String) constructor. It would look something like this:
calculate(String expression)
{
//validate input code
//...
//if operand 0 not valid
throw new NumberFormatException("operand 0 has the wrong input");
//if operand 1 not valid
throw new NumberFormatException("operand 1 has the wrong input");
//rest of calculate method
}
Maybe you could define a new exception. As for example CalculatorException which could contain more specific information about calculations, as for example which operand is incorrect. Or you could even define one more exception like IllegalOperandException which could extend CalculatorException. And then your method calculate could be declared to throw a CalculatorException. In conclusion, the idea is to define a new hierarchy of exceptions to give information more related to the domain of your problem.
And then, your code could be so:
try {
System.out.println("result: " + MyCalculator.calculate(expression));
System.out.println();
} catch(CalculatorException e) {
System.out.println(e.getMessage());
}

Try/Catch error exception returing null [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
I'm trying to read in a list of words a file using BufferedReader and determine if any are duplicates, and if they are, to not print them. I know that there is a SuperClass called "UniqueLineReader" that can check the occurrence of duplicate lines for you, and something else called Linked HashSet. However, I haven't learned either of these in class, so I'm trying not to use them.
Anyways, the e.getMessage() is printing "null", which I don't understand, because the file obviously isn't and I'm checking that it isn't. Do I have wrong placement of variables?
try {
inFile = new BufferedReader(new FileReader(inputName));
outFile = new PrintWriter(new FileWriter(outputName));
while((nextLine = inFile.readLine())!= null){
if(indexOf(nextLine) == -1){
insert(nextLine);
outFile.println(nextLine);}
else{
System.out.println(nextLine + " has been seen before!");
}
}
inFile.close();
}//try
catch(Exception e){
System.out.println(e.getMessage());
}//catch
My indexOf method:
private int indexOf(String newWord){
for(int i = 0; i < numWords; i++){
if(arrayStrings[i].equals(newWord)){
return i;
}
}
return -1;
}//indexOf
stacktrace
`java.lang.NullPointerException
at A2Q2.indexOf(A2Q2.java:58)
at A2Q2.removeDuplicateLines(A2Q2.java:79)
at TestA2Q2.main(TestA2Q2.java:10)
According to the stack trace, the problem is at line 58 of file A2Q2.java, at that line you are using this:
arrayStrings[i].equals(...)
Which means that either arrayStrings is null, or arrayStrings[i] is null.
Adding a simple System.out.println before that line (or using a debugger) will show you exactly what is wrong.
BTW: I see you are using a fixed size array instead of an ArrayList to save the lines, I recommend the latter in this case as you don't need to specify the maximum number of lines beforehand.

No exception still not coming out of while loop [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
Following is my java code block
i am not able to come out of while block, the same code run's perfect in other module. kindly help me
public void current_ER(View v){
try{
String[] parameters= {uid};
Caller c=new Caller();
c.url="current_ER.php";
c.parameters=parameters;
c.join(); c.start();
String result=MainActivity.result;
System.out.print("before while");
while(result=="START") {
try {
Thread.sleep(10);
System.out.print(result);
}
catch(Exception ex) {
ex.getLocalizedMessage();
System.out.print("in catch");
}
}
System.out.print("after while");
Toast.makeText(this, "ER Details->"+result , Toast.LENGTH_LONG).show();
{
System.out.print("before start indent block");
/////////to next screen////
Intent Manage_Expense=new Intent(this,Manage_Expense.class);
Manage_Expense.putExtra("er_details", result);
//MainActivity.result="START";
Toast.makeText(this, "ER Details->"+result , Toast.LENGTH_LONG).show();
//startActivity(Manage_Expense);
}
}catch(Exception e){
System.out.println(e.getMessage());
}
};
First of all, use:
while("START".equals(result))
In order to compare Strings.
The main error is that you never update result.
At first you set:
String result=MainActivity.result;
So result and MainActivity.result points to the same object.
However, in the other thread you update:
MainActivity.result=resp;
Causing MainActivity.result to point to resp, but result still points to previous value.
If you want to check a variable in a loop, you must make sure the value is changed inside the loop.
When you're going to compare 2 strings it's better to use String.equals(), == operator better works on primitives but not on objects.
As well as using String#equals() make sure the variable is marked as volatile so threads can see changes made by other threads.
i updated my code as follows and it worked
System.out.print("before while");
while("START".equals(MainActivity.result)) {
try {
Thread.sleep(10);
System.out.print(MainActivity.result);
}catch(Exception ex) { ex.getLocalizedMessage();
System.out.print("in catch");
}
}
but i am still unable to figure out why my original code didn't work

How to continue execution of a try catch statement in java [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Java: Try-Catch-Continue?
I'm reading in information from a text file and I want my code to throw an exception if there is an invalid type being read. However, I can't figure out how to have my program continue after an exception has been found
while(input.hasNext()) {
try{
type = input.next();
name = input.next();
year = input.nextInt();
} catch(InputMismatchException ex)
{
//System.out.println("** Error: Invalid input **");
//code to make program continue
}
}
You can either just let the thread leave the catch block - code execution will continue after that. If you want to skip the code after the catch block, you can use the continue keyword within a while loop...
If you want to retrieve a year after retrieving the name failed with an exception, then you will have to put a try ... catch around each input.next...() statement. You cannot restart execution at the point the exception has been thrown.

Categories

Resources