While statement

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?
Thanks

The 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.

Similar Messages

  • When would I use an if, for or while statement in Small Basic and what is the difference between the three?

    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

  • 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)))

  • 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

  • URGENT! Having problem with while statement and other syntax errors

    I am trying to teach myself JSP for a school project due very soon. But I keep receiving errors surrounding my while statement. The errors are:
    Syntax: ";" inserted to complete BlockStatements
    Syntax: "}" inserted to complete Block
    I have checked it over and over again, comparing against other examples found in this forum and against servlet examples and I can see no difference. This is my file for your information. It is supposed to list all the users in the user table. Is there a simpler way to do this?
    regards
    rach
    <%@ page language="java" import="java.sql.*, java.util.*"%>
    <html>
    <head>
    <title></title>
    </head>
    <body>
    <%! String selected = null; %>
    <%
    try{
         // Connect to the database
         Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance();
         Connection con = DriverManager.getConnection("jdbc:odbc:dbtest");
    catch(ClassNotFoundException e) {
         System.out.println("Database driver could not be found.");
         System.out.println(e.toString());
         throw new UnavailableException(this, "Database driver class not found");
    try{
         //create SQL statement
         stmt = con.createStatement();
         ResultSet rs = stmt.executeQuery("SELECT * from USER ORDER BY User_lastname, User_firstname");
    catch(SQLException e){
         System.out.println("Error connecting to the database.");
         System.out.println(e.toString());
         throw new UnavailableException(this, "Cannot connect to the database");
    %>
    <table width="100%" border="0" cellpadding="0" cellspacing="0">
    <tr>
         <td width="10">    </td>
         <td width="200" valign="top" align="center">
         <table width="100%" border="0" cellpadding="0" cellspacing="0">
              <tr><td><form method="post" action="userupdatedelete.jsp" target="content" name="userlist">
                   <h2>Users</h2>
              </td>
              </tr>
              <tr>
                   <td width="10">    </td>
              </tr>
              <tr>
                   <td valign="top"><select size="15" name="rec">
                   <!-- if the resultset is not null -->
                   <% try {
                   //if (rs.next()) {
                        While (rs.next()){
                             //retrieve data from User table
                             String userid = rs.getString("User_ID");
                             String firstname = rs.getString("User_firstname");
                             String lastname = rs.getString("User_lastname");
                             out.println("<option value='userid'>lastname + ', ' + firstname</option>");
                             //<option value="<%=userid%>"><%=lastname + ", " + firstname%></option>
                   //else {
                   //     out.println("<option>    - No Users Entered - </option>");
                        //<option>    - No Users Entered - </option>
                   stmt.close();
                   con.close();
                   catch (SQLException ex){
                        System.err.print("SQL Exception :");
                        System.err.println(ex.getMessage());
                   %>               
                   </select>
                   </td>
              </tr>
              <tr>
                   <td align="center"><input type="submit" value="Update/Delete"></td>
              </tr></form>
              <tr>
                   <td><br></td>
              </tr>
              <tr>
                   <td align="center">
                   <form method="post" action="useraddform.jsp" name="addbuttonform">
                   <input type="submit" value="    Add New    " name="addnew">
              </tr></form>
              </table>
         </td>
         <td width="10">    </td>
    </tr>
    </table>
    </body>
    </html>

    There is a problem here with the "scope" of variables namely your variables "rs" and "stmt". Variables declared within a try block are available only within that try block. Also, the type for stmt is not even given.
    Change:
    try{
    //create SQL statement
    stmt = con.createStatement();
    ResultSet rs = stmt.executeQuery("SELECT * from USER ORDER BY User_lastname, User_firstname");
    catch(SQLException e){
    System.out.println("Error connecting to the database.");
    System.out.println(e.toString());
    throw new UnavailableException(this, "Cannot connect to the database");
    }to:
    Statement stmt = null;
    ResultSet rs = null;
    try
        //create SQL statement
        stmt = con.createStatement();
        rs = stmt.executeQuery("SELECT * from USER ORDER BY User_lastname, User_firstname");
    catch(SQLException e)
        System.out.println("Error connecting to the database.");
        System.out.println(e.toString());
        throw new UnavailableException(this, "Cannot connect to the database");

  • While Statement Help

    Hey, I'm having a problem with my while statement. I need to be able to have the program stop running when the input is Q. The only problem is that the input should otherwise be a number. I have to convert the user inputed number of dollars to euros using a previously inputed rate. So I can't just put everything as a String because then the equation doesn't work. Any help is welcome.

    gdawgrancid wrote:
    Hey, I'm having a problem with my while statement. I need to be able to have the program stop running when the input is Q. The only problem is that the input should otherwise be a number. I have to convert the user inputed number of dollars to euros using a previously inputed rate. So I can't just put everything as a String because then the equation doesn't work. Any help is welcome.A handy thing to do when solving ANY programming problem:
    1. Understand the problem, and what it is you have to do.
    2. Think of a solution in terms of english (or whatever your language may be)
    3. Put that solution into pseudo-code, which is often easier than working out what Java classes you might need.
    4. Take that pseudocode and code it in Java.
    Apply that to your current situation and the while loop should sort itself out.

  • While statements

    Hi All. I am a student in java programming, beginning class. I am having problems with understanding how to make a loop body work properly using a while statement. I have a problem I am working on, and I can't seem to get it to run properly, and I believe its mainly because I don't understand what I am doing. I have been searching the net for examples of while statements, but all I find are mostly the same ones, and they don't help. Here is the code I have so far, which compiles fine, but does not return the value I want, and also it seems to run infinately. Any ideas or help with this concept would be greatly appreciated.
    public class StereoPayments
    public static final double INTEREST_MONTHLY = 0.015;
    public static final int PAYMENT_MONTHLY = 50;
    public static void main(String[] args)
    //Need variables for monthly interest amount, for amount left over from $50 payment minus inerest(which gets
    //subtracted from the principle.
    double startMoney = 1000;
    double monthsInterest = 0;
    double moneyAfterInterestPayment = 0;
    double numberOne = 0;
    double numberTwo = 0;
    System.out.println("Here is your payments");
    while (startMoney >= 0)
    moneyAfterInterestPayment = (startMoney*INTEREST_MONTHLY);
    numberOne = (moneyAfterInterestPayment + startMoney);
    numberTwo = (numberOne - PAYMENT_MONTHLY);
    monthsInterest++;
    System.out.println("Months of payments " + monthsInterest);
    System.out.printf("Amount of interest paid " + numberOne);
    I am trying to print out how long it took to pay off the stereo, at $50 a month, while adding the interest to it each month, then output the amount of months it took to pay it off, and the total amount of interest paid. I am obviously not doing this right though. Can anyone help me? Thanks in advance! Newbie101.

    public class StereoPayments
    public static final double INTEREST_MONTHLY = 0.015;
    public static final int PAYMENT_MONTHLY = 50;
    public static void main(String[] args)
    //Need variables for monthly interest amount, for amount left over from $50 payment minus inerest(which gets
    //subtracted from the principle.
    double startMoney = 1000;
    double monthsInterest = 0;
    double moneyAfterInterestPayment = 0;
    double numberOne = 0;
    double numberTwo = 0;
    double currentAmount = 0;
    System.out.println("Here is your payments");
    while (startMoney >= 0)
    moneyAfterInterestPayment = (startMoney*INTEREST_MONTHLY);
    numberOne = (moneyAfterInterestPayment + startMoney);
    startMoney = (numberOne - PAYMENT_MONTHLY);
    monthsInterest++;
    System.out.println("Months of payments " + monthsInterest);
    System.out.printf("Amount of interest paid " + moneyAfterInterestPayment);
    Here is a revised code. It does end now, thanks to you folks' help! However, I am failing to add up the interest amount. What is does is show how much interest is being paid monthly, but not adding it up to a grand total. So, would I make a statement of "moneyAfterInterestPayment++; ? Newbie101.

  • Programming a times table with FOR, WHILE & DO WHILE STATEMENTS

    Guys,
    Help me, I have tried hard, but I didn't find the answer, my problem is that I got difficulties in doing a times table with the FOR, WHILE, and DO WHILE STATEMENTS just using a single index or a single variable.
    Guys, is it possible to program a times table with these conditions all together in the same code???
    Do I await your suggestions?
    Ps: Below, the attempt that I did, but I was not successful.
    import javax.swing.JOptionPane;
    public class tab
    public static void main(String args[])
    int i;
    String TimesTable= "";
    int result=0;
    do
    for (i=0;i<=10;i++)
    result=i*1;
    TimesTable +="\n" + i + "x" + i + "=" + result;
    //JOptionPane.showMessageDialog(null, "Times tables of " + i + TimesTable);
    // TimeTable="";
    // i=0;
    // i=i+1;
    // i=0;
    while(i<=10)
    i=i+1;
    // System.out.println("2 x "+i+"="+2*i);
    // i--;
    }while(i!=0);
    JOptionPane.showMessageDialog(null, "Times Table of " + i + TimesTable);
    TimesTable="";
    }

    You can use the if block "if(i%10==9)" in this case.

  • Problem interpreting a  while statement

    Hello there,
    The following code snippet (excerpted from Thinking in Java) has held me down all day. Can anyone tell me what condition evaluated to true in the while statement?
    import java.io.*;
    public class FormattedMemoryInput
      public static void main(String[] args) throws IOException
         try
            DataInputStream in = new DataInputStream( new 
                         ByteArrayInputStream(BufferedInputFile.read(
                                     "FormattedMemoryInput.java").getBytes()));
           while(true)
            System.out.print((char)in.readByte());
         catch(EOFException e)
           System.err.println("End of stream"); 
    } Thanks,
    ue_Joe

    Do not mind me. I am just as confused with the concept as with interpreting the statement. Here's the other half of the code. Might wish to run it to see that it works.
    // BufferedInputFile.java
    import java.io.*;
    public class BufferedInputFile
      // Throw exceptions to console:
      public static String read(String filename) throws IOException
        // Reading input by lines:
        BufferedReader in = new BufferedReader(new FileReader(filename));
        String s;
        StringBuilder sb = new StringBuilder();
        while((s = in.readLine())!= null)
          sb.append(s + "\n");
        in.close();
        return sb.toString();
      public static void main(String[] args) throws IOException
        System.out.print(read("BufferedInputFile.java"));
    }ue_Joe.

  • 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.

  • Conditional in while statement

    OK, i know this should be simple stuff.
    Imagine i have a while loop. The looping is converned by a statement that is populated by a webservice call inside the loop.
    So i have placed this inside the while expression:
    xp20:matches(bpws:getVariableData('CheckTransmittalDocs_Output','parameters','/ns1:CheckTransmittalDocumentsResponse/ns1:CheckTransmittalDocumentsResult'),'[OK]') = true()
    Basically if the return contains OK then exit the loop.
    but this doesn't work and i assume this becuase the initial variable is null and a regex match will just return null on this match no true or false.
    I can't use boolean as any value will be true. Any ideas?

    Thanks for the quick reply.
    I tryed that:
    <assign name="Assign_1">
    <copy>
    <from expression="'null'"/>
    <to variable="CheckTransmittalDocs_Output" part="parameters" query="/ns1:CheckTransmittalDocumentsResponse/ns1:CheckTransmittalDocumentsResult"/>
    </copy>
    </assign>
    Which was successful, but when it came to the while, it through this:
    XPath expression failed to execute. Error while processing xpath expression, the expression is "(xp20:matches(bpws:getVariableData("CheckTransmittalDocs_Output", "parameters", "/ns1:CheckTransmittalDocumentsResponse/ns1:CheckTransmittalDocumentsResult"), "[OK]") = true())", the reason is . Please verify the xpath query.
    I assume here that the error is misleading and it is the regex that is failing, but this should be ok.

  • How to return to first record in table after a while statement?

    Hi,
    I'm trying to multiply data from two different tables to get a distance between two points - I only want to return the result if the distance is less than 0.15 metres. It loops ok the first time but dies once I get into the second while for the second time. I'm sure I have the logic wrong, I just can't figure out the right way. I haven't used Java or programmed in four years so apologises if the answer is ridiculously simple!
    public static void main(String args[])
              try
                   FileOutputStream out = new FileOutputStream("c://output.txt", true);
                   PrintStream p;
    // Connect print stream to the output stream
    p = new PrintStream( out );
                   Connection conn = getConnection();
              System.out.println("1");
              Statement st1 = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
              Statement st2 = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
              ResultSet inact = st1.executeQuery("select Radio, aLocationLatLong, Lat, Lon from Inactive_EK");
              ResultSet act = st2.executeQuery("select Radio, aLocationLatLong, Lat, Lon from Active_EK");
              while(inact.next())
                   R_ID = inact.getString("Radio");     
                   inLt = inact.getDouble("Lat");          
                   inLn = inact.getDouble("Lon");
                   p.println("Inactive: " + R_ID + " " + inLt + " " + inLn);
                   while(act.next())
                        acR_ID = act.getString("Radio");
                        acLt = act.getDouble("Lat");
                        acLn = act.getDouble("Lon");
                        p.println("Active Lat: " + acLt + " " + acLn );
                             double earthRadius = 6378.137;
                             double dLat = Math.toRadians(inLt-acLt);
                             double dLng = Math.toRadians(inLn - acLn);
                             double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
                        Math.cos(Math.toRadians(acLt)) * Math.cos(Math.toRadians(inLt)) *
                        Math.sin(dLng/2) * Math.sin(dLng/2);
                             double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
                             double dist = earthRadius * c;
                             if(dist <= 0.15)
                                  p.println("Active Lat: " + acR_ID + " " + acLt + " " + acLn + " " + dist);
                   p.close();
                   st1.close();
                   st2.close();
                   conn.close();
              catch
              (Exception e)
    System.err.println ("Connect problem");
    Thanking you in advance!

    Try something like below: change the script as required.
    create Table T1(Col1 int)
    Insert into T1 Select 1
    Insert into T1 Select 2
    Declare @T1 Table(Col1 int, errmsg varchar(100))
    create Table T2(Col1 int, errmsg varchar(100))
    DELETE T1
    output deleted.*,'error 1' INTO @T1
    Where Col1 = 1
    Select * From @t1
    If exists(Select 1 From @t1)
    Begin
    Insert into T2 Select * From @T1
    Drop table T1,T2
    return ;
    End
    DELETE T1
    output deleted.*,'error 2' INTO @T1
    Where Col1 = 2
    Select * From @t1
    Insert into T2 Select * From @T1
    Select * From T2
    Drop table T1,T2

  • Terminating a while statement

    I have written a program to calculate the factorial of a numbers entered using a BigInteger. I want the program to be able to calculate the factorial of one number after another not just one number and terminate. In my main method I have included while(!finished) so I can achieve this but I do not have anything to terminate this statement.
    public static void main (String[] args)
          BufferedReader reader = new BufferedReader(new InputStreamReader(System.in),1);
          Factorial factorial = new Factorial();
          BigInteger integer;
          boolean finished = false;
          while(!finished) {
                        do {
               integer = readInt(reader);
                       if(integer.intValue() < 1) {
                          System.out.println("Please enter an integer greater than zero!");
                   integer = readInt(reader);
                       while ( integer.intValue() <1 );
              System.out.print("The factorial of " +integer+ " is: " +(factorial.factorialRec(integer)) );
              System.out.println("");
    *   Reads input from the command line and throws an exception if there is an error.
             public static BigInteger readInt(BufferedReader reader)
         System.out.println("Please enter an integer!");
         BigInteger input=null;
              try {
                    input = new BigInteger(reader.readLine());
               catch (IOException e) {
                    System.out.println("Unable to read integer!");
         return input;
           }I was thinking of setting finished to true if 'quit' or 'exit' is entered at the command line but my method readInt() will throw an exception for text entered that cant be converted into BigInts
    Does anyone have any suggestions as to what I could do?
    Thanks!

    i think you should read in a string then check if it's equal to "quit", if so finished = true;
    input =(reader.readLine());
    finished =true;
    else input = new BigInteger(input);
    try that...

  • I need help with this while() statement please!

    So I'm pretty new to Java programming and I cannot seem to understand why this is not looping if the user inputs a "n" at the end.
    Here is my code:
    * proj1nrh.java
    * Created on September 28, 2007, 2:42 PM
    * To change this template, choose Tools | Template Manager
    * and open the template in the editor.
    package proj1nrh;
    * @author Nate
    import java.util.Scanner;
    public class proj1nrh {
    /** Creates a new instance of proj1nrh */
    public proj1nrh() {
    public static void main(String[] args) {
    String areYouFinished;
    char repeat;
    Scanner keyboard = new Scanner (System.in);
    int numericResponse1,
    numericResponse2,
    numericResponse3,
    numericResponse4,
    numericResponse5,
    numericResponse6,
    numericResponse7;
    System.out.println("Survey #1");
    System.out.println("Please enther the numerical student responses (1-5) for each question:");
    System.out.println("Q1. The instructor was available for consultation.");
    numericResponse1 = keyboard.nextInt ();
    System.out.println("Q2. Student responsibilities for this course were well defined.");
    numericResponse2 = keyboard.nextInt ();
    System.out.println("Q3. Class time well spent.");
    numericResponse3 = keyboard.nextInt ();
    System.out.println("Q4. I learned a lot from the intructor in this course.");
    numericResponse4 = keyboard.nextInt ();
    System.out.println("Q5. Course material contributed to my learning.");
    numericResponse5 = keyboard.nextInt ();
    System.out.println("Q6. I was challenged in this course.");
    numericResponse6 = keyboard.nextInt ();
    System.out.println("Q7. Coming into this course, I was motivated to learn this subject.");
    numericResponse7 = keyboard.nextInt ();
    //Consume new line
    keyboard.nextLine();
    System.out.println("Are you finished (y/n)?");
    areYouFinished = keyboard.nextLine();
    repeat = areYouFinished.charAt(0);
    } while (repeat == 'n' || repeat == 'N');
    Thanks for the help!

    Ight you guys have been great help.... but I'm having another problem
    * proj1nrh.java
    * Created on September 28, 2007, 2:42 PM
    * To change this template, choose Tools | Template Manager
    * and open the template in the editor.
    package proj1nrh;
    * @author Nate
    import com.sun.xml.internal.bind.v2.schemagen.xmlschema.List;
    import java.util.Scanner;
    import java.util.ArrayList;
    public class proj1nrh {
        /** Creates a new instance of proj1nrh */
        public proj1nrh() {
        public static void main(String[] args) {
            String areYouFinished;
            char repeat;
            int n = 0;
            Scanner keyboard = new Scanner (System.in);
            int numericResponse1, sumOfResponse1,
                    numericResponse2, sumOfResponse2,
                    numericResponse3, sumOfResponse3,
                    numericResponse4, sumOfResponse4,
                    numericResponse5, sumOfResponse5,
                    numericResponse6, sumOfResponse6,
                    numericResponse7, sumOfResponse7;
            ArrayList storeValue1 = new ArrayList ();
            ArrayList storeValue2 = new ArrayList ();
            ArrayList storeValue3 = new ArrayList ();
            ArrayList storeValue4 = new ArrayList ();
            ArrayList storeValue5 = new ArrayList ();
            ArrayList storeValue6 = new ArrayList ();
            ArrayList storeValue7 = new ArrayList ();
          do {
                n = n + 1;
          System.out.println("Survey #1");
          System.out.println("Please enther the numerical student responses (1-5) for each question:");
          System.out.println("Q1. The instructor was available for consultation.");
            numericResponse1 = keyboard.nextInt ();
            storeValue1.add(numericResponse1);
            System.out.println("Q2. Student responsibilities for this course were well defined.");
            numericResponse2 = keyboard.nextInt ();
            storeValue2.add(numericResponse2);       
            System.out.println("Q3. Class time well spent.");
            numericResponse3 = keyboard.nextInt ();
            storeValue3.add(numericResponse3);
            System.out.println("Q4. I learned a lot from the intructor in this course.");
            numericResponse4 = keyboard.nextInt ();
            storeValue4.add(numericResponse4);
            System.out.println("Q5. Course material contributed to my learning.");
            numericResponse5 = keyboard.nextInt ();
            storeValue5.add(numericResponse5);
            System.out.println("Q6. I was challenged in this course.");
            numericResponse6 = keyboard.nextInt ();
            storeValue6.add(numericResponse6);
            System.out.println("Q7. Coming into this course, I was motivated to learn this subject.");
            numericResponse7 = keyboard.nextInt ();
            storeValue7.add(numericResponse7);
            //Consume new line
            keyboard.nextLine();
            System.out.println("Are you finished (y/n)?");
            areYouFinished = keyboard.nextLine();
            repeat = areYouFinished.charAt(0);
          } while (repeat == 'n' || repeat == 'N');
            int sum = 0;
    }I want to get the sum of each ArrayList 1-7 so I can divide this sum by "n" and display the average output.
    Thanks!

  • Help with MYSQLi Query and WHILE statement

    Hi,
    Not sure what is wrong here but the same record is printed in the while loop 11 times (the amount of records in the table).
    <?php 
    //Main Connection & Query
    //Database Connection & Error
    $con_host = 'X';
    $con_username = 'X';
    $con_password = 'X';
    $con_database = 'X';
    $con = mysqli_connect($con_host, $con_username, $con_password, $con_database);
    ?>
    <?php
    //Query
    $sql = "SELECT * FROM equipment ORDER BY name ASC";
    $query = mysqli_query($con, $sql);
    $row = mysqli_fetch_assoc($query);
    $row_count = mysqli_num_rows($query);
    //Create Variables
    $name = $row['name'];
    $size = $row['size'];
    $quantity = $row['quantity'];
    $protection = $row['protection'];
    $location = $row['location'];
    $sublocation = $row['sublocation'];
    $bc = $row['BC'];
    $id = $row['id'];
    ?>
    <!doctype html>
    <html>
    <link href="stylesheets/main_stylesheet.css" rel="stylesheet" type="text/css">
    <link href='http://fonts.googleapis.com/css?family=Slabo+27px' rel='stylesheet' type='text/css'>
    <!-- Favicon -->
    <link rel="shortcut icon" type="image/png" href="images/icon.png" />
    <style type="text/css">
    </style>
    <head>
    <meta charset="utf-8">
    <title>Print Equipment List</title>
    <link href="stylesheets/print_stylesheet.css" rel="stylesheet" type="text/css">
    <script src="sorttable.js"></script>
    <!--<body onload="window.print()">-->
    </head>
    <body>
    <div class="print_button no-print" onClick="window.print()">Print</div>
    <div class="print_text no-print">Select the sorting of the list by clicking on the table categories and click the print button below</div>
    <div class="print_a4page">
      <div class="print_header">
         <div class="print_header_logo"><img src="images/logo.png" width="306" height="43"></div>
          <div class="print_header_text" id="header_text">Drama Database</div>
          <div class="print_header_info">List printed: <script type="text/javascript">
      var currentTime = new Date();
      var month = currentTime.getMonth() + 1;
      var day = currentTime.getDate();
      var year = currentTime.getFullYear();
      document.write(day + "/" + month + "/" + year);</script>
      <br>
    Total records:
    <?php echo $row_count ?></div>
      </div>
        <div class="print_header_divider">Equipment List</div>
        <div class="print_body">
          <div>
            <form name="users" method="post">
              <div class="table_print">
              <table width="100%" border="0" cellpadding="5" class="sortable">
                <tr class="table_header_print">
                  <th width="15%" scope="col">Name</th>
                  <th width="12%" scope="col">Size</th>
                  <th width="9%" scope="col">Quantity</th>
                  <th width="12%" scope="col">Protection</th>
                  <th width="17%" scope="col">Location</th>
                  <th width="12%" scope="col">Sublocation</th>
                  <th width="11%" scope="col">Barcode</th>
                  <th width="12%" scope="col">Internal ID</th>
                </tr>
                <?php do { ?>
                <tr class="table_body">
                  <td><?php echo $name ?></td>
                  <td><?php echo $size ?></td>
                  <td><?php echo $quantity ?></td>
                  <td><?php echo $protection ?></td>
                  <td><?php echo $location ?></td>
                  <td><?php echo $sublocation ?></td>
                  <td><?php echo $bc ?></td>
                  <td><?php echo $id ?></td>
                </tr>
                <?php } while ($row = mysqli_fetch_assoc($query));?>
              </table>
            </form>
          </div>
        </div>
    </div>
    </body>
    </html>

    Still getting the same issue.
    As I see it, the way you have suggested is just rearanging things right?
    here is a screenshot of the outcome:
    And here is the improved code:
    <?php 
    //Main Connection & Query
    //Database Connection & Error
    $con_host = 'X';
    $con_username = 'X';
    $con_password = 'X';
    $con_database = 'X';
    $con = new mysqli($con_host, $con_username, $con_password, $con_database);
    ?>
    <?php
    //Query
    $sql = "SELECT * FROM equipment ORDER BY name ASC";
    $result = $con->query($sql);
    $row = $result->fetch_assoc();
    $row_count = $result->num_rows;
    //Create Variables
    $name = $row['name'];
    $size = $row['size'];
    $quantity = $row['quantity'];
    $protection = $row['protection'];
    $location = $row['location'];
    $sublocation = $row['sublocation'];
    $bc = $row['BC'];
    $id = $row['id'];
    ?>
    <!doctype html>
    <html>
    <link href="stylesheets/main_stylesheet.css" rel="stylesheet" type="text/css">
    <link href='http://fonts.googleapis.com/css?family=Slabo+27px' rel='stylesheet' type='text/css'>
    <!-- Favicon -->
    <link rel="shortcut icon" type="image/png" href="images/icon.png" />
    <style type="text/css">
    </style>
    <head>
    <meta charset="utf-8">
    <title>Print Equipment List</title>
    <link href="stylesheets/print_stylesheet.css" rel="stylesheet" type="text/css">
    <script src="sorttable.js"></script>
    <!--<body onload="window.print()">-->
    </head>
    <body>
    <div class="print_button no-print" onClick="window.print()">Print</div>
    <div class="print_text no-print">Select the sorting of the list by clicking on the table categories and click the print button below</div>
    <div class="print_a4page">
      <div class="print_header">
         <div class="print_header_logo"><img src="images/logo.png" width="306" height="43"></div>
          <div class="print_header_text" id="header_text">Drama Database</div>
          <div class="print_header_info">List printed: <script type="text/javascript">
      var currentTime = new Date();
      var month = currentTime.getMonth() + 1;
      var day = currentTime.getDate();
      var year = currentTime.getFullYear();
      document.write(day + "/" + month + "/" + year);</script>
      <br>
    Total records:
    <?php echo $row_count ?></div>
      </div>
        <div class="print_header_divider">Equipment List</div>
        <div class="print_body">
          <div>
            <form name="users" method="post">
              <div class="table_print">
              <table width="100%" border="0" cellpadding="5" class="sortable">
                <tr class="table_header_print">
                  <th width="15%" scope="col">Name</th>
                  <th width="12%" scope="col">Size</th>
                  <th width="9%" scope="col">Quantity</th>
                  <th width="12%" scope="col">Protection</th>
                  <th width="17%" scope="col">Location</th>
                  <th width="12%" scope="col">Sublocation</th>
                  <th width="11%" scope="col">Barcode</th>
                  <th width="12%" scope="col">Internal ID</th>
                </tr>
                <?php while ($row = $result->fetch_assoc()) { ?>
                <tr class="table_body">
                  <td><?php echo $name ?></td>
                  <td><?php echo $size ?></td>
                  <td><?php echo $quantity ?></td>
                  <td><?php echo $protection ?></td>
                  <td><?php echo $location ?></td>
                  <td><?php echo $sublocation ?></td>
                  <td><?php echo $bc ?></td>
                  <td><?php echo $id ?></td>
                </tr>
                <?php } ?>
              </table>
            </form>
          </div>
        </div>
    </div>
    </body>
    </html>

Maybe you are looking for

  • Reverse Calculation in Pricing Procedure

    Hi All, My client requirement is to calculate the PR00 from the TOTAL and TAX i.e. If we enter the TOTAL some amount and TAX 12.5% VAT in the Pricing Condition then it should calculate the d Basic Price PR00 . Tanks and regards, Bala

  • Installing OLEDB 8.1.7.3.0

    When run the "Setup.exe" program, afrer selected all the components of "Oracle Provider for OLE DB Components 8.1.7.3.0" and click next page, the Installer terminated without any error message. Oracle OLE DB 8.1.7.3.0 can't install on Windows 2003 se

  • IDVD wont open on Macbook Pro. 'loading themes' bar only.

    Everytime i try to open iDVD, i select 'start new project' and the 'loading themes' bar appears and nothing else happens. I have never been able to get into the actual program properly. When i was installing all the new updates when i first receieved

  • SQL Server Agent ... Relation with BizTalk.

    Hi All, I know that there are jobs in SQL Server Agent which are used to perform some activity on scheduled basis like Purging,backup etc... what happens if SQL server agent service is in Stop mode(is it mandatory to have it started) and does it have

  • ALE - Distribution Error

    Hello Experts, I need to add an extension in MATMAS. I created an extension and added to message type Z_MATMAS. Here, my partner system is Siebel. I added Z_MATMAS under one Model View and Generated the partner profile and saved. Here, the problem is