Search Results

Search found 6988 results on 280 pages for 'if else statement'.

Page 28/280 | < Previous Page | 24 25 26 27 28 29 30 31 32 33 34 35  | Next Page >

  • 1 error with an array "missing return statement"

    - by danielit0w
    import javax.swing.JOptionPane; public class Mate { double suma (double x1,double x2) {return x1+x2;} double suma (double x1,double x2,double x3) {return x1+x2+x3;} double suma (int num [ ]) {int i=num.length; int j=0; int s=0; for(j=0;j < i;j++) {return (double)(s);}}} // here appears the error "missing return statement" class AplicacionMate {public static void main (String arg []) {int n[ ]={5,4,3,2,1}; double r=0.0; Mate m=new Mate ( ); r=m.suma(5,4); JOptionPane.showMessageDialog(null,"La suma 1="+r); r=m.suma(5,5,4); JOptionPane.showMessageDialog(null,"La suma 2="+r); r=m.suma(n); JOptionPane.showMessageDialog(null,"La suma del arreglo="+r); System.exit(0);}}

    Read the article

  • Oracle 10.1 and 11.2 produce different XML using the same statement

    - by MindFyer
    I am migrating a database from Oracle 10.1 to 11.2 and I have the following problem. The statement SELECT '<?xml version="1.0" encoding="utf-8" ?>' || (Xml).getClobVal() AS XmlClob FROM ( SELECT XmlElement( "Element1", ( SELECT XmlAgg(tpx.Xml) FROM ( SELECT XmlElement("Element3",XmlForest('content' as Element4)) AS Xml FROM dual ) tpx ) AS "Element2" ) AS Xml FROM dual ) On the original 10.1 database produces XML like this... <?xml version="1.0" encoding="utf-8"?> <Element1> <Element2> <Element3> <ELEMENT4>content</ELEMENT4> </Element3> </Element2> </Element1> On the new 11.2 system it looks like this... <?xml version="1.0" encoding="utf-8"?> <Element1> <Element3> <ELEMENT4>content</ELEMENT4> </Element3> </Element1> Is there some environmental variable I am missing that tells Oracle how to format its XML. There are hundreds of thousands of lines of PL/SQL in the database; it would be a mammoth task to rewrite if it turned out they had changed they way Oracle formats XML between versions. Hopefully someone has come accross this before. Thanks

    Read the article

  • Multiple Exception Handling in one if statement [closed]

    - by JA3N
    I am having trouble with throwing and catching exceptions. Here is the code for assignSeat(), assignSeat is called in a try block in another class. void assignSeat(String passengerName, int x, int y) throws SeatOccupiedException, InvalidPassengerNameException { Seat tSeat = airplane.getSeat(x,y); if (tSeat!=null) { if (passengerName.isEmpty() || !passengerName.matches("[a-zA-Z]+")) { throw new InvalidPassengerNameException(); } //excluded else if else if (foundPassenger(passengerName)) { airplane.seatList.get(airplane.seatNumber(passengerName)).unOccupy(); tSeat.occupy(); for (int i = 0; i<passengers.size();i++) if (passengers.get(i).getName().equals(passengerName)) passengers.get(i).changeSeat(tSeat.getSeatName()); } else if (!tSeat.occupied) { tSeat.occupy(); addPassenger(passengerName, tSeat.getSeatName()); } else if (tSeat.occupied) { throw new SeatOccupiedException(); } } and here is the code that calls assignSeat() and is in another class (I won't copy the whole class to make it look clearer) if (afComp.currentAF != null) { try { afComp.currentAF.assignSeat(nameField.getText(), x, y); //<-Problem here, "Unhandled exception type SeatOccupiedException" } catch (SeatOccupiedException exception) //<-Problem here, "Unreachable catch block, This exception is never thrown from the try statement body" { } catch(InvalidPassengerNameException exception) //<-No problems. { } } Whats wrong with the try block? why won't it throw the SeatOccupiedException? Exception classes: SeatOccupied: package a2; public class SeatOccupiedException extends Exception { public SeatOccupiedException(){} } InvalidPassengerName: package a2; public class InvalidPassengerNameException extends Exception { public InvalidPassengerNameException() {} } Every class I have is in package a2 imports for class that calls assignSeat package a2; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.awt.event.MouseEvent; import java.awt.BorderLayout; import javax.swing.*; import javax.swing.event.*; imports for class that has assignSeat package a2; import java.util.ArrayList;

    Read the article

  • Use string to store statement (or part of a statement), and then add it to the code

    - by Dean
    I use multidimensional arrays to store product attributes (well Virtuemart does, to be precise). When I tried to echo the sub-arrays value, if the sub-array did not exist PHP threw: Fatal error: Cannot use string offset as an array To get around this, I attempted to create a function to check on every array level if it is an actual array, and if it is empty (when trying on the whole thing at once such as: is_array($array['level1']['level2']['level3']), I got the same error if level1 or level2 are not actual arrays). This is the function ($array contains the array to check, $array_levels is an array containing the names of the sub-arrays, in the order they should apper): function check_md_array($array,$array_levels){ if(is_array($array)){ $dimension = null; //This will store the dimensions string foreach($array_levels as $level){ $dimension .= "['" . $level . "']"; //Add the current dimension to the dimensions string if(!is_array($array/* THE CONTENT OF $dimension SHOULD BE INSERTED HERE*/)){ return false; } } return true; } } How can I take the string contained in $dimensions, and insert it into the code, to be part of the statement?

    Read the article

  • Is there programming language with better approach for switch's break statements ?

    - by Vitaly Polonetsky
    It's the same syntax in a way too many languages: switch (someValue) { case OPTION_ONE: case OPTION_LIKE_ONE: case OPTION_ONE_SIMILAR: doSomeStuff1(); break; // EXIT the switch case OPTION_TWO_WITH_PRE_ACTION: doPreActionStuff2(); // the default is to CONTINUE to next case case OPTION_TWO: doSomeStuff2(); break; // EXIT the switch case OPTION_THREE: doSomeStuff3(); break; // EXIT the switch } Now all you know that break statements are required, because the switch will continue to the next case when break statement is missing. We have an example of that with OPTION_LIKE_ONE, OPTION_ONE_SIMILAR and OPTION_TWO_WITH_PRE_ACTION. The problem is that we only need this "skip to next case" very very very rarely. And very often we put break at the end of case. It very easy for a beginner to forget about it. And one of my C teachers even explained it to us as if it was a bug in C language (don't want to talk about it :) I would like to ask if there are any other languages that I don't know of (or forgot about) that handle switch/case like this: switch (someValue) { case OPTION_ONE: continue; // CONTINUE to next case case OPTION_LIKE_ONE: continue; // CONTINUE to next case case OPTION_ONE_SIMILAR: doSomeStuff1(); // the default is to EXIT the switch case OPTION_TWO_WITH_PRE_ACTION: doPreActionStuff2(); continue; // CONTINUE to next case case OPTION_TWO: doSomeStuff2(); // the default is to EXIT the switch case OPTION_THREE: doSomeStuff3(); // the default is to EXIT the switch } The second question: is there any historical meaning to why it is like this in C? May be continue to next case was used far more often than we use it these days ?

    Read the article

  • JavaScript, jQuery, XML - if statement not executing for unknown reason

    - by Jack Roscoe
    Hi, I have a 'for' loop which extracts data from an XML document and adds it into some JavaScript objects, each time the loop executes I want it to run a certain function depending on the value of the attribute 'typ' which is being retrieved from the xml. Currently, the data from the XML is successfully being parsed, which is proven by the first 'alert' you can see which produces the correct value. However, neither of the 'alert' lines in the 'if' statement lower down are being executed and as a result I cannot test the 'ctyp3' function which is supposed to be called. Where have I gone wrong? for (j=0; j<arrayIds.length; j++) { $(xml).find("C[ID='" + arrayIds[j] + "']").each(function(){ // pass values questions[j] = { typ: $(this).attr('typ'), width: $(this).find("I").attr('wid'), height: $(this).find("I").attr('hei'), x: $(this).find("I").attr('x'), y: $(this).find("I").attr('x'), baC: $(this).find("I").attr('baC'), boC: $(this).find("I").attr('boC'), boW: $(this).find("I").attr('boW') } alert($(this).attr('typ')); if ($(this).attr('typ') == '3') { ctyp3(x,y,width,height,baC); alert('pass'); } else { // Add here alert('fail'); } }); }

    Read the article

  • mysql_affected_rows() returns 0 for UPDATE statement even when an update actually happens

    - by Alex Moore
    I am trying to get the number of rows affected in a simple mysql update query. However, when I run this code below, PHP's mysql_affected_rows() always equals 0. No matter if foo=1 already (in which case the function should correctly return 0, since no rows were changed), or if foo currently equals some other integer (in which case the function should return 1). $updateQuery = "UPDATE myTable SET foo=1 WHERE bar=2"; mysql_query($updateQuery); if (mysql_affected_rows() > 0) { echo "affected!"; } else { echo "not affected"; // always prints not affected } The UPDATE statement itself works. The INT gets changed in my database. I have also double-checked that the database connection isn't being closed beforehand or anything funky. Keep in mind, mysql_affected_rows doesn't necessarily require you to pass a connection link identifier, though I've tried that too. Details on the function: mysql_affected_rows Any ideas? SOLUTION The part I didn't mention turned out to be the cause of my woes here. This PHP file was being called ten times consecutively in an AJAX call, though I was only looking at the value returned on the last call, ie. a big fat 0. My apologies!

    Read the article

  • Using array instead of lots of db queries in PHP

    - by Tural Teyyuboglu
    My function looks like that. It works but does lots of work (recursively calls itself and does lots of db queries.). There must be another way to do same thing but with array (with one query). I can't figure out how to modify this function to get it work with array. Please help. function genMenu($parent, $level, $menu, $utype) { global $db; $stmt=$db->prepare("select id, name FROM navigation WHERE parent = ? AND menu=? AND user_type=?") or die($db->error); $stmt->bind_param("iii", $parent, $menu, $utype) or die($stmt->error); $stmt->execute() or die($stmt->error); $stmt->store_result(); /* bind variables to prepared statement */ $stmt->bind_result($id, $name) or die($stmt->error); if ($level > 0 && $stmt->num_rows > 0) { echo "\n<ul>\n"; } while ($stmt->fetch()) { echo "<li>"; echo '<a href="?page=' . $id . '">' . $name . '</a>'; //display this level's children genMenu($id, $level+1, $menu, $utype); echo "</li>\n\n"; } if ($level > 0 && $stmt->num_rows > 0) { echo "</ul>\n"; } $stmt->close(); }

    Read the article

  • How to print contents from a session variable by looping in a foreach statement

    - by itsover9000
    im trying to write a code where can print and loop through the contents of my session variable by using a foreach statement here is my code <form class="form form-inline" method = "post" action="reportmaker.php"> <select name="rfield"> <option value="">--Select Field--</option> <?php $sc2=mysql_query("SELECT * from searchcolumn s left join report_fields r on s.scol_id=r.field_id where s.category != 'wh'"); foreach($sc2 as $sc){ ?> <option value="<?php echo $sc[advsearch_col]; ?>"><?php echo $sc[advsearch_name]; ?></option> <?php } ?> </select> <button type="submit" value = "submit" id="add" name="add" class="btn pull-right">Add More</button> </form> <?php if(isset($_POST['add'])) { $_SESSION['temp'][]=$_POST['rfield']; } if($_SESSION[temp][]!=""){ foreach($_SESSION[temp][] as $temp) { echo $temp; } } ?> the error that appears with this code is Fatal error: Cannot use [] for reading the line where the error is is this if($_SESSION[temp][]!=""){ i need to print the contents of the session array and this is the only way i know how is there a way to fix this? thanks =========EDIT thanks for the answers guys i finally got it

    Read the article

  • Using Enum in Hibernate causes select followed by an update statement

    - by Leonardo
    Hi all, I have a mapped entity wich has an enum property. By loking at log file, whenever I run a select statement on such entity, the result is an immediately following update. For example if my result set contains 100 records, then I have: [INFO org... select...] [INFO org... update... where id=?] [INFO org... update... where id=?] .... repeated 100 times If I mark the property as update=false the problem disappear. The enum is assigned trough an enum converter class, which I copied from a well known book. So I don't know if I just copy and paste the code. Here it is how is declared on hbm file. <typedef class="mypackage.HbnEnumConverter" name="the_type"> <param name="enumClassname">mypackage.TheType</param> </typedef> Can you point out a direction to investigate this ? Beside, what are the consequences of having update=false on hibernate field ? thanks

    Read the article

  • Java doest run prepare statements with parameter

    - by Zaiman Noris
    If using PreparedStatement to query my table. Unfortunately, I have not been able to do so. My code is as simple as this :- PreparedStatement preparedStatement = connection.prepareStatement( "Select favoritefood from favoritefoods where catname = ?"); preparedStatement.setString(1, "Cappuccino"); ResultSet resultSet = preparedStatement.executeQuery(); Error thrown is java.sql.SQLException: ORA-00911: invalid character. As if it never run through the parameter given. Thanks for your time. I've spend a day to debug this yet still unsuccessful. As mention by Piyush, if I omit the semicolon at the end of statement, new error is thrown. java.sql.SQLException: ORA-00942: table or view does not exist. But I can assure you this table is indeed exist. UPDATE shoot. i edited the wrong sql. now it is successful. thx for your time.

    Read the article

  • Confusion with a while statement evaluating if a number is triangular

    - by Darkkurama
    I've been having troubles trying to figure out how to solve a function. I've been assigned the development of a little programme which tells if a number is "triangular" (a number is triangular when the addition of certain consecutive numbers in the [1,n] interval is n. Following the definition, the number 10 is triangular, because in the [1,10] interval, 1+2+3+4=10). I've coded this so far: class TriangularNumber{ boolean numTriangular(int n) { boolean triangular = false; int i = n; while(n>=0 && triangular){ //UE06 is a class which contains the function "f0", which makes the addition of all the numbers in a determined interval UE06 p = new UE06(); if ((p.f0(1, i))==n) triangular = true; else i=i-1; } return triangular; } boolean testTriangular = numTriangular(10) == true && numTriangular(7) == false && numTriangular(6) == true; public static void main(String[] args){ TriangularNumber p = new TriangularNumber(); System.out.println("testTriangular = " + p.testTriangular); } } According to those boolean tests I made, the function is wrong. As I see the function, it goes like this: I state that the input number in the initial state isn't triangular (triangular=false) and i=n (determining the interval [1,i] where the function is going to be evaluated While n is greater or equals 0 and the number isn't triangular, the loop starts The loop goes like this: if the addition of all the numbers in the [1,i] interval is n, the number is triangular, causing the loop to end. If that statement is false, i goes from i to (i-1), starting the loop again with that particular interval, and so on till the addition is n. I can't spot the error in my "algorithm", any advice? Thanks!

    Read the article

  • fastest way to check to see if a certain index in a linq statement is null

    - by tehdoommarine
    Basic Details I have a linq statement that grabs some records from a database and puts them in a System.Linq.Enumerable: var someRecords = someRepoAttachedToDatabase.Where(p=>true); Suppose this grabs tons (25k+) of records, and i need to perform operations on all of them. to speed things up, I have to decided to use paging and perform the operations needed in blocks of 100 instead of all of the records at the same time. The Question The line in question is the line where I count the number of records in the subset to see if we are on the last page; if the number of records in subset is less than the size of paging - then that means there are no more records left. What I would like to know is what is the fastest way to do this? Code in Question int pageSize = 100; bool moreData = true; int currentPage = 1; while (moreData) { var subsetOfRecords = someRecords.Skip((currentPage - 1) * pageSize).Take(pageSize); //this is also a System.Linq.Enumerable if (subsetOfRecords.Count() < pageSize){ moreData = false;} //line in question //do stuff to records in subset currentPage++; } Things I Have Considered subsetOfRecords.Count() < pageSize subsetOfRecords.ElementAt(pageSize - 1) == null (causes out of bounds exception - can catch exception and set moreData to false there) Converting subsetOfRecords to an array (converting someRecords to an array will not work due to the way subsetOfRecords is declared - but I am open to changing it) I'm sure there are plenty of other ideas that I have missed.

    Read the article

  • Printing the "source" class in a log statement with a log4j wrapper

    - by Dur4ndal
    My application has a homebrew logging class that I'm migrating to using log4j under the covers. However, since I'm using the homebrew class to pass the rest of the application's logging statements to log4j, the output statements are logged as coming from the wrapper class instead of the source class. Is there a way to ensure that the "correct" source is being shown besides creating new org.apache.log4j.Logger instances for every log statement? I've also tried using the Logger.log(String callerFQCN, Priority level, Object message, Throwable t) method, but it doesnt seem to be working, for example: public class Logger2 { public static org.apache.log4j.Logger log4JLogger = org.apache.log4j.Logger.getLogger(Logger2.class); public static void warning(Object source, String message) { log(source, message, Level.WARN, null) } private static void log(Object source, String message, Level level, Throwable t) { String className = source.getClass().getName(); System.out.println("Logging class should be " + className); log4JLogger.log(className, loggingLevel, message, t); } } When called by: public void testWarning() { Logger2.warning(new Integer(3), "This should warn"); } Prints: Logging class should be java.lang.Integer 2010-05-25 10:49:57,152 WARN test.Logger2 - This should warn

    Read the article

  • switch namespace by if condtion

    - by pascal
    Hi, in my C++ program I have several namespaces that contain several pointers with identical names. I then want a function to choose a namespace according to a parameter. I.e. something like: #include <iostream> namespace ns1{ double x[5]={1,2,3,4,5}; } namespace ns2{ double x[5]={6,7,8,9,10}; } int main(){ int b=1; if(b==1){ using namespace ns1; } if(b==2){ using namespace ns2; } std::cout << x[3] << std::endl; } However, this doesn't work since the compiler complains that x isn't known in that scope. I guess the problem is that "using namespace ..." is only valid within the if-statement. I think that it should be possible to switch namespaces somehow, but cannot find out how... Do you know how to do this without casting all variable separately? int main(){ int b=1; double *x; if(b==1){ x = ns1::x; } if(b==2){ x = ns2::x; } std::cout << x[3] << std::endl; } Cheers, Pascal

    Read the article

  • how do I use an enum value on a switch statement in C++

    - by BotBotPgm
    I would like to use an enum value for my switch statment in C++. Is it possible to use the enum values enclosed in the "{}" as choices for the "switch()"? I know that switch() needs an integer value in order to direct the flow of programming to the appropriate case number. If this is the case, do I just make a variable for each constant in the 'enum' statment? I also want the user to be able to pick the choice and pass that choice to the switch() statement. for example: cout<< "1 - Easy"; cout<<"2 - Medium"; cout<< "3 -Hard"; enum myChoice {EASY =1 ,MEDIUM = 2, HARD = 3} cin ???? switch(????) case 1/EASY: (can I just type case EAST?) cout << "You picked easy!"; break; case 2/MEDIUM: cout << "You picked medium!"; case 3..... (same thing as case 2 except on hard.) default: return 0; Thanks

    Read the article

  • Batch Inserts And Prepared Query Error

    - by ircmaxell
    Ok, so I need to populate a MS Access database table with results from a MySQL query. That's not hard at all. I've got the program written to where it copies a template .mdb file to a temp name and opens it via odbc. No problem so far. I've noticed that Access does not support batch inserting (VALUES (foo, bar), (second, query), (third query)). So that means I need to execute one query per row (there are potentially hundreds of thousands of rows). Initial performance tests show a rate of around 900 inserts/sec into Access. With our largest data sets, that could mean execution times of minutes (Which isn't the end of the world, but obviously the faster the better). So, I tried testing a prepared statement. But I keep getting an error (Warning: odbc_execute() [function.odbc-execute]: SQL error: [Microsoft][ODBC Microsoft Access Driver]COUNT field incorrect , SQL state 07001 in SQLExecute in D:\....php on line 30). Here's the code I'm using (Line 30 is odbc_execute): $sql = 'INSERT INTO table ([field0], [field1], [field2], [field3], [field4], [field5]) VALUES (?, ?, ?, ?, ?, ?)'; $stmt = odbc_prepare($conn, $sql); for ($i = 200001; $i < 300001; $i++) { $a = array($i, "Field1 $", "Field2 $i", "Field3 $i", "Field4 $i", $i); odbc_execute($stmt, $a); } So my question is two fold. First, is there any idea on why I'm getting that error (I've checked, and the number in the array matches the field list which matches the number of parameter ? markers)? And second, should I even bother with this or just use the straight INSERT statements? Like I said, time isn't critical, but if it's possible, I'd like to get that time as low as possible (Then again, I may be limited by disk throughput, since 900 operations/sec is high already)... Thanks

    Read the article

  • How to delay execution of a method in c#?

    - by Pandiya Chendur
    I have this if condition, if (sendSMS(Convert.ToInt32(DLComportNo.SelectedItem.Text), TxtDriMob.Text, TxtCliDet.Text) && sendSMS(Convert.ToInt32(DLComportNo.SelectedItem.Text), TxtCliMob.Text, TxtDriDet.Text)) { // I am inserting details to my db } and my sendSMS method looks like this, private bool sendSMS(int portNo, string mobNo, string details) { try { SerialPort SerialPort1 = new SerialPort(); SerialPort1.PortName = "COM" + portNo.ToString(); SerialPort1.BaudRate = 9600; SerialPort1.Parity = Parity.None; SerialPort1.DataBits = 8; SerialPort1.StopBits = StopBits.One; SerialPort1.RtsEnable = true; SerialPort1.DtrEnable = true; SerialPort1.Encoding.GetEncoder(); SerialPort1.ReceivedBytesThreshold = 1; SerialPort1.NewLine = Environment.NewLine; SerialPort1.Open(); SerialPort1.Write("AT" + SerialPort1.NewLine); Sleep(500); SerialPort1.Write("AT+CMGF=1" + SerialPort1.NewLine); Sleep(500); SerialPort1.Write("AT+CMGS=" + (char)34 + mobNo + (char)34 + SerialPort1.NewLine); Sleep(1000); SerialPort1.Write(details + (char)26); Sleep(2000); SerialPort1.Close(); } catch { } return true; } What happens is when i use break point in my sendSMS i get my output (ie) both the methods get executed and messages are sent properly... But when i removed my breakpoint both the methods in the if statement are executed but message from the first method is sent and not from the second method.... Any suggestion?

    Read the article

  • vb Syntax error in INSERT INTO statement

    - by user201806
    im new in vb, i was create a program to connection ms access but when i run the program it get syntax error in Insert into statement, OleDbExpection was unhandled here my code Public Class Form2 Dim cnn As New OleDb.OleDbConnection Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load txtdate.Value = DateTime.Now cnn = New OleDb.OleDbConnection cnn.ConnectionString = "Provider=Microsoft.Jet.Oledb.4.0; Data Source=C:\Users\John\Documents\db.mdb" End Sub Private Sub btnsave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnsave.Click If Not cnn.State = ConnectionState.Open Then cnn.Open() End If Dim cmd As New OleDb.OleDbCommand cmd.Connection = cnn cmd.CommandText = "INSERT INTO sr(names,add,tel,dates,prob,serv,model,snm,acc,sna,remark)" & _ "VALUES ('" & Me.txtname.Text & "','" & Me.txtadd.Text & "','" & Me.txttel.Text & "', '" & _ Me.txtdate.Text & "','" & Me.txtpro.Text & "','" & Me.txtser.Text & "','" & Me.txtmod.Text & "', '" & _ Me.txtsnm.Text & "','" & Me.txtacc.Text & "','" & Me.txtsna.Text & "','" & Me.txtrem.Text & "')" cmd.ExecuteNonQuery() cnn.Close() End Sub End Class it's there any wrong with my code?

    Read the article

  • C++: Case statement within while loop?

    - by Jason
    I just started C++ but have some prior knowledge to other languages (vb awhile back unfortunately), but have an odd predicament. I disliked using so many IF statements and wanted to use switch/cases as it seemed cleaner, and I wanted to get in the practice.. But.. Lets say I have the following scenario (theorietical code): while(1) { //Loop can be conditional or 1, I use it alot, for example in my game char something; std::cout << "Enter something\n -->"; std::cin >> something; //Switch to read "something" switch(something) { case 'a': cout << "You entered A, which is correct"; break; case 'b': cout << "..."; break; } } And that's my problem. Lets say I wanted to exit the WHILE loop, It'd require two break statements? This obviously looks wrong: case 'a': cout << "You entered A, which is correct"; break; break; So can I only do an IF statement on the 'a' to use break;? Am I missing something really simple? This would solve a lot of my problems that I have right now.

    Read the article

  • C++: Switch statement within while loop?

    - by Jason
    I just started C++ but have some prior knowledge to other languages (vb awhile back unfortunately), but have an odd predicament. I disliked using so many IF statements and wanted to use switch/cases as it seemed cleaner, and I wanted to get in the practice.. But.. Lets say I have the following scenario (theorietical code): while(1) { //Loop can be conditional or 1, I use it alot, for example in my game char something; std::cout << "Enter something\n -->"; std::cin >> something; //Switch to read "something" switch(something) { case 'a': cout << "You entered A, which is correct"; break; case 'b': cout << "..."; break; } } And that's my problem. Lets say I wanted to exit the WHILE loop, It'd require two break statements? This obviously looks wrong: case 'a': cout << "You entered A, which is correct"; break; break; So can I only do an IF statement on the 'a' to use break;? Am I missing something really simple? This would solve a lot of my problems that I have right now.

    Read the article

  • Linq2Sql - attempting to update but the Set statement in sql is empty

    - by MrTortoise
    This is weird ... done updates loads of times before but cannot spot why this is different. I have a client class from the dbml I added a method called update public void UpdateSingle() { L2SDataContext dc = new L2SDataContext(); Client c = dc.Clients.Single<Client>(p => p.ID == this.ID); c.CopyToMe(this); c.updatedOn = DateTime.Now; dc.SubmitChanges(); dc.Dispose(); } The CopytoMe method public void CopyToMe(Client theObject) { if (ID != theObject.ID) { ID = theObject.ID; } /// this is redundant as generated code checks field for a change. deleted = theObject.deleted; deletedBy = theObject.deletedBy; deletedOn = theObject.deletedOn; insertedBy = theObject.insertedBy; insertedOn = theObject.insertedOn; name = theObject.name; updatedBy = theObject.updatedBy; updatedOn = theObject.updatedOn; } Im taking a client that was selected, changing its name and then calling this update method. The generated sql is as follows exec sp_executesql N'UPDATE [dbo].[tblClient] SET WHERE ([ID] = @p0) AND ([name] = @p1) AND ([insertedOn] = @p2) AND ([insertedBy] = @p3) AND ([updatedOn] = @p4) AND ([updatedBy] = @p5) AND ([deletedOn] IS NULL) AND ([deletedBy] IS NULL) AND (NOT ([deleted] = 1))',N'@p0 int,@p1 varchar(8000),@p2 datetime,@p3 int,@p4 datetime,@p5 int',@p0=103,@p1='UnitTestClient',@p2=''2010-05-17 11:33:22:520'',@p3=3,@p4=''2010-05-17 11:33:22:520'',@p5=3 I have no idea why this is not working ... used this kind of select object, set field to new value submit the selected object pattern many times and not had this problem. there is also nothing obviously wrong with the dbml - although this is probably a false statement any ideas?

    Read the article

  • Turning logical expression around

    - by BluePrint
    I have the following code: bool s = true; for (...; ...; ...) { // code that defines A, B, C, D // and w, x, y, z if (!(A < w) && s == true) { s = false; } if (!(B < x) && s == true) { s = false; } if (!(C < y) && s == true) { s = false; } if (!(D < z) && s == true) { s = false; } } This code is working well. However, I want to, for several (unimportant) reasons, change the code so that I can initiate s = false; and set it to true inside the if-statement. It tried the following: bool s = false; for (...; ...; ...) { // code that defines A, B, C, D // and w, x, y, z if (A >= w && s == false) { s = true; } if (B >= x && s == false) { s = true; } if (C >= y && s == false) { s = true; } if (D >= z && s == false) { s = true; } } However, this is not working properly as the code above is working. I know thought wrong somewhere in the logic, but I can't figure out where. Does anbyone see my probably obvious error? EDIT: Added three more if-statemets. Missed them since they were commented away.

    Read the article

  • Is there any alternative way of writing this switch statement(C#3.0)

    - by Newbie
    Can it be done in a better way public static EnumFactorType GetFactorEnum(string str) { Standardization e = new Standardization(); switch (str.ToLower()) { case "beta": e.FactorType = EnumFactorType.BETA; break; case "bkp": e.FactorType = EnumFactorType.BOOK_TO_PRICE; break; case "yld": e.FactorType = EnumFactorType.DIVIDEND_YIELD; break; case "growth": e.FactorType = EnumFactorType.GROWTH; break; case "mean": e.FactorType = EnumFactorType.MARKET_CAP; break; case "momentum": e.FactorType = EnumFactorType.MOMENTUM; break; case "size": e.FactorType = EnumFactorType.SIZE; break; case "stat_fact1": e.FactorType = EnumFactorType.STAT_FACT_1; break; case "stat_fact2": e.FactorType = EnumFactorType.STAT_FACT_2; break; case "value": e.FactorType = EnumFactorType.VALUE; break; } return e.FactorType; } If I create a Static class(say Constatant) and declare variable like public static string BETA= "beta"; and then if I try to put that in the Case expression like Case Constants.BETA : e.FactorType = EnumFactorType.BETA; break; then the compiler will report error.(quite expected) So is there any other way?(I canot change the switch statement) Using C#3.0 Thanks

    Read the article

  • Just a small help about switch's use

    - by Laurent Fournier
    If an answer on this already exist, my apologies i've not found on this question... is this statement correct if i want presice actions on integers from -2 to 0, and for those between 1 and 6 apply the same methods with only my integer who'll change ? Like this: public void setCaseGUI(Point pt, int i, boolean b){ plateau.cellule[(int)pt.getAbs()][(int)pt.getOrd()].setSelected(b); plateau.cellule[(int)pt.getAbs()][(int)pt.getOrd()].setIcon(null); switch(i) { case -2: plateau.cellule[(int)pt.getAbs()][(int)pt.getOrd()].setText("F"); plateau.cellule[(int)pt.getAbs()][(int)pt.getOrd()].setForeground(Color.red); break; case -1: plateau.cellule[(int)pt.getAbs()][(int)pt.getOrd()].setText("B"); plateau.cellule[(int)pt.getAbs()][(int)pt.getOrd()].setForeground(Color.red); break; case 0: plateau.cellule[(int)pt.getAbs()][(int)pt.getOrd()].setText(""); plateau.cellule[(int)pt.getAbs()][(int)pt.getOrd()].setForeground(null); break; case 1: case 2: case 3: case 4: case 5: case 6: case 7: case 8: plateau.cellule[(int)pt.getAbs()][(int)pt.getOrd()].setText(String.valueOf(i)); plateau.cellule[(int)pt.getAbs()][(int)pt.getOrd()].setForeground(null); break; default: System.out.println("Erreur de changement d'état/case !"); } } Please don't be too harsh on me i've started to learn dev only a few month ago

    Read the article

< Previous Page | 24 25 26 27 28 29 30 31 32 33 34 35  | Next Page >