Controling flow of method

got a problem with the following code... everytime some one enters something other than an int the code runs on till it finishes, problem is i want it to start at the question it was asking - ie 1, 2, or 3. I can add addition(); in the catch statement but that makes it start from the beginning of the count.. ie question 1. (which is a pain if your doing question 3) can any one help?
import java.util.*;
class Math {
    private void addition() {
     Scanner keyboard = new Scanner(System.in);
     int sum = 0, num = 0, count = 0, answer = 0;
     for(num = 0; num < 3; num++) {
         System.out.println("Question " + (num + 1));
         System.out.println("What is the sum of these numbers?");
         int randomAddition = new Random().nextInt(6);
         for(count = 0; count < randomAddition; count++) {
          int rand = new Random().nextInt(11);
          System.out.print(rand + " ");
          sum = sum + rand;
         System.out.println();
         try {
          answer = keyboard.nextInt();
         catch (java.util.InputMismatchException e) {
          System.out.println("Enter a whole number only");
         System.out.println("Your answer is " + answer);
         System.out.println("The correct answer is " + sum);
         System.out.println();
         if(sum == answer) {
          System.out.println("CORRECT ANSWER");
         else {
          System.out.println("Incorrect, try again");
          num--;
         sum = 0;
    public static void main(String[] arg) {
     Math start = new Math();
     start.addition();
}

I'm not sure I understand what's going on with the input and the random numbers.
Here's an idea of how you might accomplish this. It's a bit funny with the do/while, but perhaps you can spend the time figuring it out. Use it as a template for thought:
import java.util.Scanner;
import java.util.ArrayList;
import java.util.List;
public class IntArrayAdder
   public static final int DEFAULT_ARRAY_LENGTH = 32;
   public static int [] getValues(Scanner scanner, String prompt)
      List values = new ArrayList(DEFAULT_ARRAY_LENGTH);
      try
         do
            System.out.print(prompt);
            int value = scanner.nextInt();
            values.add(new Integer(value));
         } while (scanner.hasNext());
      catch (Exception e)
         System.out.println("end of input");
      int [] valuesAsArray = new int[values.size()];
      for (int i = 0; i < valuesAsArray.length; ++i)
         valuesAsArray[i] = ((Integer)values.get(i)).intValue();
      return valuesAsArray;
   public static int sumArray(int [] values)
      int sum = 0;
      for (int i = 0; i < values.length; ++i)
         sum += values;
return sum;
public static void main(String [] args)
try
int [] values = getValues(new Scanner(System.in), "input an int: ");
System.out.println("sum: " + sumArray(values));
catch (Exception e)
e.printStackTrace();

Similar Messages

  • Setting Control-Flow- Case on java class/method

    hello All :D
    i have little problem about control flow case, in my case i've 2 page where before load to the page i'wanna make condition (if-else)
    when the user choose the field, the java class get the value for make true condition. In this case, i wanna implement ControlFlowCase in java class/method, so anyone help..?
    thx
    agungdmt

    Have you considered using router activity - http://download.oracle.com/docs/cd/E17904_01/web.1111/b31974/taskflows_activities.htm#CJHFFGAF ?

  • Dialog control flow case not opening in new browser window

    Hello -
    Using JDev 11gR1.
    I have a page fragment that contains a table of command links like so:
            <af:commandLink text="#{row.id}" id="cl2"
                            action="#{reportRunnerBean.runReportAction}"
                            useWindow="true" windowHeight="500" windowWidth="500">
              <f:param value="#{row.id}" name="reportId" id="p2"/>
            </af:commandLink>the runReportAction method returns the String: "dialog:runReport"
    in my page flow, the page fragment has a control flow case with the outcome "dialog:runReport" that leads to a URL View with the URL setting set to #{pageFlowScope.reportUrl}
    (the reportRunAction places a string in page flow scope with the key of "reportUrl". in case it matters, the url is external to the application)
    When I click on the link, I am directed to the correct URL. However, it does not open in a new browser window - it takes up the main browser window.
    Is there something obvious that I am doing wrong?
    Thank you for reading this,
    -- Scott

    Well, I couldn't figure out why the dialog wasn't working correctly, so I changed my page to use a server listener to handle the logic I wanted and just used af:goLink instead of a command link. That command link above became:
              <af:goLink text="#{row.id}" id="gl1"
                         destination="#{row.reportUrl}"
                         targetFrame="_blank">
                <af:clientAttribute name="reportId" value="#{row.id}"/>
                <af:clientListener method="logReport" type="click"/>
                <af:serverListener type="LogReportEvent"
                                   method="#{reportListBean.logReportInvocation}"/>
              </af:goLink>with the following client listener:
        <af:resource type="javascript">
          function logReport(evt) {
              var component = evt.getSource();
              var reportIdParam = component.getProperty("reportId");
              AdfCustomEvent.queue(component,
                                   "LogReportEvent",
                                   { reportId: reportIdParam}, false);
        </af:resource>and code in the bean:
        public void logReportInvocation(ClientEvent clientEvent) {
                String reportId =
                    (String)clientEvent.getParameters().get("reportId");
                //...do something w/reportId here...
        }Thanks to anyone who took the time to read this.

  • Better control flow?

    Actually this is a general question I've been wondering for a while...
    As the title states, I'm looking for a better control flow statement for what I planned.
    I have 4 variables that determine types of pipe in a program in my main class. There are 6 possible pipe types.
    For example Type 1 would have plastic grade = 5-7, color = 2, inner reinforcement = yes etc.
    My main method determines which type the client chose, (if it matched one of the types or not so if all 4 were true then it matches x type.)
    It's going to get really ugly if I use ifs and I don't think using a case statement would work.
    Any suggestions in what I can use?

    Unless you're just referring to getting user input and using it to look up a pipe >type?That would be what I'm doing, if I could figure out how to get the input variables from my applet class to the class that sorts out which pipe they picked.
    Except the variables had to be defined within a method so the try catch statments could be added to them to catch the nfe as most of them are converted from String to int.
    Let me suggest you to use nested switch case to solve the problemHmm, ok, I'll look into that. Would nested ifs suffice?
    Message was edited by:
    Yuriy_Ivanov

  • FileDownloadActionListener then Control Flow Case Action

    Hi guys!
    I'm working on a bounded taskflow and I've a little problem......
    I've put a fileDownloadActionListener in a command button and I can download a file fine.Now I want put another action listener to follow the control flow case designed in the bounded taskflow. Is it possible?
    this is my commando button code:
    <af:commandButton text="Conferma" id="cb1" action="cancel">
                <af:fileDownloadActionListener contentType="application/pdf;charset=UTF-8"
                                               filename="Chiusura#{bindings.RegitrationNumber.inputValue}.pdf"
                                               method="#{pageFlowScope.JasperClient.reportPDFDownload}"/>
              </af:commandButton>thanks!!!

    Thanks Zeeshan,
    but your advice don't resolve my issue.... I forgot to say that my command button is in a popup dialog, this the entire code
      <af:popup id="p1" animate="false">
          <af:dialog id="d2" title="Siete sicuri"
                     shortDesc="Siete sicuri di voler chiudere il veicolo?"
                     closeIconVisible="false" inlineStyle="width:500px;"
                     type="cancel">
            <af:outputText value="Siete proprio sicuri di voler chiudere questo veicolo?"
                           id="ot1" inlineStyle="width:500px; height:150.0px;"/>
            <f:facet name="buttonBar">
              <af:commandButton text="Conferma" id="cb1"
                                action="#{pageFlowScope.JasperClient.returnToSearch}">
                <af:fileDownloadActionListener contentType="application/pdf;charset=UTF-8"
                                               filename="Chiusura#{bindings.RegitrationNumber.inputValue}.pdf"
                                               method="#{pageFlowScope.JasperClient.reportPDFDownload}"/>
              </af:commandButton>
            </f:facet>
          </af:dialog>
        </af:popup>thanks!!!

  • Use exception to control flow?

    I use validateExcelFile(File excelFile) to validate whether a file has valid excel format,
    when file is in invalid format, I have two options:
    1) return the error message in validate method:
    public String validateExcelFile(File excelFile) {
    String errorMsg = "";
    if(errorMsg.length == 0) {
    return null;
    } else {
    return errorMsg;
    Or
    2)Throw out a exception containing errorMsg
    public void validateExcelFile(File excelFile)
    throws InvalidExcelFormatException {
    String errorMsg = "";
    if(errorMsg.length != 0) {
    throw new InvalidExcelFormatException(errorMsg);
    The context in which the validate method is invoked needs to delete any invalid excel file according to the validate result, option 2 has the good that if there is another validate method and it also throws out the same exception when a file is invalid then I can place the two method in one
    try{
    validateMethod1( excelFile );
    validateMethod2( excelFile );
    } catch (InvalidFormatException ex) {  // deletes invalid file } statement, it is more clear than to check every method's returned error message, but I doubt whether it is good practice to control flow with exception instead of
    flow statements like if.
    Thanks.
    StuartS
    Edited by: StuartS on Oct 24, 2007 8:35 PM

    TimSparq wrote:
    You are correct, it is best practice not to controll flow with exceptions.
    Perhaps your validate message could just return a boolean and you can do something like:
    if (!validateExcelFile(file)) {
    // delete file
    Yeah, I was thinking of it more from a security validation standpoint, but if you simply want to accomplish an action as the result of a bad format, then you're definitely better off having a boolean function.

  • Cash Flow (Direct Method ) Report ( T-Code S_ALR_870_12271 ) not Working

    Hi All,
             I am trying to run Cash Flow (Direct Method ) Report with T-Code S_ALR_870_12271 but it's showing Output  as following .
         No records were selected          
         Table     Financial Statement Key Figures
         Report name     0SAPRATIO-04
         Report long text     Cash Flow (Direct Method)
         Form     0SAPRATIO-04 Cash Flow (Direct)
         Report type     Form report
               General information          
         A     uthor          SAP
         Created on     06.02.1996
         Last changed by     ABAP1
         Last changed on     25.03.2009
         Last changed at     17:42:09
         Last displayed on     25.03.2009
         Number of times displayed     18
         Basic list     Detail list
               Additional selection conditions     
         C     ompany Code     101     0 HGSL INDIA
         Currency Type     10 Company code currenc
         G/L Account     60000000
         G/L Account     60000000
         Bal.sheet type     1 Standard financial s
               General data selections          
         P     lan./act. ind.          0    Actual
         Fin.Stmt Vers.     INT  Financial Statement
               Variable          
         F     iscal year          
         Fiscal year     2008 2008
               Selected characteristics ( Online sort order )     
         G     /L Account     *     
         Business Area     *
         Company Code     *
         Period     *
               Columns selected for drilldown list     
         F     iscal Yr ;2008          
         Fiscal Yr ;2007     
               Rows selected for drilldown list     
         +      Sales revenues          
         + Incr.dwn pmts rec.     
         - Incr.recvbls f.G&S     
         Sales collections     
         + Material costs     
         - Incr.in pybls G&S     
         + Incr.dwn pmts made     
         Material disbursmnts     
         + Personnel costs     
         - Incr.in pens.prov.     
         Personnel disbursmts     
         + Oth.int./sim.incme     
         - Interest expenses     
         - Increase in discnt     
         + Inc.fr.investments     
         + Due to prof.trans.     
         + Inc.f.oth.securits     
         Financial collectns     
         + Other operat.inc.     
         - Gns f.retr.sp.itms     
         + Increase in AE/DI     
         Oth.operat.collectns     
         + Oth.operat.expnses     
         - Optional add.items     
         - All.sp.itms w.res.     
         - Incr.in oth.provs     
         + Inc.prpd/defr.itms     
         Oth.operat.disbrsmts     
         + other taxes     
         - Incr.in tax.prov.     
         Income tax     
         = Cash flow (total)     
               Particular sort orders          
         G     /L Account          G/L Account Long name Ascending
         Company Code     Company Code        e Ascending Long name Ascending
    Plese Help me out ...
    Thanks
      Amit

    Hello Ajay
    It happens due to different settings mostly in FORM e.g. FSV set in the form would be INT where as you have your own FSV.  Similarly you need to check each and every item and change suitably.
    Run the report via above tcode again, then a screen will appear saying u201CNo records were selectedu201D
    In this screen you can see the FSV used in General Data Selection (4th box) which you need to change by pushing u201CFORMu201D push button on the extreme left side, > Go to edit menu>Gen data selection > make changes suitably.
    However do not make changes to the standard report / form, so copy the standard report with your own naming and make the changes where ever required.
    Hope it works!
    Ambadas

  • Programatically calling control flows from java code

    Hi all,
    I have a bounded taskFlow that uses pageFragments. This flow is a region in a page(.jspx).
    In my page fragment, I have a inputComboboxListOfValues with a ValueChangeListener code in a java bean.
    I want when a value is changed, to programatically call "controll flow" (this one has: "From Activity Id" -the page fragment with that inputComboboxListOfValues, and "To Activity Id" - the default Activity on this task Flow).
    So when the value change, practically I want to restart the flow programatically and pass the selected value as input parameter.
    Since the inputComboboxListOfValues is not like a button where in the "Action" property you can set the Control Flow and navigate somewhere, the only option I have is to programatically cause navigation from java code (example: the value change listener code).
    Can this be achieved?
    Any advice is helpfull.

    Hi,
    Absolutely, you can do it using the NavigationHandler. Try the following in you value change listener:
    FacesContext context = FacesContext.getcurrentInstance();
    NavigationHandler handler = context.getApplication().getNavigationHandler();
    handler.handleNavigation(context, null, outcome);
    // Render the response after that phase, the button actions should not be called
    context.renderResponse();
    // Add the following line if you want to prevent further value change listeners to be called
    // throw new AbortProcessingException();Regards,
    ~ Simon

  • Bounded-Task-Flow Page Fragment Control Flow Help

    jDeveloper: 11.1.1.0.2
    I am having an issue trying to figure out the correct way to use control flow cases between a bounded-task-flow with page fragments and an unbounded-task-flow page. We have taken the approach in our application to have a few shell / container pages to host bounded-task-flows made up of page fragments to facilitate re-usability and to speed up development. There are 4 or 5 shell pages on the applications unbounded-task-flow. As of now, we have about 20 page fragments that are implemented as bounded-task-flows. These fragments don't do much now, meaning there is only a single fragment in each bounded-task-flow. The issue I am having is trying to invoke a control flow navigation action from one of the fragments to load a different shell page.
    For Example, shellPage1.jspx contains fragment-flow-1 as a region. In my adfc-config.xml I have shellPage1.jspx and shellPage2.jspx, with control flow cases "toShell1" and "toShell2" respectively connecting the two pages. I have a link's action bound to the "toShell2" within the fragment that makes up fragment-flow-1. When the application is run, shellPage1.jspx and its fragment are displayed. But clicking on the link in the fragment ("toShell2") does absolutely nothing. It does not navigate me to the shellPage2.jspx as expected. What am I doing wrong here or do not understand?
    If the fragment is included as a JSP include, and not a bounded task flow include, everything works as expected. This is not desirable as we then need to copy the fragment's pageDef into the shellPage's pageDef to get the DataControls to function.
    If the faces-config.xml is used instead, and a JSF navigation case is used, it will also work as expected. This is not desirable because we really don't want to be mixing adcf-config and faces-config.
    So I am really stumped here.... Thanks in advance!

    Hi there:
    In your case, the adfc-config.xml has the control flow case between shell pages. And the task-flow-N.xml or your-task-flow.xml for each page fragment by default doesn't inherit control flow case from their containing shell page. In your case, in the page fragment task-flow.xml, you should add a "Parent Action" to flow to shell page2 for example. The outcome of "Parent Action" would be "toShell2" if calling from ShellPage1 page fragment.
    Is this 'Correct' or 'Helpful' for you? Please mark it as so if it does.
    Good luck,
    Alex

  • From where i can understand the control flow and architecture of JVM?

    i want to know control flow and architecture of JVM?
    Where i can know from?
    if some one wish to explain you can here also.

    makpandian wrote:
    No it s not broken.
    As per your experience,tell me some links.Per my experience I don't need links. I could build the VM both from the general level and the specific levels by referring only to the VM spec.
    And I read the book I suggested, first edition, years ago. Although with many other books.
    Conversely if I wanted to find a link now then I would use google.

  • Cash flow indirect method drill down report

    Hi!
    I have developed the report for cash flow indirect method ( FSI6) where i have given the selection parameter as year, but users are asking for from period/year to to period/year.
    In FSI3, I am not able to change variable which was already defined as Fiscal year.
    How can change?
    regs,
    ramesh

    Hi Dan,
    Very interesting! Though, I didn't get the answer. Think it would be very favorable for everybody, if you explain in more details.
    AFAIK, data is stored in BCS periodically. So, do you imply that it's possible to create cash flow for any set of data in the system (because of periodicity)?
    Talk about ttypes and breakdown categories are also not very clear for me.
    Anyway, I'd like to talk functional, not SAP (or some other IT) language.
    Here we go.
    Did you say that you used to create the cash flow report on the fly, by using some calculations in BEx?
    And the same for eliminations in cash flow?
    Did you do eliminations in CF?
    If yes, then I would suggest that you were lucky, having local and group currency the same, USD?
    As BCS consultant knows, the indirect cash flow report consists of 3 parts: net cash flows from operating activities, finance and investing ones.
    NCF from operating activities is usually calculated as net profit (before or after taxes) with some corrections that are calculated as differences in reported-beginning balances on some accounts. Would you calculate them in local or group currency? Taking into account that there might be no real movement in cash (local currency), but currency rate has changed?
    Financial & investing activities MUST BE PROVIDED in direct sense, like: dividends received, interests paid for credits and loans etc. There is, usually, no such information, only some netted activities. You need to get them additionally. How did you get them?
    So, the main question is:
    how would you calculate the CONSOLIDATED INDIRECT cash flow report
    having different local currencies (and a different group currency), with some intergroup activities?
    Everybody will appreciate your input on this subject.

  • Why do we want use 'Data Flow Task' to 'Data Flow Tast' in Control Flow?

    I found an example in my company's SSIS package folders. In Control Flow, it has one data flow connected to the other. Both of them are importing data from flat file and then exported to database. I think these two are kind of at the same level and cannot
    see any reasons to conncect them together.
    Thanks & Happy Thxgiving,
    Gavin 

    Hi Gavin,
    Just as Arthur said, if there is no relationship between those two data flow tasks, we don’t have to connect them together. If they connect together, maybe there are some relationship between them.
    According to your description, both of the data flow tasks are importing data from flat file and then exported to database. It seems that there is no direct relationship between them. Another possibility is that there is a precedence constraint between them.
    The precedence constraint can be based on a combination of the first execution results and the evaluation of expressions. We can check the issue by double-check the connection string between them.
    The following screenshot is for your reference:
    If there are any other questions, please feel free to ask.
    Thanks,
    Katherine Xiong
    Katherine Xiong
    TechNet Community Support

  • Ssis data flow item and ssis control flow item tab missing in choose toolbox item from ssdt 2010

    ssis data flow item and ssis control flow item  tab missing in choose toolbox item from ssdt 2010

    I have the same problem.
     When i click on tools -> choose tools Items dialog box, Control Flow and Data Flow Tab are missing.
    I've just worked with SQL Server Data Tools and SQL Server 2012 and these tabs are not missing.
    i think this is a problem installing SQL Server.
    I've not yet  found a solution.

  • How to Customize "CASH FLOW(indirect method) STATEMENT"

    Dear Guru's,
    this is an urgent task for me.Kindly give me the steps to customize the CASH FLOW(indirect method) STATEMENT.kindly send me the material related to this to
    [email protected]
    Regards
    Sap Guru

    Pl send me also [email protected]

  • Control flow case to return from any page to start page!

    I need to use a Image Link at Master Page for go to "Start page". but when i use control flow case don't work.
    How can i assign a control flow case in a master page?
    My djeveloper version is 11.1.2.3

    You have to define what you mean by master page and start page. Are both pages are on the same talk flow?
    What do you mean by 'the navigation doesn't work'? Do you get an error?
    Normally you implement a wild card navigation which points to the start page. This navigation you use as target for the image link.
    Please post the code of your image link.
    Timo

Maybe you are looking for

  • Installed latest update and now i cannot get itunes to load

    installed latest update and now i cannot get itunes to load

  • Download map in PI 7.0

    Can we download  a mapping in PI 7.0 to XIM format?

  • Strange problem with CachedRowSet

    Hi, I got I an strange problem, I got two CachedRowSet in two different classes, it works without problem, but now I need to create more classes that will receive a RowSet, but the problem is that it don't execute, I got a NullPointerException, but w

  • How to import whole song in WaveBurner

    Hi When I import into WB it imports all the different tracks i have eg guitar, drums synth sepratly and not as one song . How do I get it to condence all my tracks into one song. cheers!

  • Spacing between two line types in smartform

    I have data in two different line types as below line type1 linetype2 but what my requirement is line item1 line item2 i had tried by changing the smart style but it dint work. Please help me out in reducing the space between the datas of the line ty