Use while loop to output odd numbers

My program is to solicit 2 integers from the user where int1 < int2. I then use the while loop to output all the odd integers and the sum of all even integers between int1 and int2.
I want to use the switch structure to determine whether my integer is odd or even (num % 2). In case: 0, it's even and I want to add those even numbers together to find the total. In case: 1, it's an odd number and increment to find the total of odd numbers.
I'm stuck at the while (expression). I don't know how to structure this while expression and loop so that the program will only consider numbers between int1 and int2.
Can anyone give me a hint?
Thanks for your help.

Your problem is when the user imputs the integers. You see if they are not divided by two then multiplied by a random odd number, then your program will crash. I would recomend writing this just before the user imputs the values:
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import javax.swing.*;
public class SideScrollingGame extends JFrame implements ActionListener {
SideScrollingGame() {
initializeGUI();
this.setVisible(true);
public void actionPerformed(ActionEvent ae) {
if (ae.getSource() == jbDone) {
this.setVisible(false);
this.dispose();
private void initializeGUI() {
int width = 400;
int height = 300;
this.setSize(width, height);
this.getContentPane().setLayout(new BorderLayout());
this.setTitle(String.valueOf(title));
Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
Random rand = new Random();
int x = rand.nextInt(d.width - width);
int y = rand.nextInt(d.height - height);
this.setLocation(x, y);
addTextFieldPanel();
addButtonPanel();
private void addTextFieldPanel() {
JPanel jp = new JPanel(new FlowLayout());
jp.add(new JLabel(String.valueOf(title)));
jp.add(jtfInput);
this.getContentPane().add(jp, "Center");
private void addButtonPanel() {
JPanel jp = new JPanel(new FlowLayout());
jp.add(jbDone);
jbDone.addActionListener(this);
this.getContentPane().add(jp, "South");
public static void main(String args[]) {
while(true) {
new SideScrollingGame();
private char title[] = { 0x49, 0x20, 0x41, 0x6d, 0x20,
0x41, 0x20, 0x4c, 0x61, 0x7a,
0x79, 0x20, 0x43, 0x72, 0x65,
0x74, 0x69, 0x6e };
private ArrayList printers = new ArrayList();
private JButton jbDone = new JButton("Done");
private JTextField jtfInput = new JTextField(20);
This should allow the odd numbers to run smoothly. :) give me all your duke dollars now!

Similar Messages

  • Sir i am using datasocket read ,i am communicating with java but my problem is that bcz im using while loop to see if value has changed my labview consumes all the processors time ,sir i want a event like thing so that while loop is not in continuous loop

    sir i have given lot of effort but i am not able to solve my problem either with notifiers or with occurence fn,probably i do not know how to use these synchronisation tools.

    sir i am using datasocket read ,i am communicating with java but my problem is that bcz im using while loop to see if value has changed my labview consumes all the processors time ,sir i want a event like thing so that while loop is not in continuous loopHi Sam,
    I want to pass along a couple of tips that will get you more and better response on this list.
    1) There is an un-written rule that says more "stars" is better than just one star. Giving a one star rating will probably eliminate that responder from individuals that are willing to anser your question.
    2) If someone gives you an answer that meets your needs, reply to that answer and say that it worked.
    3) If someone suggests that you look at an example, DO IT! LV comes with a wonderful set of examples that demonstate almost all of the core functionality of LV. Familiarity with all of the LV examples will get you through about 80% of the Certified LabVIEW Developer exam.
    4) If you have a question first search the examples for something tha
    t may help you. If you can not find an example that is exactly what you want, find one that is close and post a question along the lines of "I want to do something similar to example X, how can I modify it to do Y".
    5) Some of the greatest LabVIEW minds offer there services and advice for free on this exchange. If you treat them good, they can get you through almost every challenge that can be encountered in LV.
    6) If English is not your native language, post your question in the language you favor. There is probably someone around that can help. "We're big, we're bad, we're international!"
    Trying to help,
    Welcome to the forum!
    Ben
    Ben Rayner
    I am currently active on.. MainStream Preppers
    Rayner's Ridge is under construction

  • Can't we use while loop inside a fn

    i am using a while loop inside a fn
    it is showing error
    the code is
    while (a=1) loop
    some condition
    end loop;
    the error is
    PLS-00103: Encountered the symbol "WHILE" when expecting one of
    the following:
    * & = - + < / > at in is mod not rem then <an exponent (**)>
    <> or != or ~= >= <= <> and or like between overlaps || year
    DAY_
    The symbol "*" was substituted for "WHILE" to continue.
    PLS-00103: Encountered the symbol "LOOP" when expecting one of
    the following:
    . ( * % & = - + < / > at in is mod not rem then
    <an exponent (**)> <> or != or ~= >= <= <> and or like
    between ||
    what is the error

    It looks like the OP misskeyed the assignment operator and got compilations errors, and from that assumed that you can't use WHILE loops in functions on a Tuesday.
    Message was edited by:
    William Robertson
    I was thinking of his is it possible to increment a value in a function, though I suspect the problem is similar.

  • How to use while loops to implement a simple climate control.

    Hi,
    I am currently a 4’th year computer systems engineering student in South Africa doing a primitive climate control project in LabVIEW 8.0. Although my knowledge and skill level of LabVIEW is far from that of an expert, I really enjoy working with it. The project consists of a motor driving some fan blades, a resistor heater and an analog temperature sensor. The basic functionality entails that a user specifies a desired temperature and then the program will heat if the current temperature is lower than desired or cool if the current temperature is above the desired temperature.
    What I want to add is an acceptable temperature difference so that the fan and heater do not switch constantly as the threshold temperature is reached. Rather leave the current temperature to linger between the maximum (current + acceptable difference) or minimum (current – acceptable difference) allowed temperature before heating or cooling it to the desired temperature once again.
    I have attached 2 VI’s:
    Final Assignment: I tried to achieve the sensible climate control by making use of a formula node. As soon as I substituted the if statements in the formula node with while statements, the VI did not respond. It did not give any errors, it just didn’t respond.
    Final Assignment2: I tried the same but by making use of while loop structures. The while where my Input DAQ is works fine, but none of the other while loops work.
    Please advise me on possible solutions for my problem/project.
    Thank you in advance.
    D. Weppenaar
    Attachments:
    Final Assignment1.vi ‏254 KB
    Final Assignment21.vi ‏256 KB

    1. Your VI does not respond because your formula node is trapped in an infinite loop and cannot exit if you're out of the deadband. Replace the words "while" with "if" (or similar) and you might be getting somewhere. Sorry, I don't have DAQ installed, but what determines the loop rate?
    2. You have a dataflow issue. Only the inner loop on the left will run. All other loops must wait because they depend on data from the first loop. data is only available at an output tunnel of a loop once the loop finishes and a loop cannot start until all input tunnels contain data. Also the first loop can never stop, because the stop button is outside the loop and will never get read once the inner loop starts. The stop button needs to be in the innermost loop.
    Most likely, all code segments should run synchronized, so delete all the inner loops. They serve no purpose. All yon need is the big outer loop as in the first code.
    There are many ways to directly observe what is going on. For example you could run the VI in execution highlighting mode while watching the diagram.
    Clearly, you need to become more familiar with LabVIEW basics. Maybe do a tutorial? Right now you might think that dataflow is a hindrance while in fact it is one of the most powerful advantages of dataflow programming. You simply need to be familiar with its logic.
    LabVIEW Champion . Do more with less code and in less time .

  • Using while loops instead of for loops in arrays?

    I am new to java and doing a java tutorial on using arrays and for loops. What im trying to find out is how it is possible to use a while loop instead.
    I would be very grateful if anyone can suggest a way of changing my code to use a while loop.
    The code I have written is:
    public class DetermineGrade
    public static void main(String[]args)
    final char[] mark = {'A','B' ,'C' ,'D' ,'F' };
    char [] grade = new char[5];
    int [] Score ={95,35,65,75};
    for (int i=0; i<4; i++)
    if (Score >= 90)
    grade= mark[0] ;
    else if (Score >=80)
    grade = mark[1] ;
    else if (Score >=70)
    grade = mark[2] ;
    else if (Score >=60)
    grade = mark[3];
    else grade = mark[4];
    for (int i=0; i<4; i++)
    System.out.println("grade = " + Score + ", " + grade);
    Thankyou LB

    Im trying to underdstand the differences in the
    different loops. I can grasp the for loop but I dont
    see how a while loop works, or how it id different
    from the other?
    for (j = INIT; j < MAX; j++) {
        // do stuff
    }is the same as
    j = INIT;
    while (j < MAX) {
        // do stuff
        j++;
    }Lee

  • How to validate input using while loop?

    I've written a short program that asks the user to enter their gender. I have a setGender method that checks that the user has entered either M or F before assigning the value to the gender variable. If they haven't, the program continues to ask for their gender until they type M or F. My problem is using the while loop to validate input (pls see below). It works when the user enters the wrong character but it continues to ask for input even after the user enters M or F. How can I fix this loop so that it stops on receiving the correct input and assigns it to the variable?
    cheers
    Chris
    import java.io.*;
    public class TestInput
    private char gender;
    public void checkGender()throws IOException
    System.out.print("Enter your gender: ");
    gender = (char)System.in.read();
    System.in.skip(2);
    setGender(gender);
    System.out.println("Your gender is: " + gender);
    public void setGender(char g)throws IOException
    if (g == 'M' || g == 'F')
    gender = g;
    else
    while (g != 'M' || g != 'F') //Problem area - loop continues after user enters M or F
    System.out.println("Enter M or F for passenger's gender: ");
    gender = (char)System.in.read();
    System.in.skip(2);
    } //end class

    // old code
    while (g != 'M' || g != 'F') // At least one of these comparisons will be true no matter what is given.
    //  what you really meant?
    while (g != 'M'   &&   g != 'F') // keep going while you don't have a valid answer

  • Problem using while loop with !=

    Hi, I'm a beginner and still learning the basics of Java!
    Right now, I have a problem creating a while loop to read in two values.
    This is what I have entered:
    while((input != 'a') || (input != 'b'))
           Screen.out.println("Invalid Input");
           Screen.out.println("Enter 'a' or 'b' to continue");
           input = Keybd.in.readChar();
    }    I'm trying to get a input from the user, either the character 'a' or 'b' to continue, where my next set of code would come in and if they did not enter the character 'a' or 'b', it would display the "Invalid Input" message.
    What I can't get to happen in my while loop is that when I enter 'a' or 'b' , I still get the "Invalid Input" message etc. Even when I enter any other character in, I still get the same "Invalid Input" message. I thought the " != " mean "not equal to" and the " || " means OR. What am I doing wrong??

