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

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

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

Try code not getting executed? [duplicate]

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;
}
}

java-how to handle runtime errors?

I'm writing a java program that adds two numbers with any length(the input is string). it works well but the judge gives me 44 because it has "Runtime Error"
what should i do?
To Answer your question "How to handle runtime-errors",
It is not different from any other exception:
try {
someCode();
} catch (RuntimeException ex) {
//handle runtime exception here
}
This judge may have given you a 44 (assuming that is low) because the input that comes to you as strings may not be numbers at all, and if this happens, your program should not crash? That would be my guess
UPDATE: Now that you have some code up, this is most likely the case, what happens if String a is "hello" ? Your program would crash at Long.parseLong(), you need to handle this!
Replace all your calls to Long.parseLong, by calls to such a method :
private long checkLong(String entry){
long result = 0;
try
{
result = Long.parseLong(entry);
}
catch(NumberFormatException e)
{
System.out.println("Value " + entry + " is not valid") ;
System.exit(1);
}
return result;
}

No conversion with Integer.ParseInt()

I have a problem that when I use Integer.parseInt in this context it doesn't convert my and somehow it even kick me out of loop so it dont't want to display for example System.out.print(1) after loop like everything was crashed but i have no error. Please help. That's a part of code which cause it. variable "input" is an Arrayl
for (int i=0;i<input.size();i++)
{
if(point>Integer.parseInt(input.get(i).split(":")[1]))
{
input.set(i,highScore + System.getProperty("line.separator"));
break;
}
}
Have you verified that input.get(i).split(":")[1] gives you exactly a string that only contains digits?
Integer.parseInt(String s) throws NumberFormatException, so you should execute that code inside a try/catch block like this:
for (int i=0;i<input.size();i++) {
try {
int parsedValue = Integer.parseInt(input.get(i).split(":")[1]);
// do whatever you want to do with parsedValue
}
catch(NumberFormatException e) {
System.out.print("I caught an error!, what i was trying to parse wasn't a number");
// or any other action you consideer that needs to be done when parseInt fails
}
}
There is only one explanation (if you are sure that no exception is thrown): the input is empty. :)

Is there an easy way to exit Java while loop without re-writing much of the code? [duplicate]

This question already has answers here:
How do I exit a while loop in Java?
(10 answers)
Closed 5 years ago.
I am new to Java and programming in general. I've encountered not exactly a problem, but more like a wall of my ignorance. On my QA Automation courses I was asked to write a simple calculator program in Java, I kept it very basic - you needed to launch the program over again every time you preformed a calculation. I learned about while loops and it seemed the while loop was a good solution to keep the program running. But now I am at another extreme - the loop is infinite. My question is: is there any simple way to exit the program without re-writing the code and the way I've structured my calculator? I don't know how to do it but it would be nice if program would end when user presses [Esc] or prints "Exit". Is there a simple way that I (beginner) would understand and could implement?
import java.io.IOException;
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
int first, second, answer;
String operator;
Scanner s = new Scanner(System.in);
try {
while (true) {
log("Please enter a math equation using +, -, * or /");
first = s.nextInt(); //User enters first number
operator = s.next(); //User enters operator
second = s.nextInt(); //User enters second number
if (operator.contains("+")) {
answer = first + second;
log("" + answer);
}
if (operator.contains("-")) {
answer = first - second;
log("" + answer);
}
if (operator.contains("*")) {
answer = first * second;
log("" + answer);
}
if (operator.contains("/")) {
if (second == 0) {
log("You can't divide by 0");
} else {
answer = first / second;
log("" + answer);
}
}
}
} catch (java.util.InputMismatchException error) {
log("Incorrect input");
}
}
public static void log(String s) {
System.out.println(s);
}
}
Thank you, if you can help me!
P.S. I don't know if it is a correct way to handle exceptions or a very ugly one. I'd appreciate if you could comment on that too.
Yes, use break:
if(endingCondition)
break;
This will break out of the innermost loop.
In order to follow your example and not deviate from it focusing on other code improvements, you should have to change the way you read the parameters, because the way you do it now, you could never read the exit word to get out. In order to do this you can use the following approach:
This will add a new string parameter to read the exit or the first operand (in string format). Then, it will transform it into an int:
int first, second, answer = 0;
String operator, firstParam = "";
Scanner s = new Scanner(System.in);
try {
while (true) {
System.out.println("Please enter a math equation using +, -, * or /, or exit if you want to stop the program");
firstParam = s.next(); //User enters first number or exit
// This first param is read as a String so that we are able to read the word exit
if(firstParam.equals("exit"))
break;
first = Integer.valueOf(firstParam); // This will transform the first parameter to integer, because if it reaches this point, firstParam won't be "exit"
//[... Rest of your program...]
}
} catch (java.util.InputMismatchException error) { ... }
TIPS FOR ERROR HANDLING
1: You don't have to specify the complete reference of the InputMismatchException while in catch block because you have already imported the java.util package
catch (InputMismatchException e)
{
//handle exception here
}
2: In case you are unsure about the type of Exception that can thrown, just catch the object of class Exception. Since Exception is the super class for all the Exceptions, it can handle all exceptions.. This would work perfectly for beginners.
catch (Exception e)
{
//handle exception
}
3: You can handle multiple exceptions for the same try block, each catch handling a particular type of exception. Give it a try.
FOR EXITING THE LOOP
if (s1.contains("EXIT"))
break;
Here s1 is the string, and if the string contains the word EXIT (ALL CAPS ONLY), the loop will terminate.

Categories

Resources