Unreachable statement error
Could you please help me figure out what the problem with my code is? I get: C:\Documents and Settings\Sandy\My Documents\Payroll2.java:31: unreachable statement
System.out.println( "Enter Hourly Rate: "); // prompt
^
1 error
when I compile this:
// Payroll2.java
// A Payroll program with a while loop
// that continues until "stop" is used as the name
import java.util.Scanner; // program uses class Scanner
public class Payroll2
// main method begins execution of java application
public static void main(String args[])
// create a scanner to obtain input in command window
Scanner input = new Scanner( System.in );
String employeeName; // Name of employee
double hourlyRate; // Amount made in one hour
double hoursWorked; // Number of hours worked in one week
double weeklyPay; // The multiple of hourly rate and hours worked in one week
// while method employed to enter emplyee's name
while ( "employeeName" != "stop")
System.out.println("Enter an employee name(Input 'stop' when finished)\n\n"); //prompt
employeeName = input.nextLine(); // read employee name or stop
} // end while
// if...else method used to input hourly rate as a positive double
System.out.println( "Enter Hourly Rate: "); // prompt
hourlyRate = input.nextDouble(); // read hourly rate
if ( hourlyRate <= 0)
System.out.println( "Hourly Rate incorrect, please try again\n"); // error message
}// end if
else
System.out.println( "Correct Hourly Rate input, thank you\n\n"); // confirmation message
} // end else
// if...else method used to input hours worked
System.out.print( "Enter Hours Worked: "); // prompt
hoursWorked = input.nextDouble(); // read hours worked
if ( hoursWorked <= 0)
System.out.println( "Weekly hours worked is incorrect, please try again\n"); // error message
}// end if
else
System.out.println( "Correct weekly hours input, thank you\n\n"); // confirmation message
} // end else
// calculate weekly pay
weeklyPay = hourlyRate * hoursWorked; // multiply numbers
// display employee name and weekly pay
System.out.printf( "Weekly Pay for %s,is $%.2f\n", employeeName, weeklyPay);
System.out.println( "Thank you for using Payroll2\n"); // good bye message
} // end method main
} // end class Payroll2
Tip: You will find the appropriate method in the Java API. (If you are not familiar whit that try http://java.sun.com/javase/6/docs/api/)
If you do not find the answer just ask again... Everybody loves to help here it seems. But you should know that the sooner you learn how to find the (simple or not simple) answers in the API the sooner you will be a real good java programmer. good luck!
Similar Messages
-
Unreachable statement error occured while using return statement.
Consider this code
class q25{
public static void main(String args[]){
amethod(args);
public static void amethod(String args[]){
String str;
try{
str = "Hello "+args[0];
System.out.println(str);
System.out.println("Returning to caller");
System.exit(0);
catch(Exception e){
System.out.println("Exception ocured");
System.exit(0);
finally{
System.out.println("In finally");
System.out.println("At the end of method");
}Above code compiles and runs successfully without any errors.
Now consider below code which is same as above one except "System.exit(0)" statements were replace by "return" statements. Below code when compiled gives error as
"q25.java:22: unreachable statement
System.out.println("At the end of method");
^
1 error"
One thing i didn't understood in this context that, the above code when compiled should get same error as stated above. But not. It is obvious that presence of System.exit(0) must generate unreachable statement same as when it is replaced by "return" statement. What is the difference in getting the error for above but not for below code. Pls anyone help.
class q25{
public static void main(String args[]){
amethod(args);
public static void amethod(String args[]){
String str;
try{
str = "Hello "+args[0];
System.out.println(str);
System.out.println("Returning to caller");
return;
catch(Exception e){
System.out.println("Exception ocured");
return;
finally{
System.out.println("In finally");
System.out.println("At the end of method");
}warnerja wrote:
masijade. wrote:
Since you have a "return" in both the try and the catch portions of the try/catch block *(the second of which you should never do)* , anything thing that comes after the try/catch/finally blocks will be unreachable.That is not true. There are plenty of reasons to return from a catch block. If you handle the exception instead of rethrowing it or another exception, then you'll need a return somehow, either there or after the catch block. What you should never do is "return" in a finally block, because that will mask any exception in flight about to be thrown to the caller.Perhaps masijade's use of never is too strong, but I too prefer/tend to avoid using return anywhere in try/catch/finally to avoid potential gotchas. Consider:
public class TryCatchFinally
public Data process(String s)
Data returnData = new Data();
try
returnData.value = Integer.parseInt(s);
returnData.message = "Success";
return returnData;
catch (Exception ex)
returnData.value = -1;
returnData.message = "Fail";
return returnData;
finally
returnData.value = 42;
returnData.message = "?";
public static void main(String[] args)
TryCatchFinally demo = new TryCatchFinally();
Data d = demo.process("2");
System.out.println(d.message + ": " + d.value);
d = demo.process("2.1");
System.out.println(d.message + ": " + d.value);
class Data
int value = 0;
String message = "";
} -
Expected "unreachable statement" error but it compiled successfully
Bellow following code, i expected compile time error something like "unreachable statement i++" on line no. 4 as it is obvious that the line returns 'i' and increments 'i' value due to virtue of post increment operator ++. But i didn't get any type of errors - compile time or runtime error - which i thought would get one and ran successfully printing 0.
Can anybody explain the reason behind this?
1. class Target {
2. private int i = 0;
3. public int addOne() {
4. return i++;
5. }
6. }
7. public class Client {
8. public static void main(String[] args) {
9. System.out.println(new Target().addOne());
10. }
11.}karthikbhuvana wrote:
Ok fine. That's a good example. But my question is, once the control returns from the method addOne(), how it is possible that variable 'i' gets incremented?
return i++; is equivalent to the following:
int tmp = i;
i = i + 1;
return tmp;The expression i++ is evaluated completely, and then the value of the i++ expression is returned. Evaluating i++ completely means "remembering" the current value of i as the value of the expression, and then incrementing i.
That's also why
int i = 0;
i = i++; // never do this for real
System.out.println(i);prints out 0, not 1. The RHS is evaluated before assigning to the LHS. The "post" in "post-increment" doesn't mean "after the rest of the statement is done." I means "increment happens after getting the value of the expression." -
Wrong code analysis on "unreachable statement" for nested loops
Try this with JavaFX 1.2 (NetBeans 6.5.1)
function foo():Void {
for (i in [0..<10]) {
for (j in [0..<10]) { // be marked as unreachable statement
if (match()) {
break;
return; // I just want to get out
// break goes here
}It shows "unreachable statement" at the second 'for'.
Right now I just change "return;" to "if (true) return;" to get it pass.I agree it is a bug at the compiler level. If I do your change and add println of i and j, I get a trace on j, obviously.
You should file a bug report at [Jira / Kenai|http://javafx-jira.kenai.com/] (or I can do if you don't want to create an account).
[EDIT] Uh, no, it is a known problem: [Bogus 'Unreachable statement' error|http://javafx-jira.kenai.com/browse/JFXC-3323], I will add this thread as a comment.
A more complete use case:
function foo(): Void {
for (i in [ 0 ..< 5 ]) {
println("I {i}");
for (j in [ 0 ..< 5 ]) {
println("J {j}");
if (match()) {
break;
println("Some operation in the inner loop");
if (true) return;
// break goes here
function match(): Boolean { return Math.random() > 0.5; }
foo();Now, the inner loop isn't really necessary, we never go beyond 0 for j... But technically, there is no unreachable statement, unless it means we never go up to 5 in the inner loop. In this case, Robert Field is right, the error message should be clearer.
Edited by: PhiLho on 29 juil. 2009 10:17 -
"catch is unreachable" compiler error with java try/catch statement
I'm receiving a compiler error, "catch is unreachable", with the following code. I'm calling a method, SendMail(), which can throw two possible exceptions. I thought that the catch statements executed in order, and the first one that is caught will execute? Is their a change with J2SE 1.5 compiler? I don't want to use a generic Exception, because I want to handle the specific exceptions. Any suggestions how to fix? Thanks
try {
SendMail(....);
} catch (MessagingException e1) {
logger.fine(e1.toString());
} catch (AddressException e2) {
logger.fine(e2.toString());
public String SendMail(....) throws AddressException,
MessagingException {....I found the problem:
"A catch block handles exceptions that match its exception type (parameter) and exception types that are subclasses of its exception type (parameter). Only the first catch block that handles a particular exception type will execute, so the most specific exception type should come first. You may get a catch is unreachable syntax error if your catch blocks do not follow this order."
If I switch the order of the catch exceptions the compiler error goes away.
thanks -
I need help with this code error "unreachable statement"
the error_
F:\Java\Projects\Tools.java:51: unreachable statement <-----------------------------------------------------------------------------------------------------------------THIS
int index;
^
F:\Java\Projects\Tools.java:71: missing return statement
}//end delete method
^
F:\Java\Projects\Tools.java:86: missing return statement
}//end getrecod
^
3 errors
import java.util.*;
import javax.swing.*;
import java.awt.*;
public class Tools//tool class
private int numberOfToolItems;
private ToolItems[] toolArray = new ToolItems[10];
public Tools()//array of tool
numberOfToolItems = 0;
for(int i = 0; i < toolArray.length; i++)//for loop to create the array tools
toolArray[i] = new ToolItems();
}//end for loop
}//end of array of tools
public int search(int id)//search mehtod
int index = 0;
while (index < numberOfToolItems)//while and if loop search
if(toolArray[index].getID() == id)
return index;
else
index ++;
}//en while and if loop
return -1;
}//end search method
public int insert(int id, int numberInStock, int quality, double basePrice, String nm)//insert method
if(numberOfToolItems >= toolArray.length)
return 0;
int index;
index = search(id); <-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------HERE
if (index == -1)
toolArray[index].assign(id,numberInStock, quality, basePrice,nm);
numberInStock ++;
return 1;
}//end if index
}//end if toolitem array
return -1;
}//end insert method
public int delete(/*int id*/)//delete method
}//end delete method
public void display()//display method
for(int i = 0; i < numberOfToolItems; i++)
//toolArray.display(g,y,x);
}//end display method
public String getRecord(int i)//get record method
// return toolArray[i].getName()+ "ID: "+toolArray[i].getID()
}//end getrecod
}//end class
Edited by: ladsoftware on Oct 9, 2009 6:08 AM
Edited by: ladsoftware on Oct 9, 2009 6:09 AM
Edited by: ladsoftware on Oct 9, 2009 6:10 AM
Edited by: ladsoftware on Oct 9, 2009 6:11 AMladsoftware wrote:
Subject: Re: I need help with this code error "unreachable statement"
F:\Java\Projects\Tools.java:51: unreachable statement <-----------------------------------------------------------------------------------------------------------------THIS
int index;
^
F:\Java\Projects\Tools.java:71: missing return statement
}//end delete method
^
F:\Java\Projects\Tools.java:86: missing return statement
}//end getrecod
^
3 errorsThe compiler is telling you exactly what the problems are:
public int insert(int id, int numberInStock, int quality, double basePrice, String nm)//insert method
if(numberOfToolItems >= toolArray.length)
return 0; // <<== HERE you return, so everyting in the if block after this is unreachable
int index;
index = search(id); //< -----------------------------------------------------------------------------------------------------------------HERE
if (index == -1)
toolArray[index].assign(id,numberInStock, quality, basePrice,nm);
numberInStock ++;
return 1;
}//end if index
}//end if toolitem array
return -1;
}//end insert method
public int delete(/*int id*/)//delete method
// <<== HERE where is the return statement?
}//end delete method
public String getRecord(int i)//get record method
// return toolArray.getName()+ "ID: "+toolArray[i].getID() <<== HERE you commented out the return statement
}//end getrecod
}//end class -
Problems with booleans - Unreachable Statement.
Hey,
at the top of my class I have Random() declared like so...
private static Random noise = new Random();
and further down I'm trying to do an IF statement like so....
if(noise.nextBoolean() == true)
makeBetterSB.reverse();
the IDE displays an error of "Unreachable Statement".
What have I done wrong?We would have to know which statement the compiler said was unreachable to answer that. We would also have to know what comes before that statement, because it's the code before that statement that causes it to be unreachable.
-
How to ignore unreachable statement (javac)?
for debugging/testing purposes, i would like the javac compiler to ignore unreachable statement or just print a warning and not an error. is this possible?
reason: it's much easer to type "return result;" somewhere within code than do enclose several (cascaded) parts with if ().Good day,
Even though I'm pretty new to Java, I don't think this is possible.
I would presume that you're doing this mainly to debug your code.
I personnaly define a boolean variable, which can be accessed all throughout the class file : "boolean leavenow=true;"
When I want to insert a "temporary breakpoint" to check things out, I simply type something like "if (leavenow) return result;".
I understand that this is tad longer to type, but it doesn't affect the indentation of your code if you want to keep the things "aligned".
Might not be the ideal approach, but this is a way to look at it.
Regards. -
Hi experts,
After running the Extended check (SLIN) I got the following message:
Unreachable Statement After Jump Statement EXIT:
DESCRIBE TABLE i_table LINES itab_lines.
(You can hide the message using "#EC *)
My question: How can I eliminate this error?Hi...
If u have any statements that terminates the Current processing Block / Program such as
Leave to Screen...
Exit..
Stop..
Then any statements after them will not be reachable.
So you need to avoid them.
Paste ur code if u are not able to trace it.
<b>Reward if Helpful.</b> -
TABLE ILLEGAL STATEMENT error with MODIFY command
Hi gurus,
i want you to inform me about table illegal statement error. The error occurs when i use modify as below.
loop at itab.
select .......
where xxx eq itab-xxxx.
MODIFY itab.
endselect.
endloop.
i know that i have to give the sy-tabix as INDEX parameter to the modify command. but i want to know why i have to do this?
cause when i debug, i follow the sy-tabix field and it have not a change in select endselect.
may the reason of the error about cursor in select and cursor effects modify command?
or why?
Thx,Hello,
I guess this is because your MODIFY statement is inside the SELECT ... ENDSELECT & not inside the LOOP ... ENDLOOP.
SAP documentation says:
Within a LOOP loop, the INDEX addition can be ommitted. In this case the current table line of the LOOP loop is changed.
You have to change the coding:
DATA: v_index TYPE i.
loop at itab.
v_index = sy-index.
select .......
where xxx eq itab-xxxx.
MODIFY itab INDEX v_index.
endselect.
endloop.
BR,
Suhas
PS: The coding practice followed is not very performance oriented as well. May be you should have a look around in some blogs, wikis in SCN & change the code accordingly.
Edited by: Suhas Saha on Nov 19, 2009 9:41 AM -
I am getting "ORA-00900: invalid SQL statement" error.?
I did installed oracle 11gR2. and used "DBMS_METADATA_DIFF.COMPARE_ALTER('TABLE','TBL_A','TBL_A','USER1','USER2')" to see the result like below, but I am getting "ORA-00900: invalid SQL statement" error. Any idea?
I am using:
Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - Production
PL/SQL Release 11.2.0.1.0 - Production
CORE 11.2.0.1.0 Production
TNS for 32-bit Windows: Version 11.2.0.1.0 - Production
NLSRTL Version 11.2.0.1.0 - Production
SQL> desc user1.tbl_a
Name Null? Type
FIELD_A1 NOT NULL NUMBER
FIELD_A2 VARCHAR2(20)
FIELD_A4 NOT NULL NUMBER(5,2)
FIELD_A5 VARCHAR2(10)
FIELD_A6 NOT NULL NUMBER(2)
SQL> desc user2.tbl_a
Name Null? Type
FIELD_A1 NOT NULL NUMBER
FIELD_A2 VARCHAR2(50)
FIELD_A3 DATE
FIELD_A4 NUMBER(5,2)
FIELD_A5 NOT NULL VARCHAR2(10)
SQL> select dbms_metadata_diff.compare_alter('TABLE','TBL_A','TBL_A','USER1','USER2') from dual
expected result:
DBMS_METADATA_DIFF.COMPARE_ALTER('TABLE','TBL_A','TBL_A','U1','U2')
ALTER TABLE "U1"."TBL_A" ADD ("FIELD_A3" DATE)
ALTER TABLE "U1"."TBL_A" DROP ("FIELD_A6")
ALTER TABLE "U1"."TBL_A" MODIFY ("FIELD_A2" VARCHAR2(50))
ALTER TABLE "U1"."TBL_A" MODIFY ("FIELD_A4" NUMBER(5,2) DEFAULT 0)
ALTER TABLE "U1"."TBL_A" MODIFY ("FIELD_A4" NULL)
ALTER TABLE "U1"."TBL_A" MODIFY ("FIELD_A5" NOT NULL ENABLE)Thanks for reply rp,
I got result using "select dbms_metadata_diff.compare_alter('TABLE','TBL_A','TBL_A','USER1','USER2') from dual" -
ORA-00900: invalid SQL statement Error while Executing Procedure
Hi:
I am trying to execute following procedure through java code, but i am getting ORA-00900: invalid SQL statement error.
Procedure is :
<code>
(vResult out int)
as
vCardId varchar2(16);
vForacid varchar2(16);
vApp_Entry_No varchar2(10);
vSrNo number(6);
vCardStatus char(1);
vCardStat char(2);
vExpiryDate date;
Cursor cardCur1 is
select u.card_number,trim(u.ACCOUNT_NUMBER),u.CARD_STATUS,to_char(u.EXPIRY_DATE,'dd-MM-yyyy')
FROM DailyCardData u
where default_indicator='1'
and isprocessed = 'N'
order by expiry_date;
begin
vSrNo := 0;
vResult := 0;
open cardCur1;
Loop
fetch cardCur1 into vCardId,vForacid,vCardStat,vExpiryDate;
if cardCur1%NOTFOUND then
exit;
end if;
if (vCardStat != null) then
vCardStatus := 'H';
elsif (vExpiryDate <= sysdate) then
vCardStatus := 'E';
else
vCardStatus := null;
end if;
select a.app_entry_no into vApp_Entry_No from Application a,ApplicationLinkedAccounts l
where l.foracid = vForacid and l.AcSrNo = '1'
and a.app_entry_no = l.app_entry_no
and a.cardid is null
and a.DOWNLOADFILECREATIONFLAG = 'Y';
update Application set CardId = vCardId,
Card_Status = vCardStatus,APPLICATIONPROCESSEDFLAG = 'Y',
APPLICATIONPROCESSEDdate = DOWNLOADFILECREATIONdate
where App_Entry_No = vApp_Entry_No;
commit;
update DailyCardData set isprocessed = 'Y',app_entry_no = vApp_Entry_No
where card_number = vCardId;
commit;
end Loop;
close cardCur1;
vResult := 1;
end;
</code>
Can any body help me in that?
Thank You,
AnupFirst of all I don't see a procedure header.
Secondly I see you commit inside your procedure. This is a bug.
Thirdly I see you also commit inside a loop. This is also a bug, and needs to be removed asap.
The error indicates a statement doesn't parse. As you don't post the error stack, nor a table definition no one can reproduce the problem.
You need to isolate the statements, one by one, and run them through sql*plus to see what happens.
Sybrand Bakker
Senior Oracle DBA -
Invalid cursor state error while executing the prepared statement
hai friends,
following code showing the invalid cursor state error while executing the second prepared statement.
pls anyone help me
String query = "select * from order_particulars where order_no=" + orderno + " order by sno"; psmt1 = conEntry.prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); rs1 = psmt1.executeQuery(); rs1.last(); intRowCount = rs1.getRow(); particularsdata = new Object[intRowCount][6]; rs1.beforeFirst(); if (intRowCount >= 1) { for (int i = 0; rs1.next(); i++) { particularsdata[0] = i + 1;
particularsdata[i][1] = rs1.getString(3);
particularsdata[i][2] = Double.parseDouble(rs1.getString(4));
rs1.close();
psmt1.close();
query = "SELECT sum(delqty) FROM billdetails,billparticulars WHERE order_no= " + orderno + " and " +
"billdetails.bill_no = billparticulars.bill_no GROUP BY particulars ORDER BY sno";
psmt1 = conEntry.prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
rs1 = psmt1.executeQuery(); //error showing while executing this lineAlso .. Why using arrays instead of collections? Shifting the cursor all the way forth and back to get the count is fairly terrible.
With regard to the problem: either there's a nasty bug in the JDBC driver used, or you actually aren't running the compiled class version of the posted code. -
Using UNUSABLE on Unique Index gives "initially in unusable state" error
I am doing the following:
1. Truncate table
2 Alter PK Index Disable
2. Alter Unique Index Unusable
3. Insert /*+ APPEND NOLOGGING*/ into my table
My problem is, I get an "ORA-26026: unique index ... initially in unusable state" error when I try to do the Insert. If I make the Unique index non-unique it isn't a problem. If I drop the index and recreate it its not a problem - so uniqueness doesn't appear to be the issue. Can you not use UNUSABLE with a Unique index, I couldn't find any reference to this in the 10g docs.
I am using 10.1.0.4.
Thanks
Richard26026, 0000, "unique index %s.%s initially in unusable state"
//* Cause: A unique index is in IU state (a unique index cannot have
//* index maintenance skipped via SKIP_UNUSABLE_INDEXES).
//* Action: Either rebuild the index or index partition, or use
//* SKIP_INDEX_MAINTENANCE if the client is SQL*Loader. -
Receiver JMS ( websphere MQ ) error - No transition found from state:ERROR
Hi all
we are using JMS adapter to connect to the Queue manager . whenever the queue manager restarts , the messages is not getting thru and it is struck in the adapter engine with status " not to be delivered "
i am getting error in receiver communication channel audit log....its showing
*MP: Exception caught with cause com.sap.aii.af.ra.ms.api.RecoverableException: No transition found from state: ERROR, on event: process_commence for DFA: CC_JMS_XXXXXXXXX:15fa03eb9fd837849906f512610314c4*
note : already i have gone thur many forum and nothing helps.
Thanks in advance
FaheemIf you are using the FCC then this could be because of that. What is the connection status with MQ? Are there any connection errors with MQ.
If you are using FCC in your Receiver JMS channel then just to confirm, first remove the FCC configuration and try to send a xml file. If the xml file goes in successfully then the problem is in your FCC configuration.
Maybe you are looking for
-
hi, I have a simple program: one frame's content pane adds two JPanels. Source as follows: import javax.swing.*; import java.awt.*; import java.awt.event.*; public class DragTest2 { public static void main(String[] args) { JFrame frame = new JFrame()
-
Aperture and iPhoto - do they co-exist?
I have been using iPhotos to import all pictures/videos from Digital Camera, iPhones, iPads for over year, although I never knew where the files were stored. In the past I could only email photos within the iPhotos 11 s/w itself, but I could not atta
-
Isolated: WEP is messing up my web browsing and uploads. Why?
My web browsing and uploads keep "hanging" when accessing my AP Extreme wirelessly. A straight HTML downloads fine. But a page that has code that talks back to the server (e.g. a Google docs page) hangs. Also it seems that javascript navigation that
-
HI,all. May i know how to get the Condition Value in Purchase Oder (me23n)?? I want to get the condition value from it's Header, but not the amount. Thanks in advance.
-
Transaction call from Abap Dynpro
Hello @all, I want to make a transaction call within an ABAP Webdynpro and I don't want to use therefore ITS or IVIEWS. Do anybody know another possibilty to make a transaction call within an ABAP Webdynpro? Is there a possibility to call a SAP trans