Switch Case Statement Help...
Hello,
I am trying to get my pages through Case Statement But...
Can any one Help me.. here is my code..
This is my Buttons Code... My buttons are on 1st Frame of My FLA..
stop();
btn1.addEventListener(MouseEvent.CLICK, varTest);
btn2.addEventListener(MouseEvent.CLICK, varTest2);
function varTest(event:MouseEvent):void
var page = 1;
gotoAndStop(20);
function varTest2(event:MouseEvent):void
var page = 2;
gotoAndStop(20);
and this is my 20th frame code. (here I'm checking variable)
import flash.events.Event;
addEventListener(Event.ENTER_FRAME,checkCaseMe);
function checkCaseMe(event:Event)
switch (page)
case "1" :
info_txt.text = "page1";
break;
case "2" :
info_txt.text = "page1";
break;
default :
info_txt.text = "page00";
When I test the movie.. Error Occured (Scene 1, Layer 'Actions', Frame 21, Line 6 1120: Access of undefined property page. )
Can Anyone help please.. How do I correct this....???
Thanks...
You should learn to use the trace() function to help you troubleshoot code yourself. In each of your button functions include:
trace("btn clicked"); // will help you know for sure that the buttons are working
And in frame 20, you should add a trace as well to determine whether you actually get there when you think you don't...
trace("in frame 20");
Lastly, your code for frame 20 is likely not what you need for a couple of reasons...
1) If you think the ENTER_FRAME listener is used to detect/trigger when the timeline enters a frame, that is not what it does. What it does is continually process the function that it calls at the frame rate of the file. It is normally only used when you want to repeatedly trigger some functionality.
2) If you assign number values to the page variable, you do not want to use String values in your cases.
All you should need in frame 20 is...
switch (page)
case 1 :
info_txt.text = "page1";
break;
case 2 :
info_txt.text = "page1";
break;
default :
info_txt.text = "page00";
Similar Messages
-
Help with Switch-Case Statement
How do you get this in a switch-case statement or work with it?
if (age < 70) {
JOptionPane.showMessageDialog(null, "People that are below the 70s are nothing special.");
else if (age > 69 && age < 80) {
JOptionPane.showMessageDialog(null, "People that are in their 70s are called septuagenarian.");
else if (age > 79 && age < 90) {
JOptionPane.showMessageDialog(null, "People that are in their 80s are called octogenarian.");
else if (age > 89 && age < 100) {
JOptionPane.showMessageDialog(null, "People that are in their 90s are called nonagenarian.");
else (age > 99 && age < 110) {
JOptionPane.showMessageDialog(null, "People that are in their 100s are called centenarian.");
}Thanks~As per Java Specification, swtich case expects an integer and boolean cannot be used as param for switch.
In your case switch can be used like this.
int index = age /10;
switch(index) {
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
Your First case
break;
case 7:
your second case
break;
case 8:
third case
break;
case 9:
fourth case
break;
default:
fifth case
break;
Take note of the break statements. Its very important. But I wont prefer in this case. Code looks awkward and is not so meaningful..... -
DoGet method is called 2 times when a switch-case statement is used
Hello all,
I have a servlet that, when run from browser, runs the doGet method 2 times.
I have a switch case statement within the servlet and when I comment out this servlet, it runs 1 time as expected.
Here is the code:
public class RSSServlet extends HttpServlet {
/** Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
* @param request servlet request
* @param response servlet response
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("CALLED SERVLET");
response.setContentType("text/xml;charset=UTF-8");
PrintWriter out = response.getWriter();
DBQueriesRSS queries = new DBQueriesRSS();
String queryType = request.getParameter("queryType");
String strCount = request.getParameter("count");
int count = (strCount != null && !strCount.equalsIgnoreCase("null") && strCount.length() > 0) ?
Integer.parseInt(strCount) : 25;
if(queryType != null && !queryType.equalsIgnoreCase("null") && queryType.length() > 0) {
System.out.println("IN IF STATEMENT");
switch(Integer.parseInt(queryType)) {
case 1 : out.println(queries.getDefault(count));System.out.println("1"); break;
case 11: out.println(queries.getDefault(count));System.out.println("11"); break;
case 21: out.println(queries.getTopDaily(count));System.out.println("21"); break;
case 22: out.println(queries.getTopWeekly(count));System.out.println("22"); break;
case 23: out.println(queries.getTopMonthly(count));System.out.println("23"); break;
case 24: out.println(queries.getTopYearly(count));System.out.println("24"); break;
case 31: out.println(queries.getTopNDailyBW(count));System.out.println("31"); break;
case 32: out.println(queries.getTopNWeeklyBW(count));System.out.println("32"); break;
case 33: out.println(queries.getTopNMonthlyBW(count));System.out.println("33"); break;
case 34: out.println(queries.getTopNYearlyBW(count));System.out.println("34"); break;
default: out.println(queries.getTopWeekly(25));System.out.println("default"); break;
System.out.println("OUT OF SWITCH");
System.out.println("OUT OF IF");
out.close();
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/** Handles the HTTP <code>GET</code> method.
* @param request servlet request
* @param response servlet response
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
/** Handles the HTTP <code>POST</code> method.
* @param request servlet request
* @param response servlet response
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
/** Returns a short description of the servlet.
public String getServletInfo() {
return "Short description";
// </editor-fold>
} The results from running this servlet are:
http://localhost/proxy/RSSServlet??queryType=34&count=66
CALLED SERVLET
IN IF STATEMENT
34
OUT OF SWITCH
OUT OF IF
CALLED SERVLET
IN IF STATEMENT
34
OUT OF SWITCH
OUT OF IFAnyone see anything obvious?
TIA!in your case you want 'count' to be a class attribute rather than a local variable. But yes, incrementing it each time that the method is called will serve your purpose.
-
Can I test (junit) default case of switch-case statement ?
Hi,
I have a class which has switch-case statements and I am trying to junit test with 100% coverage. My switch-case workes based on enum values.
say my enum values are 1, 2.
switch(getEnumValues) {
case 1:
return "some value";
case 2:
return "some value";
default:
throw new UnsupportedOperationException("No such enum value supported.");
I have test case to test the case 1 and 2 but I am not able to test default case. Can anyone please let me know how can I right a junit test case for default case.
Edited by: TUIJAVADEV on Nov 4, 2008 4:15 PMyawmark wrote:
TUIJAVADEV wrote:
I have test case to test the case 1 and 2 but I am not able to test default case. Can anyone please let me know how can I right a junit test case for default case.If your enum values are ONE and TWO, and you have cases for both, then there is no "default case". There is nothing to test.
~If I'm reading the OP correctly, they're 1 and 2, not ONE and TWO. That is, not values of a Java enum.
If this is the case, then the easiest way to test the default case is to break the swtich out into a separate, package-accessible method that takes and arg and passes that onto the switch. (There may be variations on this, depending on how your code is structured.)
However, in a similar vein to what the others are saying, if you already know that you'll only ever have 1 and 2 by the time you get to the switch (maybe because the value comes from an argument to the enclosing method, and you've already unit tested that it appropriately throws an IllegalArgumentException when other values are passed, then there's no need to test the default.
Finally, though if it is ints 1 and 2, rather than a true enum, why not switch to an enum? -
case
when datepart(mm,[SDate]) between '9' and '11' and datepart(mm,[PDate] ) between '9' and '11'
Then 'Q1_'
when datepart(mm,[SDate]) between '12' and '02' and datepart(mm,[PDate] ) between '12' and '02'
Then 'Q2_'
when datepart(mm,[SDate]) between '03' and '05' and datepart(mm,[PDate] ) between '03' and '05'
Then 'Q3_'
when datepart(mm,[SDate]) between '06' and '08' and datepart(mm,[PDate] ) between '06' and '08'
Then 'Q4_'
else 'N/A' end as QTR
from DDA_2015_FSR
Datatype for SDate and Pdate
2014-09-01 00:00:00
I need help with above case statement, When I run the case statement I get 'N/A FSY_2015 ' When I add the following where clause to validate the results. In my table I do have records for all four quarters, Except Q1, all other rows I get 'N/A
FSY_2015 '
Am i missing something? Can someone help me here?
where
datepart(m,[SDate])
between
'12'
and
'02'
and
datepart(m,[PDate]
between
'12'
and
'02'
FMThere is no CASE statement in SQL; it is a CASE expression. Big difference.
Since SQL is a database language, we prefer to do look ups and not calculations. They can be optimized while temporal math messes up optimization. A useful idiom is a report period calendar that everyone uses so there is no way to get disagreements in the DML.
The report period table gives a name to a range of dates that is common to the entire enterprise.
CREATE TABLE Something_Report_Periods
(something_report_name CHAR(10) NOT NULL PRIMARY KEY
CHECK (something_report_name LIKE <pattern>),
something_report_start_date DATE NOT NULL,
something_report_end_date DATE NOT NULL,
CONSTRAINT date_ordering
CHECK (something_report_start_date <= something_report_end_date),
etc);
These report periods can overlap or have gaps. I like the MySQL convention of using double zeroes for months and years, That is 'yyyy-mm-00' for a month within a year and 'yyyy-00-00' for the whole year. The advantages are that it will sort with the ISO-8601
data format required by Standard SQL and it is language independent. The pattern for validation is '[12][0-9][0-9][0-9]-00-00' and '[12][0-9][0-9][0-9]-[01][0-9]-00'
--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 -
Case statement help needed bit tricky
I have a requirement for a Column Quarters which will idenitfy records based on their service and paid paids.
Output of Column should be
QTR
FSY2015Q1
Our Quarters start like this Q1= 9/1 /2014-11.30.2014 , Q2 12/1/2014 -02/28/2015, Q3: 3/1/2015 - 05/31/2015 Q4:06/01/2015 -08/31/2015.
With the below Case statement records that hit Q1 should be for the FSY upcoming. records in Sept, Oct, November of 2014, would actually be for FSY15Q1 (not FSY14Q1). How can i correct
this ?
case
when datepart(mm, Service_Through_Date ) between '9' and '11' and datepart(mm, c.paid_date ) between '9' and '11'
Then 'Q1 '
when datepart(mm, Service_Through_Date ) in ('01','02', '12' ) and datepart(mm, paid_date ) in ('01','02' , '12' )
Then 'Q2 '
when datepart(mm, Service_Through_Date ) between '03' and '05' and datepart(mm, paid_date ) between '03' and '05'
Then 'Q3 '
when datepart(mm, Service_Through_Date ) between '06' and '08' and datepart(mm, paid_date ) between '06' and '08'
Then 'Q4 '
else ' ' end + ' ' + 'FSY ' + '' + cast(datepart(Year, Service_Through_Date)as char(7)) as QTR
FMYour best bet here is going to be to create a calendar table, which has your quarters in it.
I wrote an article on them here: http://social.technet.microsoft.com/wiki/contents/articles/29260.tsql-calendar-functions-and-tables.aspx.
For your particular scenario you'll need to add a column to the existing code, something like this:
SELECT CASE WHEN DATEPART(MONTH,@date) IN (9,10,11) THEN 'FSY'+RIGHT(YEAR(@date)+1,2)+'Q1'
WHEN DATEPART(MONTH,@date) IN (12) THEN 'FSY'+RIGHT(YEAR(@date)+1,2)+'Q2'
WHEN DATEPART(MONTH,@date) IN (1,2) THEN 'FSY'+RIGHT(YEAR(@date),2)+'Q2'
WHEN DATEPART(MONTH,@date) IN (3,4,5) THEN 'FSY'+RIGHT(YEAR(@date),2)+'Q3'
WHEN DATEPART(MONTH,@date) IN (6,7,8) THEN 'FSY'+RIGHT(YEAR(@date),2)+'Q4'
END AS fiscalQuarterName
Once you have this column, you can simply join to the calendar table:
SELECT service_through_date, paid_date, sc.fiscalQuarterName, pc.fiscalQuarterName
FROM myTable t
INNER JOIN calendar sc
ON t.service_through_date = c.today
INNER JOIN calendar pc
ON t.paid_date = pc.today
If you can't, or don't want to impliment this, you could solve the issue in your cast statement by moving the year into the CASE, like this:
SELECT CASE WHEN DATEPART(MONTH, Service_Through_Date ) BETWEEN 9 AND 11 AND DATEPART(MONTH, c.paid_date) BETWEEN 9 AND 11 THEN 'FSY'+RIGHT(YEAR(Service_Through_Date)+1,2)+'Q1'
WHEN DATEPART(MONTH, Service_Through_Date ) = 12 AND DATEPART(MONTH, c.paid_date) = 12 THEN 'FSY'+RIGHT(YEAR(Service_Through_Date)+1,2)+'Q2'
WHEN DATEPART(MONTH, Service_Through_Date ) BETWEEN 1 AND 2 AND DATEPART(MONTH, paid_date) BETWEEN 1 AND 2 THEN 'FSY'+RIGHT(YEAR(Service_Through_Date),2)+'Q2'
WHEN DATEPART(MONTH, Service_Through_Date ) BETWEEN 3 AND 5 AND DATEPART(MONTH, paid_date) BETWEEN 3 AND 5 THEN 'FSY'+RIGHT(YEAR(Service_Through_Date),2)+'Q3'
WHEN DATEPART(MONTH, Service_Through_Date ) BETWEEN 6 AND 8 AND DATEPART(MONTH, paid_date) BETWEEN 6 AND 8 THEN 'FSY'+RIGHT(YEAR(Service_Through_Date),2)+'Q4'
ELSE 'FSY'+RIGHT(YEAR(Service_Through_Date),2)
END
Don't forget to mark helpful posts, and answers. It helps others to find relevant posts to the same question. -
Case Statement Help needed [Nested]
Hi all,
I need to write a case statement my requirement is
ENC.EET.40 E_Disposition populated from either “E_ Status” field of HP_Response_table, “File Status” of HP _TTT_Response_Table,
or “E_Status” of DDA_R_Table. If no data in any of these fields, default to “Submitted”
So my case stmt should look like
case when E_Status is null then 'SUBMITTED'
when e_status is null then 'Submitted'
when FileStatus is null then 'Submitted'
Else case when E_status is not null then ............?????????????
else case when
Im Confused.. Can someone help me ?
FMselect ...
coalesce (resp.E_Status, resp2.FileStatus, dda.E_Status, 'Submitted')
from ...
Obviously I have used alias for the respective tables according to your logic. -
Formatted search case statement help
Hi all,
I am trying to write a case statement in a formatted search, but am running into an error when I add a condition involving the item code. The code works find with the first WHEN statement involving the customer code $[$4.0.0] however, I receive an internal error when I add the second part involving the item code $[$38.1.1] Please advise.
SELECT
CASE WHEN $[$4.0.0] = 'C00023'
THEN 'E002'
WHEN $[$38.1.1] = 'ItemA'
THEN 'J002'
END
THank you!
JaneHi Jane,
Where do you assign this FMS? If it is on the header, the second condition will not work. If it is line level, try change it to $[$38.1.0\].
Thanks,
Gordon -
Conditional case statement help.!
Hello Forum Members,
I have a table with stores order along with order dates and other information. I have a requirement to write a query to get the nominations from that order's table according to the logic mentioned below.
Nom1 = Initial order date and next order within 7 days from initial order date then its considered as R1
Nom2 = next activity within 7 seven on the same ord_id from its R1 date , this goes on as the order dates increases for same or single ord_no
Final Rn is Count (Rn)
Rn %-- Count(Rn) / Count Distinct ( ord_no ) * 100
Example data output:
ORD_DATE
ORD_ID
1_of_x
2_of_x
3_of_x
4_of_x
5_of_x
6_of_x
Final RnX
Rn%
7/10/2013
10095V1
1
0
0
0
0
0
8/3/2013
10095V1
1
0
0
0
0
0
8/8/2013
10095V1
0
1
0
0
0
0
8/12/2013
10095V1
0
0
1
0
0
0
9/6/2013
10095V1
1
0
0
0
0
0
DDL:
create table xx_ord_noms
ord_no varchar(30),
ord_date date,
ord_id varchar2(30)
Sample Data:
INSERT INTO xx_ord_noms (ord_no, ord_date, ord_id) VALUES ('10091', TO_DATE('07/10/2013','MM/DD/YYYY'), '10091');
INSERT INTO xx_ord_noms (ord_no, ord_date, ord_id) VALUES ('10091', TO_DATE('08/03/2013','MM/DD/YYYY'), '10091');
INSERT INTO xx_ord_noms (ord_no, ord_date, ord_id) VALUES ('10091', TO_DATE('08/08/2013','MM/DD/YYYY'), '10091');
INSERT INTO xx_ord_noms (ord_no, ord_date, ord_id) VALUES ('10091', TO_DATE('08/12/2013','MM/DD/YYYY'), '10091');
INSERT INTO xx_ord_noms (ord_no, ord_date, ord_id) VALUES ('10091', TO_DATE('09/06/2013','MM/DD/YYYY'), '10091');
commit;
I was planning to doing something like this but I am not getting the logic for R1 .. R7
select ord_no,
ord_date,
ord_id,
prev_dt,
(to_date(ord_date) - to_date(prev_dt)) data_diff,
case
when prev_dt is null or
(to_date(ord_date) - to_date(prev_dt)) < 7 then
'R1'
when (to_date(ord_date) - to_date(prev_dt)) > 7 THEN
'R2'
ELSE
nULL
END
FROM (select a.*,
(SELECT MAX(tmp2.ord_date)
FROM xx_ord_noms tmp2
WHERE a.ord_id = tmp2.ord_id
AND tmp2.ord_date < a.ord_date) prev_dt
from xx_ord_noms a);
Could someone give me advises or suggestions on how we can get the expected output.
Thanks in advance.LAG and LEAD are good when you want to look forward or back a fixed number of rows, but in this case you don't know how far back you'll need to go.
I've got a solution. it calculates the Rn as a number, not a column position, but you can transform that with CASE statements if you want. I did it in two main steps:
First I calculated the Rn by comparing the date of the current and previous row. To do that, I generated a row number using the row_number() analytic function:
select ord_no,
ord_date,
ord_id,
numrow
, Rn
from xx_ord_noms
model
partition by (ord_no)
dimension by (row_number() over (partition by ord_no order by ord_date) numrow)
measures (ord_date, 0 Rn, ord_id )
rules update
rn[1] = 1,
rn[ANY] = CASE when trunc(ord_date[cv()]) - trunc(ord_date[cv() - 1]) < 7 then rn[cv()-1]+1 else 1 end
ORD_NO ORD_DATE ORD_ID NUMROW RN
10091 10-Jul-2013 00:00:00 10091 1 1
10091 03-Aug-2013 00:00:00 10091 2 1
10091 08-Aug-2013 00:00:00 10091 3 2
10091 12-Aug-2013 00:00:00 10091 4 3
10091 06-Sep-2013 00:00:00 10091 5 1
Then I needed to identify all the rows of each series. I defined firstDt as the date of the first item in the series:
firstDt[1] = ord_date[cv()]
firstDt[ANY] = CASE when rn[cv()]= 1 then ord_date[cv()] else firstDt[cv()-1] end
With that, the FinalRn is just an analytic max(rn) over (partition by firstDt)
I'm not clear on what R% is. Your descriptions are unclear and I think they're inconsistent.
select ord_no, ord_date, ord_id
, Rn, finalRn, 100*finalRn/totCnt PCT1, 100 * totRn/totCnt PCT2
, totRn
from xx_ord_noms
model
partition by (ord_no)
dimension by (row_number() over (partition by ord_no order by ord_date) numrow)
measures (ord_date, 0 Rn, ord_id, to_date(null) firstDt, 0 finalRn, 0 totRn, 0 totCnt )
rules upsert all
rn[1] = 1
, rn[ANY] = CASE when trunc(ord_date[cv()]) - trunc(ord_date[cv() - 1]) < 7 then rn[cv()-1]+1 else 1 end
, firstDt[1] = ord_date[cv()]
, firstDt[ANY] = CASE when rn[cv()]= 1 then ord_date[cv()] else firstDt[cv()-1] end
, finalRn[ANY] = max(rn) over (partition by firstDt)
, totCnt[ANY] = count(*) over()
, totRn[ANY] = count(case when rn = 1 then 1 else null end) over ()
ORD_NO ORD_DATE ORD_ID RN FINALRN PCT1 PCT2 TOTRN
10091 10-Jul-2013 00:00:00 10091 1 1 20 60 3
10091 03-Aug-2013 00:00:00 10091 1 3 60 60 3
10091 08-Aug-2013 00:00:00 10091 2 3 60 60 3
10091 12-Aug-2013 00:00:00 10091 3 3 60 60 3
10091 06-Sep-2013 00:00:00 10091 1 1 20 60 3
Regards,
David -
Need help about switch & case statements
Dear friends
I am new student of Java
Our University gave us project to make a program. Here is the program:
a- Write a java program ,so the user can input the monthly salary then compute the net salary of an employee after deducting the tax ,use the following table to calculate the tax .Note use switch statement .
Annual salary Tax
100- 999 0
1000- 1999 5%
2000- 3999 7%
4000- 7000 10%
7000 13%Please help me how could I use switch statement.
All I know about switch statement is that I have use Integers for selection.
Kindly help me. I have only 2 days to submit my assignment.
Thanks in Advance
Edited by: syedejaz on Aug 13, 2008 8:09 AM
Edited by: syedejaz on Aug 13, 2008 8:10 AMHello every body:
I tried to make my first program using if then else but the problem is that no calcuation is happinig
/* TMA01 ITC250, Part-III, a
Program which gets input monthly salary and shows net salary after deducting given tax.
File: netSalary.java
import javax.swing.*;
import java.text.*;
public class netSalary {
public static void main(String[] args) {
int Salary=0,Tax=0,monthlySalary=0;
monthlySalary= Integer.parseInt(JOptionPane.showInputDialog(null, "Enter Monthly Salary:"));
if ((monthlySalary>=100) && (monthlySalary<=999)) {
Tax = (monthlySalary*(0/100));
Salary = (monthlySalary-Tax);
JOptionPane.showMessageDialog(null, "Net Salary is:" +Salary);
} else if ((monthlySalary>=1000) && (monthlySalary<=1999)) {
Tax = (monthlySalary*(5/100));
Salary = (monthlySalary-Tax);
JOptionPane.showMessageDialog(null, "Net Salary is:" +Salary);
} else if (monthlySalary>=2000 && monthlySalary<=3999) {
Tax = (monthlySalary*(7/100));
Salary = (monthlySalary-Tax);
JOptionPane.showMessageDialog(null, "Net Salary is:" +Salary);
} else if (monthlySalary>=4000 && monthlySalary<=7000) {
Tax = (monthlySalary*(10/100));
Salary = (monthlySalary-Tax);
JOptionPane.showMessageDialog(null, "Net Salary is:" +Salary);
} else {
Tax = (monthlySalary*(13/100));
Salary = (monthlySalary-Tax);
JOptionPane.showMessageDialog(null, "Net Salary is:" +Salary);
} The tax is not detuting. please tell me the mistake
Edited by: syedejaz on Aug 13, 2008 2:49 PM -
Hi Gurus,
I have a requirement like this,
I want to extract the service request which closed in last month and opened in the last three months of closing month (close month -3).
When open month is previous month and timestampdiff(tsi_month, open month(close month), openmonth(close month -3) then nbr of SRs.
How do i bring the close month in open month value.
ThanksI am trying to enter the following statement for the above requirment
CASE WHEN "Core"."Close Date"."Close Month" = VALUEOF(PREVIOUS_MONTH) AND TimeStampDiff(SQL_TSI_Month, "Core"."Open Date"."Open Month" = VALUEOF(PREVIOUS_MONTH) , "Core"."Open Date"."Open Month" = VALUEOF(PREVIOUS_MONTH) - 3 ) <= 3 THEN 1 ELSE 0 END
When i say okay, it gives the error
[nQSError: 27002] Near <=>: Syntax error [nQSError: 26012] .
Can anyone help me out.
Thanks -
SQL Case statement Help....
Hi , I have to Compare two columns to see if they are matching or not....and give the count() of overrides if they are not matching/
I have got that with the below SQL:
Count of Overrides =
select count(Case when Col_1 != Col_2 then 1 else null end) Overrides
from table_1, table_2
where table_1.id = table_2.id
But now i have to look at two columns and get the count()
I have
col_1 and col_2 in table_1 and
col_3 and col_4 in table_2
(I have to compare col_1 with col_2 and...... col_3 with col_4 and if either of them is not matching.... count it as an override
Will the following SQL return correct values?
Count of Overrides =
Select
Count( Case when (col_1 ! = col_2) or (col_3 != col_4) then 1 else null end) Overrides
from table_1, table_2
where table_1.id = table_2.id
Thanks"yes, it can be rewritten as a decode. but why bother?"
Well, although I do like Sy's code better, the decode version does naturally handle NULLs unlike the case.
SQL> WITH t AS (
2 SELECT 1 col_1, 1 col_2, 2 col_3, 2 col_4 FROM dual UNION ALL
3 SELECT 1, 1, 2, 3 FROM dual UNION ALL
4 SELECT 1, 2, 3, 3 FROM dual UNION ALL
5 SELECT null, 1, 2, 2 FROM dual UNION ALL
6 SELECT 1, 1, 2, null FROM dual UNION ALL
7 SELECT 1, 2, 3, 4 FROM dual)
8 SELECT col_1, col_2, col_3, col_4,
9 CASE WHEN (col_1 ! = col_2) or (col_3 != col_4) then 1 else null end Ocase,
10 DECODE(col_1, col_2, DECODE(col_3, col_4, NULL, 1), 1) odecode
11 FROM t;
COL_1 COL_2 COL_3 COL_4 OCASE O
1 1 2 2
1 1 2 3 1 1
1 2 3 3 1 1
1 2 2 1
1 1 2 1
1 2 3 4 1 1John -
Problems with a result in a switch/case control statement
I am having troubles with a switch/case statement in which I am trying to get a result returned from different operators. The problem is that the result always returns 0 no matter what I put in the driver class.
The class where the result needs to be returned looks like this:
public class Calculator
private int num1;
private int num2;
private char operator;
private int result;
public Calculator(int num1, char operator, int num2)
this.num1 = num1;
this.operator = operator;
this.num2 = num2;
} // end constructor
public int getNum1()
return num1;
public char getOperator()
return operator;
public int getNum2()
return num2;
public int getResult()
return result;
public int calculate()
switch(operator)
case '+':
int result = num1 + num2;
break;
} // end case '+'
case '-':
int result = num1 - num2;
break;
} // end case '-'
case '*':
int result = num1 * num2;
break;
} // end case '*'
case '/':
int result = num1 / num2;
break;
} // end case '/'
case '%':
int result = num1 % num2;
break;
} // end case '%'
} // end switch
return result;
public String toString()
String message = (num1) + " " + (operator)
+ " " + (num2) + " " + "=" + " " + result + "\n";
return message;
} // end class
The driver class looks like this:
import javax.swing.JOptionPane;
import java.lang.StringBuffer;
public class CalculatorApp
public static void main (String[] args) // begin main
String choice = "";
while (!(choice.equalsIgnoreCase("x"))) // begin while loop
String number1 = JOptionPane.showInputDialog(
"Enter a positive integer: ");
String operatorInput = JOptionPane.showInputDialog(
"Enter operator (+, -, *, /, %): ");
String number2 = JOptionPane.showInputDialog(
"Enter another positive integer: ");
int num1;
char operator;
int num2;
num1 = Integer.parseInt(number1);
operator = operatorInput.charAt(0);
num2 = Integer.parseInt(number2);
Calculator calculator = new Calculator(num1, operator, num2);
String message = calculator.toString() + "\n"
+ "Press Enter to conitnue or 'x' to exit.";
choice = JOptionPane.showInputDialog(message);
} // end while loop
System.exit(0);
} // end main
any help would be wonderful! I don't know why the result returned is always 0 but it is. Thanks!
dragwitThe previous poster is correct. You never call the calculate method. If you don't call it, no one's going to call if for you. This stuff doesn't work by magic. I think you've misunderstood your prof's intent in this regard.
However, it still won't work with the changes previously suggested, because declaring an int result in the calculate method will hide the instance field of the same name, which is what your getResult() method retrieves. Don't delare result at all in your calculate method.
That said, it would be architecturally a lot better if the calculate method returned the result rather than storing it back into the instance. -
Troubles with a switch case and final expression?
Been developing C/C++ for quite a while and still new to Java, and struggling with even the simplest things ... Why isnt this switch/case working?
have some final "variable" declared in a class contating "constants" like this ...
public class CConstants {
public static final int MY_CONSTANT1 = 0x01;
}Now, If I'm trying to use "MY_CONSTANT1" in a case stateent, I get the error "constant expression required" ?
CConstants c = new CConstants();
switch(condition){
case c.MY_CONSTANT1: { //do some work; break; }
default: { }
}I thought this would be a nice idea to increase readability as there will be a long switch/case statement.
Please help!
Edited by: George.F on Sep 3, 2009 3:07 AM
Edited by: George.F on Sep 3, 2009 3:08 AMYou should refer to that constant as CConstants.MY_CONSTANT1.
Refering to it via a reference to CConstants is possible but strongly discouraged (infact I'd make CConstants non-instantiable by adding a private constructor).
Other than that your code should work.
Could you post a SSCCE that demonstrates your problem. -
Switch/Case: How to test byte values in hex format
OK, this may be a silly question, but being new to Java, I can't seem to get this to work.
I have a byte value that I want to test in a switch/case statement. The value was assigned to the byte in hexadecimal format. However, testing only works if I use the decimal value of the byte!
What's even stranger: It does work in a simple if/else statement. In my debugging attempts, I discovered this using the following code:
//*temporary debug routine
memoryCells[0] = (byte) 0x86; //LDA
if(memoryCells[0] == (byte) 0x86)
System.err.println("byte recognized as hexadecimal!");
else
if(memoryCells[0] == -122)
System.err.println("byte recognized as decimal!"); So, this works in an ordinary if/else statement, but why doesn't it also work in the complex switch/case statement? Snippet below:
switch (currentOpcode)
case (byte) 0x86:
//*LDA immediate (2 bytes, 2 cycles)
registerA = b;
currentOpcode = 0x00;
cycleCounter = 0;
break;
}Thanks in advance for any suggestions...public static void main(String[] args) throws Exception {
byte test = (byte)0x86;
switch(test)
case (byte)0x86:
System.out.println("Success");
break;
default:
System.out.println("ooops");
}This works for me.
~Tim
Maybe you are looking for
-
Use fieldname into the tablename of a select-statement
I have made the next table : SQL> desc ttcafo001120; Name Null? Type T$GCMP NOT NULL NUMBER T$CUNO NOT NULL CHAR(6) T$NAMA NOT NULL CHAR(35) where t$gcmp is always a number of 3 postions. I want to make a program that look like this : When t$gcmp = 1
-
IPod Not recognized by XP, Slightly different from others
I am having a similiar problem to many peoples. Early this morning I connected my iPod and there were no problems, later in the day I tried and for no apparent reason XP will not recognize it. Not only this but it will also not charge when connected
-
How to get rid of compound value in hierarchy
Hello, I want to use hierarchy of cost centers in bex report. I don't want to see the compound value 1000 (controlling area) as part of the keys. For example, instead of - 1000IS3 1300 1400 I want to see - IS3 1300 1400 1300 and
-
18 month old phone. Plugged in to top up the charge. Usual charger, usual cable. 20 minutes later smoke and meltdown. USB port dripping melted plastic. Burnt finger. A quick goggle and a search on here. I am not alone it seems. Does anyone have a tec
-
Can a object created using static keyword be recreated? Singleton Pattern
Hi All To implement a Singleton I can use the following code public Singleton { private Singleton(){ private static final s_instance = new Singleton(); public Singleton getInstance(){ return s_instance; Now if the Class Singleton gets unloaded during