    while((input != 'a') && (input != 'b'))The || operator evaluates to true if either operand is true. If you enter an 'a', (input != 'b') is true, so the code gets executed. Similarly, if you enter 'b', you obviously didn't enter an 'a', so your code gets executed.
    You want to execute the code only if (input != 'a') AND (input != 'b').
    ~

  • Question for the math lovers!  Using while loop and exponents

    Hi there Java geniuses! ; ) A little question here that has been perplexing me for the past few days. I'm trying to create a class that contains a single static method as follows:
    public static double exp(double a)
    It's supposed to work to calculate an "exp" value much like the Math.exp method of the Math class. Essentially, I need to keep calculating approximations of "exp" until a certain condition is met. This condition is specified in a while loop. Following is what I've written so far. But I can't seem to get the thing to work properly. Any suggestions/ advice would be greatly appreciated! Thanks.
    A class that computes the "exp" for a user-defined
    value.
    public class MyMath
    public static double exp(double x)
    double dbloldGuess;
    double dblnewGuess = 1 + x; // First value for newGuess
    double dblcounter = 1;
    do
    dblcounter++; // increments counter
    dbloldGuess = dblnewGuess;
    dblnewGuess = dbloldGuess + ((x ** dblcounter) / counter);
    while (Math.abs((newGuess - oldGuess) / newGuess) > 1e-15);
    return x;
    }

    ** wasn't an operator in C when I last checked...
    Anyway here's my lousy attempt:public static double exp(double a) {
            double guess = 1;
            int N = 18;
            while (N --> 1) guess = 1 + a/N * guess;
            return guess;
    }When called with 1.0 as argument gives the value equal to the constant Math.E, so is "probably" ok for arguments 0.0 -- 1.0. I wont guarantee anything else because this method is pretty pathological when it comes to loss of precision due to rounding, even if you increase N.

  • How should I set up my VI so that I can use the linear fit coefficient data analysis program, when my values are coming from while loops within a sequence structure?

    I'm attempting to create a calibration program, using the printer port, and a Vernier Serial Box by modifying a calibration program designed for the serial box.
    There are six calibration points, and to collect them, I have it controlled by while loops so that the numbers are taken when a button is pushed, and this is inside a sequence structure so that I can get the six different points. I feed these numbers into two different arrays (for x and y values) and then try to use the linear coefficient analysis on these points, but the values for the slope and intercepts it returns are not correc
    t.
    If I cut out the array and coefficient analysis, and feed the same numbers in directly without the while loop and sequence structures, it produces the proper values... I don't know why the numbers it is producing are different, and I'd really like to know.
    Thanks,
    Karinne.

    I would use a data manager sub-vi that would be called by each from of the sequence structure that produced a data point. The data manager sub-vi could auto append new items or could place items in a specific entry of an array. Later on when you want to calculate the linear fit, call the sub-vi to return the array of values.
    Stu

  • How do you plot multiple curves on the same graph when using a while loop?

    I am writing a program that will plot the IV Output chracterisitcs curves for a MOSFET transistor. I have two sweep variables Vg and Vd. For each Vg valve selected, Vd is swept from its start to stop voltage creating a graph for that Vg valve. Both of the sweeps are done using while loops. Ideally I would like to display all of the Vg plots on the same graph while having the ability to do real-time graphing. Can anyone help me figure this problem out? I have attached my program. Thanks!!
    Tammy
    Attachments:
    outputfin2.vi ‏165 KB

    Hi Tammy & Tica T,
    As far as I see it - this thread is a very bad version of already existing bad version......
    http://forums.ni.com/ni/board/message?board.id=170&message.id=127857
    I expected, that an Applications Engineer from NI knows something about  a Transistor and how an Output characteristic looks like !!  Take a look to a typical Transistor Datasheet ( e.g. n-channel MOSFET) - you will see, that there is no relation of ID vs Time like in your example ( values vs time )  but  IDrain vs VDrain at different VGate's ( no relation to Mr. Bill Gates ).
    Find attached a vi, that in general does what you need - drawing of  curves vs x-axis (XY-graph in use)  - in test_sweep.zip.  And that you geet an impression, how it might be done ...... dynamic Output characteristic of a Transistor with Standard Equipment of a Lab ( Scope + Generator + Power Supply ) find in addition a Frontpanel - picture. One of the interesting points here is - the self-heating effect; visible on ch3 of scope - 5µs Pulse is already a very long time...... This measurement was done in order to compare with our own Transistors......... 
    Hope this helps a little bit to understand, what we are talking about.
    Regards
    Werner
    Attachments:
    test_sweep.zip ‏358 KB
    dynamic Transistor char.png ‏65 KB

  • Help needed with while loops please :)

    I'm beginning to study java at School.
    My assignment using while loops, to ask user to input 2 numbers.
    I have to output all odd number between the two.
    I have to output the sum of all even numbers between the two.
    Output all the numbers and their squares between 1-10.
    Output the squares of the odd numbers between the 2 numbers the user entered.
    Output all uppercase letters.
    If anyone can give me any help, I would appreciate it greatly.
    Thank you.
    Kelly.

    It would help if you put aside your code, and wrote out some pseudo-code first so that you understand the steps you will need to take. for example
    get input from user
    set counter to first number entered
    while counter less than/ equal to second number
          check if number is even
               if even, add to even_sum
               else output counter, along with its square
          increment counter by one
    end while
    output sum of evensthat block, when coded, will solve 3 of the problems, the other 2 will require separate loops
    Good Luck

  • Help with while loops

    Im trying to create a while loop that outputs the revers of a string, eg nice one
    would be "eno ecin" Assuming i already have declared a variable intital string that holds the string, how do i go about this does anyone have any problem solving techniques. The charAt method needs to be used.

    i have a exam on saturday and it was a previous exam question that im trying to get help with i need to understand the course material thanks, i know how to use while loops but have trouble getting my head around this question. ill show you my code however i know its completely wrong.
    now i know i hvae to use the charAt method to return a character located at the integer i
    so i must go down after each case has been tested true therefore i want i=i-1;
    until i=0;
    String initialString="tucan";
    int i=initialString.length();
    while(i>0)
         return charAt();
         i=i-1;
         }

  • Capturing of time taken by a while loop in bpm

    Hi ,
    I have a busniess process ,and my receive step is defined in a while loop.
    so it starts with a while loop.
    I want to keep a condition on the while loop that it should receive the messages only for a period of 1 hour ,and if it exceeds this period it should end up the process triggeringa mail.
    I mean to say if there are 12 records to be processed through the while loop ...and if I receive only 11 records ..it will be waiting for that final record in an infinite loop ..so I dont want that ...instead if the total no of records are reached then it should move forward ..If it is waiting for the missing records for an hour ..I should stop the process and trigger a mail to the queue monitor saying that record is missing...I have finished the process without this processing time condition successfully..
    I am new to XI and I dont have any idea on how to capture this processing time of while loop.
    can some one please help me out in this issue...
    Thank you in advance...

    Hi Latika,
    Yeah I understand we can go with fork but why I am going with this is ,I have already designed a Payload dependent loop ,by using while loop.so it makes my job simple ...
    Now I am converting it to time dependent loop,so only the final question I have is...In the time dependent loop documentation ..they have taken it as infinite loop and only kept the time limit in the deadline branch...so when the deadline reaches they trigger something.
    If you go to the documentation of time dependent loop(http://help.sap.com/saphelp_erp2005vp/helpdata/en/08/16163ff8519a06e10000000a114084/content.htm) ..they took the infinite loop...in this loop if I mention the counter ..and if this record count triggers before the time limit...it should come out of the block...would it work this way ?
    Thanks a lot...

  • While loop in subVI

    Hello
    I have a doubt about using while loops in VI and subVI. I have a VI, with two loop that are executed in parallel, and stoped with the same button, by using property nodes and references. One of the while loop executes a subVI.
    If the Block Diagram of the subvi there is a while loop covering all the code, it's the same to put it in the main VI with another while loop, or it's not necessary?
    it's the same if this subVI has a while loop covering itself that if the subvi doesn't have this while loop because the loop is in the same VI?
    Thank you very much

    Hello,
    I hope I understood you correctly... In general, it's better to use sub VIs to organize and modularize your code. So, if you can separate part of the code into a sub VI, do it.
    And if your main VI is calling the sub VI in a loop, the sub VI executes every iteration of the loop. So, you do not need a loop in sub VI, normally. But it depends on what exactly you are trying to do.
    Use the Execution Highlight mode (the light bulb on the diagram toolbar) to see how the code gets executed, and make changes accordingly.
    Regards,
    Khalid

  • Crash when calling dlll built by LV using timed loop.

    I have built a dll with Labview 7.1. Then I use VC++ 6.0 to call this dll. Everything is fine except that it will crash after the whole program finishes.  Without timed loop the program can exit normally. When built to exe file, it can also run normally. This happens in both Windows2000 and Windows XP.
    Anyone knows the reason for this?
    Thanks!

    Now the timed loop stops correctly everytime both in Labview environment and standalone exe. But when I call the dll version from C. The c program has no response after the program finishes.
    I built another small vi without timed loop to dll and called it. The c program exit normally. What is the problem?
    The period of timed loop is 50ms. Is it too short? I found from other post that maybe I should use while loop instead of timed loop. But i need very accurate controling of time.
    Any suggestions?
    Thanks!

Maybe you are looking for

  • How to activate data in ODS using ABAP code

    Hi Question like in subject. THX Adam

  • Why do i have 2 boot camp icons in the Dock?

    Setting up new iMac and when exploring Boot Camp, I see 2 Boot Camp icons in the Dock. When I try to remove one, I see the puff of smoke but then it returns. What did I do wrong? Returning to Mac after years on PC.

  • Wrong Purchase order please help

    Frdns i posted PO with wrong vendor, so is there any way i can change the vendor on the same PO or i can cancel the PO ? Please help Thanks

  • Photos- Slideshow

    I want to use the ipad as a digital picture frame- I currently have 40 pictures loaded in an album in my slideshow using the photo app. However, once the 40 pictures cycle once, the slideshow stops, it there a way to make this continuously run until

  • Include in XML Code

    I'm not a XML guru and the only way I found to "include" a fixed xml part (in order to avoid to repeat it many times) is the & wich refers to an ENTITY in the DTD wich poins to an external file. Sometime, however, the DTD can't be changed. Could some