Nested While Statements
Hey guys,
Im fairly new to Java programing and i have hit a brick wall in my coding.
My program is a Multi-choice questionaire. And all works fine until i add the error checking code in, and i dont get (and I can't get to work) nested will statements.
Could you guys help me merge these to Statements:
while(!in.hasNextInt()) //This part works fine
{ //This is to check if the user put in a interger.
in.nextLine();
System.out.println("\n Invalid Selection!");
System.out.println("Please Enter Amswer \n" );
}and this part i cant get this part to work correctly
if (Userinput >5 || Userinput <0) //This is ment to set parameters so that
{ //the user can only enter the numbers
in.nextLine(); //between 1 - 5
System.out.println("\n Invaild Selcetion");
System.out.println("Please Enter Answer\n" );
Userinput = in.nextInt();
}I would like to have both sections of code as 1 section so that it checks for both errors before it continues throught he rest of the code.
any help would be greatly appreciated.
if you want to email me or get me on msn:
brokenstaff at gmail dot com
again thanks.
ok, well that is a very complex section =)
well i tried it, but that numer validator still wont allow numbers under 5 ??? i dont know why. It works in the way of giving the error message when entering a char.
any way here is the full code with code inserted:
PS the counter intilization well that is for later.
and you can proably already figure out why it is there. =)
import java.util.*;
public class questions
public static void main(String[] args)
int correct = 0; //Couter for correct answers.
int incorrect = 0; //Couter for incorrect answers.
int Userinput = 0; //Number entered by user.
int userInput = -1; // I am just guessing these go here =)
boolean done = false;
boolean first = true;
Scanner in = new Scanner(System.in);
// QUESTION ONE
System.out.println ("Question 1:");
System.out.println ("");
System.out.println ("Which Java statement displays Hello World to the screen");
System.out.println ("and then moves cursor to a new line?");
System.out.println ("");
System.out.println ("\t 1. Print \"Hello World\" n");
System.out.println ("\t 2. System.out.print(\"Hello World\" + nl);");
System.out.println ("\t 3. System.out.println(\"Hello World\");");
System.out.println ("\t 4. System.out.println(\"Hello World\" + newline);");
System.out.println ("\t 5. None of the above");
System.out.println ("");
System.out.println ("Enter Answer");
/*// THIS SECTION ERROR CHECKS CHARACTERS
// AND WORKS
while(!in.hasNextInt())
in.nextLine();
System.out.println("\n Invalid Selection!");
System.out.println("Please Enter Amswer \n" );
// DOSENT WORK
// while ((!in.hasNextInt) && (Userinput >100 || Userinput <0))
// in.nextLine();
// System.out.println("\n Invalid Selection!");
// System.out.println("Please Enter Amswer \n" );
while(!done) {
if(!first) {
in.nextLine();
System.out.println("\nInvalid selection!");
} else first = false;
System.out.println("Please enter answer\n" );
if(!in.hasNextInt()) {
continue;
userInput = in.nextInt();
done = userInput >= 0 && userInput <= 5;
System.out.println("userInput=" + userInput);
//THIS PART KEEP
userInput = in.nextInt();
if (Userinput == 1 )
System.out.println ("You are correct! - Well done");
else
System.out.println ("Sorry wrong answer - Better luck next time");
// QUESTION TWO
System.out.println ("Question 2:");
System.out.println ("");
System.out.println ("Which Java statement correctly initializes");
System.out.println ("a varible at the beggining of a program?");
System.out.println ("");
System.out.println ("\t 1. int Userinput = 0;");
System.out.println ("\t 2. Userinput ; 0 = int");
System.out.println ("\t 3. Userinput int = 0;");
System.out.println ("\t 4. int 0 = Userinput;");
System.out.println ("\t 5. None of the above");
System.out.println ("");
System.out.println ("Enter Answer");
if (Userinput == 1)
System.out.println ("You are correct! - Well done");
else
System.out.println ("Sorry wrong answer - Better luck next time");
// QUESTION THREE
System.out.println ("Question 3:");
System.out.println ("");
System.out.println ("Which Java statement ius the first line");
System.out.println ("inside the public class brackets?");
System.out.println ("");
System.out.println ("\t 1. (String[public static void main]) args ");
System.out.println ("\t 2. static void public(main[String]) args");
System.out.println ("\t 3. [String]args main() void public");
System.out.println ("\t 4. public static void main(String[] args)");
System.out.println ("\t 5. None of the above");
System.out.println ("");
System.out.println ("Enter Answer");
if (Userinput == 4)
System.out.println ("You are correct! - Well done");
else
System.out.println ("Sorry wrong answer - Better luck next time");
// QUESTION FOUR
System.out.println ("Question 4:");
System.out.println ("");
System.out.println ("Which Java boolean operator is the correct ");
System.out.println ("operatorfor NOT?");
System.out.println ("");
System.out.println ("\t 1. NOT");
System.out.println ("\t 2. NONE");
System.out.println ("\t 3. ==");
System.out.println ("\t 4. !");
System.out.println ("\t 5. None of the above");
System.out.println ("");
System.out.println ("Enter Answer");
if (Userinput == 4)
System.out.println ("You are correct! - Well done");
else
System.out.println ("Sorry wrong answer - Better luck next time");
// QUESTION FIVE
System.out.println ("Question 5:");
System.out.println ("");
System.out.println ("Which Java statement displays Hello World to the screen");
System.out.println ("and then moves cursor to a new line?");
System.out.println ("");
System.out.println ("\t 1. Print Hello World n");
System.out.println ("\t 2. System.out.print(Hello World + nl);");
System.out.println ("\t 3. System.out.println(Hello World);");
System.out.println ("\t 4. System.out.println(Hello World + newline);");
System.out.println ("\t 5. None of the above");
System.out.println ("");
System.out.println ("Enter Answer");
if (Userinput == 3)
System.out.println ("You are correct! - Well done");
else
System.out.println ("Sorry wrong answer - Better luck next time");
// END CODE
System.out.println ("\n");
System.out.println ("PP400 MUTIPLE CHOICE QUIZ");
System.out.println ("=========================");
System.out.println ("");
System.out.println ( + incorrect + " WRONG");
System.out.println ( + correct + " CORRECT");
System.out.println ("");
System.out.println ("End Of Quiz");
}I commented out all the other questions so when I test the app i dont have to cycle through all the questions. Just thought it was a short cut way of doing it.
Similar Messages
-
I have a Y9 Computer Science Exam next week and I know that this will probably be one of the questions on it so I need to know the answer. What is the difference?
An If statement executes once IF the statement is true:
If 1 = 2/2 Then
Textwindow.writeline("True")
EndIf
A While statement executes WHILE the statement is true:
While 4 = 2+2
'Will keep looping while it is true
EndWhile
A For statement loops a number in increment:
For i = 1 to 10
'Every time through, i gets bigger by one until it equals 10
EndFor
It is written: "'As surely as I live,' says the Lord, 'every knee will bow before me; every tongue will acknowledge God.'" Romans 14:11 -
Nested IF statement in outline
We're using 6.2 and I've built a formula into my outline. I have used IF statements before in the outline with no problem. But I'm now trying to use a nested IF statement. Is it possible? Has anyone had any success? I keep getting "unknown calculation type [0} during the dynamic calculation. if(@ISCHILD ("MERCH DEPTS") and a40000>0); "hrs - required"=a40000/"sales/hr"; else if(d0044); "hrs - required"=25; else "hrs - required"=50; endif; endif; TIARod
I'm not sure if I completely understand what you are doing but I saw a few errors in you is statement. On your else if, you can make elseif but you don't have any function on the member name. I guesed that you need @ismbr, but it could be @isdesc or @ischild???. Take a look at the corrected calc script below. It might help youRegardsif(@ISCHILD ("MERCH DEPTS") and a40000>0); "hrs - required"=a40000/"sales/hr"; elseif (@ismbr(d0044)) "hrs - required"=25; else "hrs - required"=50; endif; Glenn S.Narratus Solutions Inc. [email protected]
-
Why is this happening, I am trying to access servlet, 2.4 on the Webshere 6.1, installation as succesfull and the servlet is running without exceptions.
nested while defining class: com.sun.xml.ws.api.WSBinding
This error indicates that the class: javax.xml.ws.Binding
could not be located while defining the class: com.sun.xml.ws.api.WSBinding
This is often caused by having the class at a higher point in the classloader hierarchy
Dumping the current context classloader hierarchy:
==> indicates defining classloader
*** indicates classloader where the missing class could have been found
==>[0]
com.ibm.ws.classloader.CompoundClassLoader@51905190
Local ClassPath: C:\Program Files\IBM\WebSphere\AppServer2\profiles\AppSrv01\installedApps\UKDSK-DBURFORD1Node02Cell\myappservelett2_4_again_war.ear\myappservelett2.4_again.war\WEB-INF\classes;C:\Program Files\IBM\WebSphere\AppServer2\profiles\AppSrv01\installedApps\UKDSK-DBURFORD1Node02Cell\myappservelett2_4_again_war.ear\myappservelett2.4_again.war\WEB-INF\lib\aopalliance-1.0.jar;C:\Program Files\IBM\WebSphere\AppServer2\profiles\AppSrv01\installedApps\UKDSK-DBURFORD1Node02Cell\myappservelett2_4_again_war.ear\myappservelett2.4_again.war\WEB-INF\lib\commons-logging-1.1.1.jar;C:\Program Files\IBM\WebSphere\AppServer2\profiles\AppSrv01\installedApps\UKDSK-DBURFORD1Node02Cell\myappservelett2_4_again_war.ear\myappservelett2.4_again.war\WEB-INF\lib\jaxb-impl-2.1.7.jar;C:\Program Files\IBM\WebSphere\AppServer2\profiles\AppSrv01\installedApps\UKDSK-DBURFORD1Node02Cell\myappservelett2_4_again_war.ear\myappservelett2.4_again.war\WEB-INF\lib\jaxb-xjc-2.1.7.jar;C:\Program Files\IBM\WebSphere\AppServer2\profiles\AppSrv01\installedApps\UKDSK-DBURFORD1Node02Cell\myappservelett2_4_again_war.ear\myappservelett2.4_again.war\WEB-INF\lib\jaxws-rt-2.1.4.jar;C:\Program Files\IBM\WebSphere\AppServer2\profiles\AppSrv01\installedApps\UKDSK-DBURFORD1Node02Cell\myappservelett2_4_again_war.ear\myappservelett2.4_again.war\WEB-INF\lib\jaxws-rt-2.1.7.jar;C:\Program Files\IBM\WebSphere\AppServer2\profiles\AppSrv01\installedApps\UKDSK-DBURFORD1Node02Cell\myappservelett2_4_again_war.ear\myappservelett2.4_again.war\WEB-INF\lib\jaxws-spring-1.8.jar;C:\Program Files\IBM\WebSphere\AppServer2\profiles\AppSrv01\installedApps\UKDSK-DBURFORD1Node02Cell\myappservelett2_4_again_war.ear\myappservelett2.4_again.war\WEB-INF\lib\jboss-j2ee.jar;C:\Program Files\IBM\WebSphere\AppServer2\profiles\AppSrv01\installedApps\UKDSK-DBURFORD1Node02Cell\myappservelett2_4_again_war.ear\myappservelett2.4_again.war\WEB-INF\lib\jremote.jar;C:\Program Files\IBM\WebSphere\AppServer2\profiles\AppSrv01\installedApps\UKDSK-DBURFORD1Node02Cell\myappservelett2_4_again_war.ear\myappservelett2.4_again.war\WEB-INF\lib\log4j-1.2.9.jar;C:\Program Files\IBM\WebSphere\AppServer2\profiles\AppSrv01\installedApps\UKDSK-DBURFORD1Node02Cell\myappservelett2_4_again_war.ear\myappservelett2.4_again.war\WEB-INF\lib\org.springframework.aop-3.0.1.RELEASE.jar;C:\Program Files\IBM\WebSphere\AppServer2\profiles\AppSrv01\installedApps\UKDSK-DBURFORD1Node02Cell\myappservelett2_4_again_war.ear\myappservelett2.4_again.war\WEB-INF\lib\org.springframework.asm-3.0.1.RELEASE.jar;C:\Program Files\IBM\WebSphere\AppServer2\profiles\AppSrv01\installedApps\UKDSK-DBURFORD1Node02Cell\myappservelett2_4_again_war.ear\myappservelett2.4_again.war\WEB-INF\lib\org.springframework.beans-3.0.1.RELEASE.jar;C:\Program Files\IBM\WebSphere\AppServer2\profiles\AppSrv01\installedApps\UKDSK-DBURFORD1Node02Cell\myappservelett2_4_again_war.ear\myappservelett2.4_again.war\WEB-INF\lib\org.springframework.context-3.0.1.RELEASE.jar;C:\Program Files\IBM\WebSphere\AppServer2\profiles\AppSrv01\installedApps\UKDSK-DBURFORD1Node02Cell\myappservelett2_4_again_war.ear\myappservelett2.4_again.war\WEB-INF\lib\org.springframework.core-3.0.1.RELEASE.jar;C:\Program Files\IBM\WebSphere\AppServer2\profiles\AppSrv01\installedApps\UKDSK-DBURFORD1Node02Cell\myappservelett2_4_again_war.ear\myappservelett2.4_again.war\WEB-INF\lib\org.springframework.expression-3.0.1.RELEASE.jar;C:\Program Files\IBM\WebSphere\AppServer2\profiles\AppSrv01\installedApps\UKDSK-DBURFORD1Node02Cell\myappservelett2_4_again_war.ear\myappservelett2.4_again.war\WEB-INF\lib\org.springframework.jms-3.0.1.RELEASE.jar;C:\Program Files\IBM\WebSphere\AppServer2\profiles\AppSrv01\installedApps\UKDSK-DBURFORD1Node02Cell\myappservelett2_4_again_war.ear\myappservelett2.4_again.war\WEB-INF\lib\org.springframework.transaction-3.0.1.RELEASE.jar;C:\Program Files\IBM\WebSphere\AppServer2\profiles\AppSrv01\installedApps\UKDSK-DBURFORD1Node02Cell\myappservelett2_4_again_war.ear\myappservelett2.4_again.war\WEB-INF\lib\org.springframework.web-3.0.1.RELEASE.jar;C:\Program Files\IBM\WebSphere\AppServer2\profiles\AppSrv01\installedApps\UKDSK-DBURFORD1Node02Cell\myappservelett2_4_again_war.ear\myappservelett2.4_again.war\WEB-INF\lib\spring-batch-infrastructure-2.1.0.RELEASE.jar;C:\Program Files\IBM\WebSphere\AppServer2\profiles\AppSrv01\installedApps\UKDSK-DBURFORD1Node02Cell\myappservelett2_4_again_war.ear\myappservelett2.4_again.war\WEB-INF\lib\stax-ex-1.2.jar;C:\Program Files\IBM\WebSphere\AppServer2\profiles\AppSrv01\installedApps\UKDSK-DBURFORD1Node02Cell\myappservelett2_4_again_war.ear\myappservelett2.4_again.war\WEB-INF\lib\streambuffer-0.7.jar;C:\Program Files\IBM\WebSphere\AppServer2\profiles\AppSrv01\installedApps\UKDSK-DBURFORD1Node02Cell\myappservelett2_4_again_war.ear\myappservelett2.4_again.war\WEB-INF\lib\TWSCore.jar;C:\Program Files\IBM\WebSphere\AppServer2\profiles\AppSrv01\installedApps\UKDSK-DBURFORD1Node02Cell\myappservelett2_4_again_war.ear\myappservelett2.4_again.war\WEB-INF\lib\xbean-spring-3.4.3.jar;C:\Program Files\IBM\WebSphere\AppServer2\profiles\AppSrv01\installedApps\UKDSK-DBURFORD1Node02Cell\myappservelett2_4_again_war.ear\myappservelett2.4_again.war
Delegation Mode: PARENT_FIRST
[1] com.ibm.ws.classloader.JarClassLoader@777399894 Local Classpath: Delegation mode: PARENT_FIRSTEdited by: romanshtekelman on Sep 9, 2010 7:34 AMFor future reference...
We followed the following instructions and created a shared lib.
http://download.oracle.com/docs/cd/E12524_01/web.1013/e12290/opensrc.htm#BABDDAIF
We resolved most of our class loading issues.
BR//Bahman -
Is it possible to nest SELECT statements?
Greetings community,
Another newbie’s question it is. Looking tutorials and some posts here I’ve been advised not to pull entire table through the local network, and torture client machines’ processors and memory. It’s been said that better solution is to
pull just one part of the table.
So, imagine this: you want to make a part of your app that would allow your user to view list of orders. So you put one data grid view on the form, pull last 20 headers from the table into it and leave to user to choose one to be opened
in another form. If user doesn’t find header they want, they press page up for example and previous 20 headers are loaded into data grid view. Of course, user could filter headers list by customer, or by distribution lane (having all customers residing in
one part of the town), or whatever more, but let’s not complicate things at this moment, because I’m practically in the beginning.
I’m trying to make a stored procedure that would load penultimate 20 headers when user presses page up. So, not knowing any better, I created table variable that has the same structure as Orders table with one difference: OrderID column,
which is identity (auto incremented) in Orders table, here is simply defined as bigint not null. Community member Visakh16 warned me few months ago it’s the bad practice to put self-incrementing columns in table variables.
At this moment there’s a query on my screen, which waits to become store procedure. After boring part with table variable definition, it goes like this:
INSERT INTO @OrdersTemp SELECT TOP 40 * FROM dbo.Orders ORDER BY OrderID DESC
SELECT TOP 20 * FROM @OrdersTemp ORDER BY OrderID ASC
To put that simply, I pull last 40 headers into table variable, and then pull first 20 from there. This thing works, and I just have to replace 40 with parameter, for every page up or down.
Now I have few questions.
-Is there some better way (considering performance) to achieve that? Here is the place where I wanted to ask the question from the title of the post. I don’t know much about T-SQL, and I’m not sure about the proper syntax to nest SELECT
statements, if something like that is even possible
-Is there any better way (some built-in function) to find about the count of the rows in one table than
SELECT COUNT(OrdersID) FROM dbo.Orders
Thanks for any suggestions.Hi Erland,
Sorry for the very late reply, but I said that I would start another thread when I find more free time to dedicate it to this, so I didn’t really expected you to reply anymore. I didn’t really check here for more than a week, and I glanced
at mail accidentally.
As for the negative result I got, its measurement unit is microsecond, so it doesn’t go out of margins you had experienced.
As for the number of cores, you got me surprised there. I use express edition of SQL server. Last time I checked was SQL server 2012 express, and in specifications it said that express edition is limited to 1 processor core, 1GB of RAM
and creates up to 10GB database file. I don’t believe they changed any of those specifications. It was generous enough when they doubled size of DB file few editions ago. Still, it appears that “one processor core for express edition” statement has some gray
areas in it.
However, at this moment I’m just learning, and I just wanted some way to test how efficient my queries are. I don’t have a real biz problem to solve. I don’t expect that any real performance problem should rise in years of everyday work
of populating database. What I expect is performance impact when it comes to creating reports, but after all, I don’t think that my boss would create reports by himself. I believe that creating reports would be my task, and I will be doing it after hours,
being the only user at the moment. Or maybe I could make de-normalized copy of database that would be populated after hours to make it possible for my boss to get his reports faster by himself, as I’ve heard that was the way of making BI in older non-express
editions.
So, I do suggest that we finally close this thread for sake of other readers. I’ll start another one with this subject when I find the time to do it.
Again, thanks for being with me along this journey. -
Nested SQL statements for complex, detailed queries.
Is it possible to write nested SQL statements for complex, detailed queries. A nested query
has a WHERE clause that includes a SELECT statement ? Is it true or false ?Hi wahid,
Here are pretty good examples:
http://www.databasejournal.com/features/mssql/article.php/3464481/Using-a-Subquery-in-a-T-SQL-Statement.htm
http://technet.microsoft.com/en-us/library/aa213252(v=sql.80).aspx
Regards Harsh -
Problem with while statement :(
i am having a problem with my while statement, can anyone help me to get it working :(
i am trying to get the while statement to only run when the input hasnt been a yes or a no, can someone please help me.
System.out.print("Are you a Resident? (yes/no): ");
Resident = console.next(); //Requests resident status from user and puts in in Resident
while ((Resident != "yes") && (Resident != "no"))
System.out.print("error - You didnt type yes or no. Try again: ");
Resident = console.next();
}while ((Resident != "yes") && (Resident != "no"))Don't compare Strings with ==, use the equals() method instead.
while(!("yes".equals(Resident) && "no".equals(Resident))) -
Having Trouble with nested Case Statements
Hi Folks,
I'm having trouble getting my head round nested case statements. For the life of me I cannot see what I'm missing here (unless my approach is all wrong).
Any help much appreciated.
Script:
set serveroutput on format wrapped
set feedback off
set linesize 150
DECLARE
/* Set supported version here */
ora_version VARCHAR2(4);
unsupp_version EXCEPTION;
/* Archive Log Info */
db_log_mode VARCHAR2(12);
BEGIN
SELECT SUBSTR(VERSION, 1, 4)
INTO ora_version
FROM v$instance;
SELECT log_mode
INTO db_log_mode
FROM v$database;
CASE
WHEN ora_version = '10.2' THEN
DECLARE
TYPE t_db IS RECORD(
dflsh VARCHAR2(3),
dcscn NUMBER);
v_db t_db;
BEGIN
CASE
WHEN db_log_mode = 'ARCHIVELOG' THEN
EXECUTE IMMEDIATE 'SELECT INITCAP(flashback_on), current_scn FROM v$database'
INTO v_db;
DBMS_OUTPUT.PUT_LINE(' Flashback On : ' || v_db.dflsh);
DBMS_OUTPUT.PUT_LINE(' Current SCN : ' || v_db.dcscn);
DBMS_OUTPUT.PUT_LINE(' Log Mode : ' || db_log_mode);
DBMS_OUTPUT.PUT_LINE(' Version : ' || ora_version);
END;
ELSE
DBMS_OUTPUT.PUT_LINE(' Log Mode : ' || db_log_mode);
DBMS_OUTPUT.PUT_LINE(' Version : ' || ora_version);
END CASE;
END;
WHEN ora_version = '9.2' THEN
DECLARE
TYPE t_db IS RECORD(
dcscn NUMBER);
v_db t_db;
BEGIN
CASE
WHEN db_log_mode = 'ARCHIVELOG' THEN
EXECUTE IMMEDIATE 'SELECT current_scn FROM v$database'
INTO v_db;
DBMS_OUTPUT.PUT_LINE(' Current SCN : ' || v_db.dcscn);
DBMS_OUTPUT.PUT_LINE(' Log Mode : ' || db_log_mode);
DBMS_OUTPUT.PUT_LINE(' Version : ' || ora_version);
END;
ELSE
DBMS_OUTPUT.PUT_LINE(' Log Mode : ' || db_log_mode);
DBMS_OUTPUT.PUT_LINE(' Version : ' || ora_version);
END CASE;
END;
ELSE
RAISE unsupp_version;
END CASE;
EXCEPTION
WHEN unsupp_version THEN
DBMS_OUTPUT.PUT_LINE('');
DBMS_OUTPUT.PUT_LINE(' Unsupported Version '||ora_version||' !');
DBMS_OUTPUT.PUT_LINE('');
END;
set linesize 80
set feedback on
set serveroutput off
Gives errors:
END;
ERROR at line 31:
ORA-06550: line 31, column 7:
PLS-00103: Encountered the symbol ";" when expecting one of the following:
case
ORA-06550: line 37, column 1:
PLS-00103: Encountered the symbol "WHEN"
ORA-06550: line 50, column 28:
PLS-00103: Encountered the symbol ";" when expecting one of the following:
case
Edited by: milkyjoe on 28-Apr-2010 05:38Hi,
Never write, much less post, unformatted code.
Indent the code to show the extent of multi-line structures like BEGIN and CASE.
For example:
DECLARE
/* Set supported version here */
ora_version VARCHAR2 (4);
unsupp_version EXCEPTION;
/* Archive Log Info */
db_log_mode VARCHAR2 (12);
BEGIN
SELECT SUBSTR(VERSION, 1, 4)
INTO ora_version
FROM v$instance;
SELECT log_mode
INTO db_log_mode
FROM v$database;
CASE
WHEN ora_version = '10.2' THEN
DECLARE
TYPE t_db IS RECORD(
dflsh VARCHAR2(3),
dcscn NUMBER);
v_db t_db;
BEGIN
CASE
WHEN db_log_mode = 'ARCHIVELOG' THEN
EXECUTE IMMEDIATE 'SELECT INITCAP(flashback_on), current_scn FROM v$database'
INTO v_db;
DBMS_OUTPUT.PUT_LINE(' Flashback On : ' || v_db.dflsh);
DBMS_OUTPUT.PUT_LINE(' Current SCN : ' || v_db.dcscn);
DBMS_OUTPUT.PUT_LINE(' Log Mode : ' || db_log_mode);
DBMS_OUTPUT.PUT_LINE(' Version : ' || ora_version);
END;
...The code above is what you posted, with some whitespace added.
The error is much clearer; the last CASE statement concludes with END, but CASE blocks always have to conclude with END CASE .
Why are you using a nested BEGIN block in the code above? Are you plannning to add an EXCEPTION handler later?
When posting formatted text on this site, type these 6 characters:
\(small letters only, inside curly brackets) before and after each section of formatted text, to preserve spacing. -
Sql 2008 nested case statement
I have a question about understanding nested case statements in sql server 2008:
The sql looks like the folloiwng:
select numberofcases
from inventory
where inventory_cnt > 1000
(when select top 1
from inventory
where inventory_cnt > 750
then numberofcases = 750 * 30
when select top 2
from inventory
where inventory_cnt > 975
then numberofcases = 975 * 35
when select top 3
from inventory
where inventory_cnt > 1025
then numberofcases = 1025 / 10
when select top 4
from inventory
where inventory_cnt > 1050
then numberofcases = 1050 / 5) c * 2
as casesused, select CustomerNumber from inventory
I would like you to explain the following:
1. There are 4 when statements. Will the logic hit each when statemnet or will the logic
stop once the first when statement is true?
2. Would you explain what the c* 2 means from the school listed above?Please post DDL, so that people do not have to guess what the keys, constraints, Declarative Referential Integrity, data types, etc. in your schema are. Learn how to follow ISO-11179 data element naming conventions and formatting rules. Temporal data should
use ISO-8601 formats. Code should be in Standard SQL as much as possible and not local dialect.
This is minimal polite behavior on SQL forums.
SELECT CASE
WHEN Inventory_cnt > 1050 THEN 1050 / 5
WHEN Inventory_cnt > 1025 THEN 1025 / 10
WHEN Inventory_cnt > 750 THEN 750 * 30
WHEN Inventory_cnt > 975 THEN 975 * 35
ELSE NULL END AS cases_used
FROM Inventory;
I would like you to explain the following:
>> 1. There are 4 when statements. Will the logic hit each when statement or will the logic stop once the first when statement is true? <<
This code is garbage, not SQL. CASE is an expression, not a statement. Expressions return a scalar value. Your are trying to do control flow! And the answer is that a CASE works this way
1) look at the THEN clauses and determine the data type to use
2) test each WHEN clause and execute the first one that tests TRUE in left to right order.
>> 2. Would you explain what the c* 2 means from the school listed above? <<
Syntax error and more garbage code.
--CELKO-- Books in Celko Series for Morgan-Kaufmann Publishing: Analytics and OLAP in SQL / Data and Databases: Concepts in Practice Data / Measurements and Standards in SQL SQL for Smarties / SQL Programming Style / SQL Puzzles and Answers / Thinking
in Sets / Trees and Hierarchies in SQL -
Hi,
I have a while statement and within this a return statement, but when i compile this it produces an error -
missing return statement.
This is my code:
public double getResults() { // Open getResults method
while ( i >= 10 ) { // Open while
i++;
return (runs * 10);
} // Close while
} // Close getResults method
What is wrong?
ThanksThe compiler waits for the return statement to be at the end of the method. For example if you put it before your while loop you'll have an error like "unreachable statement". Because the compiler understands the return statement as the end of the method.
In your case:
What happens in any loop or statement is forgot after its end. So if you create a variable inside the loop and your try to change its value after the end of the loop, it will give you an error because any variable created inside the loop is erased from the memory at the end of the loop. The same thing happens to your return statement . If the value is returned in the loop, as the compiler understand it as the end of the method, it creates an error because the method is not finished yet. And as a previous user told you if the condition of the while loop is not met the return will not be executed. But the compiler is not so smart, it just waits for the return statement as the last line of any such method. And as the value you are returning is declared outside the loop, it will keep its new value at the end of the loop, so you will return the value you want. -
Prompting for user input in nested select statements
I recently rewrote a query to use a nested select statement instead of specifying every SELECT field on the GROUP BY line. Here's the query which works perfectly with hard-coded values of '030', '01/01/11', and '12/31/11'.
SELECT T0.[CardName] AS Customer, T0.[CardCode] as 'Cust ID', T0.[Phone1] as Phone, T0.[CntctPrsn] as 'Contact Person', T0.[Address], T0.[City], T0.[State1] as State, T0.[ZipCode] as 'Zip Code', T0.[Country], T1.[TotalSales]
FROM OCRD T0
INNER JOIN
(SELECT I.[CardCode] AS CardCode, SUM(I.[DocTotal]) AS TotalSales
FROM OINV I
WHERE left (I.[CardCode], 3) = '030' AND (I.[DocDate] >= '01/01/11' AND I.[DocDate] <= '12/31/11')
GROUP BY I.[CardCode]) T1
ON T0.[CardCode] = T1.[CardCode]
ORDER BY T0.[CardName]
When I try to prompt for the left 3 characters of the CardCode (or the dates), ie.
WHERE left (I.[CardCode], 3) = [%0] AND (I.[DocDate] >= '01/01/11' AND I.[DocDate] <= '12/31/11')
I get an error "Column 'OCRD.CardName' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause".
It's like putting a user variable in the inner SELECT made it part of the outer SELECT which is exactly what I was trying to avoid by re-writing this query with the inner SELECT.
Can anyone explain what SQL Server is doing here and how to fix it?Thanks Gordon. That's how I originally wrote the query and it works fine. But I was disturbed that I had to GROUP BY every field in my SELECT statement when I really only wanted to group by CardCode. So I did some research and came up with this where the inner select still groups by only CardCode and still takes user input. I don't really understand why you need the commented SELECT statements in the SET lines, but you do. Something about using real table fields for variables.
DECLARE @startDate datetime
DECLARE @endDate datetime
DECLARE @rep varchar(10)
SET @rep /* SELECT T0.[CardCode] FROM ORDR T0 WHERE T0.[CardCode] */ = '[%0]'
SET @startDate /* SELECT T0.[DocDate] FROM OINV T0 WHERE T0.[DocDate] */ = '[%1]'
SET @endDate /* SELECT T0.[DocDate] FROM OINV T0 WHERE T0.[DocDate] */ = '[%2]'
SELECT T0.[CardName] AS Customer, T0.[CardCode] as 'Cust ID', T0.[Phone1] as Phone, T0.[CntctPrsn] as 'Contact Person', T0.[Address], T0.[City], T0.[State1] as State, T0.[ZipCode] as 'Zip Code', T0.[Country], T1.[TotalSales]
FROM OCRD T0
INNER JOIN
(SELECT I.[CardCode] AS CardCode, SUM(I.[DocTotal]) AS TotalSales
FROM OINV I
WHERE left (I.[CardCode], 3) = @rep AND (I.[DocDate] >= @startDate AND I.[DocDate] <= @endDate)
GROUP BY I.[CardCode]) T1
ON T0.[CardCode] = T1.[CardCode]
ORDER BY T0.[CardName]
FOR BROWSE -
How Do You "Unload" Using a "While" statement?
How do you "Unload" or "Exit" using a "While" statement?
Sample: The console displays "Press Enter to continue".
Description: It a User press the Enter key, then the application would start over. On the other hand, if a User presses the "0" key, the application ends, exits. What code would be used?
THANKS ... signed ... VERY NEW at JAVA ...input=readInput();
while (input!=yourExitKey)
// do stuff here
input=readInput();
// End of code -
How to create nested CASE statements in PL/SQL
Can anyone please tell how to create Nested CASE statements in PL/SQL with proper syntax?
It would be better if you can help with an example.
Thank you!Something like this:
SQL> set serveroutput on
SQL> declare
2 v1 number := 2;
3 v2 varchar2(1) := 'C';
4 begin
5 case v1
6 when 1 then dbms_output.put_line('First');
7 when 2 then begin
8 case v2
9 when 'A' then dbms_output.put_line('Found A');
10 when 'B' then dbms_output.put_line('Found B');
11 when 'C' then dbms_output.put_line('Found C');
12 else dbms_output.put_line('NONE');
13 end case;
14 end;
15 else dbms_output.put_line('Else');
16 end case;
17 end;
18 /
Found C
PL/SQL procedure successfully completed
SQL> If you have further doubts regarding syntax you can read the docs on the Case statement here:
http://download.oracle.com/docs/cd/E11882_01/appdev.112/e10472/case_statement.htm -
I'm trying to nest a statement in oracle. The first statement looks like this:
Select DEREF(TREAT (REF(P) AS ref clubmember_ty)).passwd
FROM persons_tab p; This works fine.
This gives me the password from the clubmember_ty. But insted of typing the whole DEREF...statement for every atrribute i want to get, I would like to type something like this:
select cm.username,cm.password,cm.E_mail,cm.surname from(
Select DEREF(TREAT (REF(P) AS ref clubmember_ty))
FROM persons_tab p) cm;
The problem is that i get the error messege: "invalid columname" for cm.username,cm.password,cm.E_mail.
Clubmember is a subtype of person(all created as types) and they are stored in a table that contains types.
Anyone have any suggestions? Thanks.Could this be done more efficiently with a JOIN? I always think about that when I hear about a situation where one ResultSet is used to drive a query for another. If the first query brings back N records, that means (N+1) network roundtrips to get the final result. That could be a performance killer for large N.
If you can, you're better off writing this as a SELECT with a sub-SELECT or a JOIN.
If you must do it this way, you're always smarter to load the ResultSet into a CachedRowSet or a data structure and then close out the ResultSet right away, IMO. -
Nested select statements.
Hi, I am writing a piece of code in which i use nested select statements for 4 tables to retrieve one column's data (ie: POSNR). But when i execute it, it takes way too long to get the data. I'm quite new to ABAP so very in need of your help. Thanks
REPORT z_impos_test.
TABLES: coss, "CO Object: Cost Totals for Internal Postings
afvc, "Operation within an order
prps, "WBS (Work Breakdown Structure) Element Master Data
imzo. "Table: CO Object - Capital Investment Prog.Pos.
TYPES: BEGIN OF st_impos,
objnr TYPE coss-objnr,
gjahr TYPE coss-gjahr,
kstar type coss-kstar,
projn type afvc-projn,
pspnr type prps-pspnr,
posnr type imzo-posnr,
END OF st_impos.
data: year TYPE coss-gjahr value '2007'.
DATA: t_output TYPE STANDARD TABLE OF st_impos WITH HEADER LINE,
st_output TYPE st_impos,
t_output2 TYPE STANDARD TABLE OF st_impos WITH HEADER LINE,
st_output2 TYPE st_impos.
SELECT objnr gjahr kstar FROM coss
INTO CORRESPONDING FIELDS OF st_output
WHERE ( objnr LIKE 'NV%' OR
objnr LIKE 'PR%' ) AND
gjahr = year.
SELECT SINGLE projn from afvc into CORRESPONDING FIELDS OF st_output
WHERE objnr = st_output-objnr.
APPEND st_output to t_output.
ENDSELECT.
SORT t_output BY objnr.
DELETE ADJACENT DUPLICATES FROM t_output.
LOOP AT t_output into st_output.
SELECT objnr pspnr
INTO CORRESPONDING FIELDS OF st_output2
FROM prps
WHERE objnr = st_output-objnr
AND pspnr = st_output-pspnr.
SELECT SINGLE posnr from imzo into CORRESPONDING FIELDS OF st_output2
WHERE objnr = st_output2-objnr.
APPEND st_output2 to t_output2.
ENDSELECT.
ENDLOOP.
LOOP AT t_output2 to st_output2.
WRITE: st_output2-posnr.
ENDLOOP.
Edited by: Jacie Johns on Apr 23, 2009 11:26 PMHI John,
Try to avoid INTO CORRESPONDING FIELDS in SELECT statement.
As you are not using PSPNR and POSNR fields in the first SELECT statement. If you remove these fields, in structure, INTO CORRESPONDING FIELDS can be avoided. Create a separate structure with the fields that are required for T_OUTPUT table (i.e. create another structure with only first 4 fields, as T_OUTPUT1.
And as mentioned in your code,
WHERE objnr = st_output-objnr
AND pspnr = st_output-pspnr
in select statement, ST_OUTPUT-PSPNR value is not fetched in the previous select statements.
Create Another structure with fields OBJNR, PSPNR, POSNR for table T_OUTPUT2 to store the data from tables, PRPS and IMZO.
Use JOINS and FOR ALL ENTRIES to fetch the desired data.
The sample code is as follows:
===
TYPES: BEGIN OF ty_output1,
objnr TYPE coss-objnr,
gjahr TYPE coss-gjahr,
kstar type coss-kstar,
projn type afvc-projn,
END OF ty_output1,
BEGIN OF ty_output2,
objnr TYPE coss-objnr,
pspnr type prps-pspnr,
posnr type imzo-posnr,
END OF ty_output2,
BEGIN OF ty_output3,
objnr TYPE coss-objnr,
gjahr TYPE coss-gjahr,
kstar type coss-kstar,
projn type afvc-projn,
pspnr type prps-pspnr,
posnr type imzo-posnr,
END OF ty_output3.
data: year TYPE coss-gjahr value '2007'.
DATA:
wa_output1 TYPE ty_output1,
wa_output2 TYPE ty_output2,
wa_output3 TYPE ty_output3,
t_output1 TYPE STANDARD TABLE OF ty_output1 ,
t_output2 TYPE STANDARD TABLE OF ty_output2 ,
t_output3 TYPE STANDARD TABLE OF ty_output3..
SELECT cobjnr cgjahr ckstar aprojn FROM coss as c
INNER JOIN afvc as A on aobjnr = cobjnr
INTO table t_output1
WHERE ( c~objnr like 'NV%' or
c~objnr like 'PR%' ) and
c~gjahr = year.
SELECT pobjnr ppspnr i~posnr FROM prps as P
INNER JOIN imzo AS I on pobjnr = iobjnr
INTO TABLE t_output2
for all entries in table T_OUTPUT1
WHERE p~objnr = t_output1-objnr.
SORT : t_output1 BY objnr,
t_output2 BY objnr.
DELETE ADJACENT DUPLICATES FROM : t_output1 COMPARING objnr,
t_output2 COMPARING objnr.
LOOP AT t_output1 INTO wa_output1
READ TABLE t_output2 INTO wa_output2 WITH KEY objnr - wa_output1-objnr BINARY SEARCH.
if sy-subrc = 0.
MOVE <wa_output1 fiels> and <wa_output2 fields> to WA_OUTPUT3.
append wa_output3 to T_OUTPUT3.
endif.
ENDLOOP.
Hope this will solve your problem.
Regards,
Sai Prasad
Maybe you are looking for
-
Problem with editing Aperture photos with Photoshop Elements 10
When I try to edit with Photoshop Elements 10, Aperture makes a tiff file, starts Photoshop Elements 10 and get to a screen where I have a choice between "editing" or "managing" files. I select editing but when i finally get the editing screen there
-
Added new key figure in the report
Experts, I have added new key figure in the report .If i display this key figure value in the report it is populating correct value with ERROR(example 22.5 ERROR).The report is on the multiprovider .i have check the value for this in multiprovider it
-
Print for range of customers at a time in smartforms
hai all.. how can we get thr prints for range of customers in a smartforms. here iam giving range of customers kunnr-low and kunnr-high. i want the output should be prints form kunnr-low to kunnr-high. here iam wriing the bdc fro this smartof
-
How to change name of document in Pages for iOS?
I'm having problems with changing the name of documents in Pages for iOS. Any answers? I dont want all my documents to be Blank, Blank 2, and so on!!
-
Reg: XL Reporter Installation
I am trying to install XL Reporter in a client. The problem is during the installation in the database connecting step I am giving SQL Authentication and the SA password. On clicking next the system gives an error " The required MDAC has to be instal