Calculator Array

Hi everyone,
Making an array for a calculator, and am stuck and have 57 similar errors. If someone can check what's wrong and show it to me that'll be great...
Thanks
PART 1
import javax.swing.*;
public class TestMySwing{
     * @param args
     public static void main(String[]args){
          try{
     CalculatorSwing frame = new CalculatorSwing();
     frame.setVisible(true);
     }catch(Exception e){
          System.out.println("My Exception"+e.toString());
PART 2
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class CalculatorSwing extends JFrame{
     public CalculatorSwing(){
     setTitle("Calculator");
     //setSize(300,200);
     addWindowListener(new WindowAdapter(){
          public void windowClosing(WindowEvent e){
               System.exit(0);
     Toolkit tk = Toolkit.getDefaultToolkit();
     Dimension d = tk.getScreenSize();
     int screenHeight = d.height;
     int screenWidth = d.width;
     System.out.println(screenHeight+":"+screenWidth);
     setSize(180,270);//screenWidth/2, screenHeight/2);
     setLocation(screenWidth/4,screenHeight/4);
     Container contentP = getContentPane();
     contentP.add(new ButtonPanel());
class ButtonPanel extends JPanel implements ActionListener{
     public ButtonPanel(){
          oneButton = new JButton("1");
          twoButton = new JButton("2");
          threeButton = new JButton("3");
          fourButton = new JButton("4");
          fiveButton = new JButton("5");
          sixButton = new JButton("6");
          sevenButton = new JButton("7");
          eightButton = new JButton("8");
          nineButton = new JButton("9");
          zeroButton = new JButton("0");
          eqButton = new JButton("=");
          plusButton = new JButton("+");
          minusButton = new JButton("-");
          multiplyButton = new JButton("*");
          divideButton = new JButton("/");
          cButton = new JButton("C");
          dotButton = new JButton(".");
          displayCalc = new JTextField("",12);
          displayCalc.setEditable(false);
     JButton[]name = newJButton[oneButton,twoButton, threeButton,
fourButton, fiveButton, sixButton, sevenButton, eightButton, nineButton,
zeroButton, eqButton, plusButton, minusButton, multiplyButton, divideButton,
cButton, dotButton];
     for (i=0; i<17; i++){
          add(button);
     for (i=0; i<17; i++){
          buttons[i].addActionListerner(this);
// myGlass();
public void painComponent(Graphics g){
super.paintComponent(g);
// g.drawString("Hello to everybody!",75,100);
public double performOperation(char ch1, double num){
if (ch1=='-'){
num-=Double.parseDouble(displayCalc.getText());
}else if(ch=='+'){
num+=Double.parseDouble(displayCalc.getText());
}else if(ch=='/'){
num=num/Double.parseDouble(displayCalc.getText());
}else if(ch=='*'){
num*=Double.parseDouble(displayCalc.getText());
return num;
public boolean checkVal(char chh){
if (chh=='-'||chh=='+'||chh=='/'||chh=='*'){
return true;
}else{
return false;
public void actionPerformed(ActionEvent evt){
Object source = evt.getSource();
Color color = getBackground();
if(source == eqButton){
if(checkVal(ch)){
displayCalc.setText(""+performOperation(ch, tempNo));
//displayCalc.setText(""+((Interger.parseInt(displayCalc,getTExt()))+7));
}else if(source == dotButton){
displayCalc.setText(displayCalc.getText()+".");
System.out.println("1");
}else if(source == oneButton){
displayCalc.setText(displayCalc.getText()+"1");
System.out.println("1");
}else if(source == twoButton){
displayCalc.setText(displayCalc.getText()+"2");
System.out.println("2");
          }else if(source == threeButton) {
displayCalc.setText(displayCalc.getText()+"3");
System.out.println("3");
}else if(source == fourButton) {
displayCalc.setText(displayCalc.getText()+"4");
System.out.println("4");
}else if(source == fiveButton) {
displayCalc.setText(displayCalc.getText()+"5");
System.out.println("5");
}else if(source == sixButton) {
displayCalc.setText(displayCalc.getText()+"6");
System.out.println("6");
}else if(source == sevenButton) {
displayCalc.setText(displayCalc.getText()+"7");
System.out.println("7");
}else if(source == eightButton) {
displayCalc.setText(displayCalc.getText()+"8");
System.out.println("8");
}else if(source == nineButton) {
displayCalc.setText(displayCalc.getText()+"9");
System.out.println("9");
}else if(source == zeroButton) {
displayCalc.setText(displayCalc.getText()+"0");
System.out.println("0");
}else if(source == plusButton) {
ch='+';
tempNo=Double.parseDouble(displayCalc.getText());
displayCalc.setText("");
System.out.println("+");
}else if(source == minusButton) {
ch='-';
tempNo=Double.parseDouble(displayCalc.getText());
displayCalc.setText("");
System.out.println("-");
}else if(source == multiplyButton) {
ch='*';
tempNo=Double.parseDouble(displayCalc.getText());
displayCalc.setText("");
System.out.println("*");
}else if(source == divideButton) {
ch='/';
tempNo=Double.parseDouble(displayCalc.getText());
displayCalc.setText("");
System.out.println("/");
}else if(source == cButton){
tempNo = 0;
displayCalc.setText("");
repaint();
private JButton eqButton;
private String calcText = "";
private String textDisp ="";
private double tempNo=0.0;
private char ch='s';
private JButton minusButton;
private JButton plusButton;
private JButton multiplyButton;
private JButton divideButton;
private JButton oneButton;
private JButton twoButton;
private JButton threeButton;
private JButton fourButton;
private JButton fiveButton;
private JButton sixButton;
private JButton sevenButton;
private JButton eightButton;
private JButton nineButton;
private JButton zeroButton;
private JTextField displayCalc;
private JButton cButton;
private JButton dotButton;
Edited by: Hao.Tran on Nov 26, 2007 9:26 PM

Hao.Tran wrote:
it compiles but the there is a 'class' or 'interface' expected for lines 64 and lines 172-193 (those being the last like 20).That's not the only error you got I only made your code compilable and runnable.
You still have a long way to go and your code is a mess.
In the future Swing related questions should be posted in the Swing forum.
http://forum.java.sun.com/forum.jspa?forumID=57
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class CalculatorSwing extends JFrame {
    public CalculatorSwing(){
        setTitle("Calculator");
        //setSize(300,200);
        addWindowListener(new WindowAdapter(){
            public void windowClosing(WindowEvent e){
                System.exit(0);
        Toolkit tk = Toolkit.getDefaultToolkit();
        Dimension d = tk.getScreenSize();
        int screenHeight = d.height;
        int screenWidth = d.width;
        System.out.println(screenHeight+":"+screenWidth);
        setSize(180,270);//screenWidth/2, screenHeight/2);
        setLocation(screenWidth/4,screenHeight/4);
        Container contentP = getContentPane();
        contentP.add(new ButtonPanel());
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new CalculatorSwing().setVisible(true);
class ButtonPanel extends JPanel implements ActionListener {
    public ButtonPanel() {
        oneButton = new JButton("1");
        twoButton = new JButton("2");
        threeButton = new JButton("3");
        fourButton = new JButton("4");
        fiveButton = new JButton("5");
        sixButton = new JButton("6");
        sevenButton = new JButton("7");
        eightButton = new JButton("8");
        nineButton = new JButton("9");
        zeroButton = new JButton("0");
        eqButton = new JButton("=");
        plusButton = new JButton("+");
        minusButton = new JButton("-");
        multiplyButton = new JButton("*");
        divideButton = new JButton("/");
        cButton = new JButton("C");
        dotButton = new JButton(".");
        displayCalc = new JTextField("",12);
        displayCalc.setEditable(false);
        JButton[] name = {oneButton,twoButton, threeButton,
        fourButton, fiveButton, sixButton, sevenButton, eightButton, nineButton,
        zeroButton, eqButton, plusButton, minusButton, multiplyButton, divideButton,
        cButton, dotButton};
        int i;
        for (i = 0; i < 17; i++) {
            add(name);
for (i = 0; i < 17; i++) {
name[i].addActionListener(this);
// myGlass();
public void painComponent(Graphics g) {
super.paintComponent(g);
// g.drawString("Hello to everybody!",75,100);
public double performOperation(char ch1, double num) {
if (ch1=='-'){
num-=Double.parseDouble(displayCalc.getText());
}else if(ch=='+'){
num+=Double.parseDouble(displayCalc.getText());
}else if(ch=='/'){
num=num/Double.parseDouble(displayCalc.getText());
}else if(ch=='*'){
num*=Double.parseDouble(displayCalc.getText());
return num;
public boolean checkVal(char chh) {
if (chh=='-'||chh=='+'||chh=='/'||chh=='*'){
return true;
}else{
return false;
public void actionPerformed(ActionEvent evt) {
Object source = evt.getSource();
Color color = getBackground();
if(source == eqButton){
if(checkVal(ch)){
displayCalc.setText(""+performOperation(ch, tempNo));
//displayCalc.setText(""+((Interger.parseInt(displayCalc,getTExt()))+7));
}else if(source == dotButton){
displayCalc.setText(displayCalc.getText()+".");
System.out.println("1");
}else if(source == oneButton){
displayCalc.setText(displayCalc.getText()+"1");
System.out.println("1");
}else if(source == twoButton){
displayCalc.setText(displayCalc.getText()+"2");
System.out.println("2");
}else if(source == threeButton) {
displayCalc.setText(displayCalc.getText()+"3");
System.out.println("3");
}else if(source == fourButton) {
displayCalc.setText(displayCalc.getText()+"4");
System.out.println("4");
}else if(source == fiveButton) {
displayCalc.setText(displayCalc.getText()+"5");
System.out.println("5");
}else if(source == sixButton) {
displayCalc.setText(displayCalc.getText()+"6");
System.out.println("6");
}else if(source == sevenButton) {
displayCalc.setText(displayCalc.getText()+"7");
System.out.println("7");
}else if(source == eightButton) {
displayCalc.setText(displayCalc.getText()+"8");
System.out.println("8");
}else if(source == nineButton) {
displayCalc.setText(displayCalc.getText()+"9");
System.out.println("9");
}else if(source == zeroButton) {
displayCalc.setText(displayCalc.getText()+"0");
System.out.println("0");
}else if(source == plusButton) {
ch='+';
tempNo=Double.parseDouble(displayCalc.getText());
displayCalc.setText("");
System.out.println("+");
}else if(source == minusButton) {
ch='-';
tempNo=Double.parseDouble(displayCalc.getText());
displayCalc.setText("");
System.out.println("-");
}else if(source == multiplyButton) {
ch='*';
tempNo=Double.parseDouble(displayCalc.getText());
displayCalc.setText("");
System.out.println("*");
}else if(source == divideButton) {
ch='/';
tempNo=Double.parseDouble(displayCalc.getText());
displayCalc.setText("");
System.out.println("/");
}else if(source == cButton){
tempNo = 0;
displayCalc.setText("");
repaint();
private JButton eqButton;
private String calcText = "";
private String textDisp ="";
private double tempNo=0.0;
private char ch='s';
private JButton minusButton;
private JButton plusButton;
private JButton multiplyButton;
private JButton divideButton;
private JButton oneButton;
private JButton twoButton;
private JButton threeButton;
private JButton fourButton;
private JButton fiveButton;
private JButton sixButton;
private JButton sevenButton;
private JButton eightButton;
private JButton nineButton;
private JButton zeroButton;
private JTextField displayCalc;
private JButton cButton;
private JButton dotButton;

Similar Messages

  • Calculating Arrays

    This is my first Java course. I have to create an array that stores 20 prices. I have
    double[] prices = {2.34, 7.89, 1.34,5.00,5.89, 3.59, 4.83, 6.72, 1.89,
    .89,2.00, 3.00, 6.53, 4.32, 1.66,10.99, 19.99,7.45, 25.95,.99};
    Then we have to display the sum of all the prices and calculate the average price.
    It sounds easy. I can do it in C++ but some how I do not know how to code it in java. Our text does not explain it well enough.
    I suspect that I have to use a method. I know how to create methods but not for an array.
    Can anyone help with an example?

    This is what you want?
    import java.text.DecimalFormat;
    class ArrayTest
         public static void main(String args[]) //main method
         DecimalFormat twoDigits = new DecimalFormat("0.00"); //two digits after the dot(.), adjust to your needs
         double sum =0.0, average=0.0; //sum & average variables
         double[] prices ={ 2.34, 7.89, 1.34, 5.00, 5.89, 3.59, 4.83,
                            6.72, 1.89, 0.89, 2.00, 3.00, 6.53, 4.32,
                            1.66, 10.99, 19.99, 7.45, 25.95, 0.99 };
          for (int i=0; i<20; i++)
            sum = sum + prices; //the sum
         average = sum/20; //the average
         System.out.println("The sum is: " + twoDigits.format(sum));
         System.out.println("The average is: " + twoDigits.format(average));
    Study it, Anything you don't understand let me know.
    AA

  • Refreshing an array

    i have chess program which has newgame() method inside it
    with local array
    now i implemented loading postion of my game form file and when i load game it display board [with new array(array in updateloaded from file)] but still use [arrays in (defualt)new game] as its calculation array how can i reset value(in new game) [it correct itself after the first move) i think it construct progame with old value and it refresh them when it through it once.it work properly after other player make its move
    how can i tell loadgame with load arrays rather arrays in newgame.
    does anything to do with how i initial the array.
    tanx
    [code]
    Class Board{
    int loadboard[]= new int [120];
    int loadboardcolor[]= new int [120];
    public void drawloadBoard(){  
    updateload();
    repaint();
    }public void updateload()
    {     for (int i=21;i<99 ;i++ )           
    { board<i>=loadboard<i>;
    boardcolor<i> = loadboardcolor<i>;
    }public void newgame ()
    {     //generate original position 
         int [] openningpostion = {     7,Pawn,Pawn,Pawn,Pawn,Pawn,Pawn,Pawn,Pawn,7,          7,FreshRook,Knight,Bisshop,Queen,Freshking,Bisshop,
    Knight,FreshR };     
    int [] Coloropenning=     {     7,White,White,White,White,White,White,White,White,7,          7,White,White,White,White,White,White,White,White,7,            };}          
    // here it method which should update my board     
    for (int i=0; i < 120; i++)          
    { board <i> = openningpostion <i>;
         boardcolor<i> = Coloropenning<i>;      }}
    tanx

    I tried your code and it did work. I implemented your suggestion but in my application it keeps adding the new data as an additional curve. I cannot append the new data, even if the shift register feeds the data into the build array. I can't see at the moment what I did wrong...
    Attachments:
    waveform_graph_udate_2.PNG ‏50 KB
    waveform_graph_udate_2_front_panel.PNG ‏32 KB

  • Char loop problem

    Hi,
    I'm having trouble with this char loop of mine. It tells me that there is a .class that is expected and I'm not too sure as to what that is...
    I'd like each value coming out of the loop to go into this char array and then to be converted to a string
    for (char x= ' '; x <= '~'; x++)
             char[] myChars = x.toCharArray();
                String y = new String(myChars);Can anybody help me please? Much appreciated!

    Let's look at your code each line at a time.
    StringBuffer catcher = new StringBuffer();     creates the stringbuffer, no problem here
    int arrsize = 128;
    char[] arrs = new char[arrsize]; creates an array of char 0 to 127. Perhaps unknown to you, but I believe that this array is initialized such that each element is set equal to 0 or more precisely, (char)0.
    for (char x= ' '; x <= '~'; x++)
    catcher.append(arrs[x]);Here's a problem. Loops through all chars of interest. That's ok, BUT you haven't done anything to the array. It's still filled with nothing but 0's, and then you take elements of the array (not starting at array index 0 mind you), and stick them into the StringBuffer. In the end what do you have? A StringBuffer that is stuffed with nothing but (char)0. Not very useful at all. You need to do a couple of things here and you have a choice.
    1. First and foremost, always use curly braces in all of your for loops, if, else, and similar statements. It may seem like overkill, but it will save you a world of worry some day, trust me.
    2. Next either put the correct char in the array or in the StringBuffer. The correct character is x, just x, not arrs[x], but just simply x. So to put it into your StringBuffer you'd call cather.append(x);
    3. As an alternative, you could fill the array, but if you did, you should start at index 0, not index (int)' '. That can be done like so:
    import java.util.Arrays;
    public class Fubar2
        public static void main(String[] args)
            char firstChar = ' '; // to make it easy later
            char lastChar = '~'; // to make it easy later
            // let java do the dirty work of calculating array size
            int arrsize = lastChar - firstChar + 1;
            char[] arrs = new char[arrsize];
            for (char x = firstChar; x <= lastChar; x++)
                arrs[x - firstChar] = x; // array index starts at 0
            System.out.println(Arrays.toString(arrs));
    }

  • Make sure objectoutputstream is open before objectinputstream

    If I am not mistaken the objectoutputstream must be opened before the objectinputstream is for the connection to be made correctly. My task is to send an array from one computer to another through a socket, do some calculation then send back the calculated array. So I need to have communications both ways. I am running into problems with the connection not being made because I think the timing is off. On a small scale (2 computers) everything works fine, but for 1 computer trying to connect to multiple others (7) it isn't working.
    Should I give up on object streams or is there a way to coordinate their openings? Thank you.
    BTW-- the error message I get at the initial receiving computer is an IOException and the getMessage() returns null. This is the same error that i got on my small scale when I had objectinputstream opening before objectoutputstream.

    icccapital wrote:
    I don't know how reliable this source is, but here is the link where I had read that.
    http://frequal.com/java/OpenObjectOutputStreamFirst.html
    You seem to have misunderstood.that article. It doesn't not say that you have to construct the OOS that sends before you constuct the OIS at the other end that receives. Rather, it says that, on each end when you're doing bidirectional communication (which you are), you should construct that end's OOS before constructing its OIS. If you do this:
    // client
    ObjectInputStream ois = new ObjectInputStream(...);
    ObjectOutputStream oos = new ObjectOutputStream(...);
    // server
    ObjectInputStream ois = new ObjectInputStream(...);
    ObjectOutputStream oos = new ObjectOutputStream(...);then both sides are stuck in the OIS line because the OIS c'tor doesn't return until it reads something, but neither one can read because the other end--both other ends--can't write because it's can't get past the OIS. It's a form of deadlock.
    So, theoretically, all you should have to do is switch the order and put OOS first on just one side, but to keep things simple I'd just do it on both:
    // client
    ObjectOutputStream oos = new ObjectOutputStream(...);
    ObjectInputStream ois = new ObjectInputStream(...);
    // server
    ObjectOutputStream oos = new ObjectOutputStream(...);
    ObjectInputStream ois = new ObjectInputStream(...);Again, remember, you don't have to worry about controlling the timing of the client and server relative to each other. It's just within each side, you want that side's OOS first.
    Now, here's one thing I'm not sure of. I looked briefly at the code for both OIS and OOS, and OIS does indeed do a read in it's c'tor, and OOS does a write. I'm not sure why this would be any better. It looks to me like we'd now have both OOS lines blocking waiting to be able to write, so, contrary to what the article is saying (and contrary to what I just said above) it seems--at least at first glance--that we should do OOS first on one end and OIS first on the other. However, if there's buffering going on, then the OOS c'tor could just write its bytes to the buffer and return, without having to wait for them to actually be delivered.

  • VAL_BASE_ZERO_VERTICAL_BAR

    I am trying to plot a histogram (PlotXY....) with the following plot stile:
    VAL_BASE_ZERO_
    VERTICAL_BAR
    Vertical bars are plotted for each plotted point.  The bars extend upward and downward from zero, depending on whether the data value is positive or negative.
    The y-axis is also auto-scaled. All my data points are Greater then ZERO and of type integer.
    I hoped to see a histogram where the y-axis start with ZERO, BUT it starts with the lowest value of the Y-array.
    What am I doing wrong????
    (I don't want to add an extra set of points with the with  Y-value ZERO)
    Solved!
    Go to Solution.

    The behaviour you are observing depends exatly on AutoScale settings: graph scaling operates on array values regardless the plot type): you can test it with the attached simple project.
    However, it doesn't seem to me that this behaviour is to be changed: it acts as if you had manually set axis scaling so that part of the plot lies out of viewable graph area; nevertheless, an update in function documentation may be needed.
    In your situation, you should manually set axis scaling to (0 ÷ max) having calculated array max value before.
    Proud to use LW/CVI from 3.1 on.
    My contributions to the Developer Zone Community
    If I have helped you, why not giving me a kudos?
    Attachments:
    ScaleChange.zip ‏8 KB

  • How do I create a 1d array that takes a single calculation and insert the result into the first row and then the next calculation the next time the loop passes that point and puts the results in thsecond row and so on until the loop is exited.

    The attached file is work inprogress, with some dummy data sp that I can test it out without having to connect to equipment.
    The second tab is the one that I am having the problem with. the output array from the replace element appears to be starting at the index position of 1 rather than 0 but that is ok it is still show that the new data is placed in incrementing element locations. However the main array that I am trying to build that is suppose to take each new calculation and place it in the next index(row) does not ap
    pear to be working or at least I am not getting any indication on the inidcator.
    Basically what I am attempting to do is is gather some pulses from adevice for a minute, place the results for a calculation, so that it displays then do the same again the next minute, but put these result in the next row and so on until the specifiied time has expired and the loop exits. I need to have all results displayed and keep building the array(display until, the end of the test)Eventually I will have to include a min max section that displays the min and max values calculated, but that should be easy with the min max function.Actually I thought this should have been easy but, I gues I can not see the forest through the trees. Can any one help to slear this up for me.
    Attachments:
    regulation_tester_7_loops.vi ‏244 KB

    I didn't really have time to dig in and understand your program in depth,
    but I have a few tips for you that might things a bit easier:
    - You use local variables excessively which really complicates things. Try
    not to use them and it will make your life easier.
    - If you flowchart the design (very similar to a dataflow diagram, keep in
    mind!) you want to gather data, calculate a value from that data, store the
    calculation in an array, and loop while the time is in a certain range. So
    theres really not much need for a sequence as long as you get rid of the
    local variables (sequences also complicate things)
    - You loop again if timepassed+1 is still less than some constant. Rather
    than messing with locals it seems so much easier to use a shiftregister (if
    absolutely necessary) or in this case base it upon the number of iterations
    of the loop. In this case it looks like "time passed" is the same thing as
    the number of loop iterations, but I didn't check closely. There's an i
    terminal in your whileloop to read for the number of iterations.
    - After having simplified your design by eliminating unnecessary sequence
    and local variables, you should be able to draw out the labview diagram.
    Don't try to use the "insert into array" vis since theres no need. Each
    iteration of your loop calculates a number which goes into the next position
    of the array right? Pass your result outside the loop, and enable indexing
    on the terminal so Labview automatically generates the array for you. If
    your calculation is a function of previous data, then use a shift register
    to keep previous values around.
    I wish you luck. Post again if you have any questions. Without a more
    detailed understanding of your task at hand it's kind of hard to post actual
    code suggestions for you.
    -joey
    "nelsons" wrote in message
    news:[email protected]...
    > how do I create a 1d array that takes a single calculation and insert
    > the result into the first row and then the next calculation the next
    > time the loop passes that point and puts the results in thsecond row
    > and so on until the loop is exited.
    >
    > The attached file is work inprogress, with some dummy data sp that I
    > can test it out without having to connect to equipment.
    > The second tab is the one that I am having the problem with. the
    > output array from the replace element appears to be starting at the
    > index position of 1 rather than 0 but that is ok it is still show that
    > the new data is placed in incrementing element locations. However the
    > main array that I am trying to build that is suppose to take each new
    > calculation and place it in the next index(row) does not appear to be
    > working or at least I am not getting any indication on the inidcator.
    >
    > Basically what I am attempting to do is is gather some pulses from
    > adevice for a minute, place the results for a calculation, so that it
    > displays then do the same again the next minute, but put these result
    > in the next row and so on until the specifiied time has expired and
    > the loop exits. I need to have all results displayed and keep building
    > the array(display until, the end of the test)Eventually I will have to
    > include a min max section that displays the min and max values
    > calculated, but that should be easy with the min max function.Actually
    > I thought this should have been easy but, I gues I can not see the
    > forest through the trees. Can any one help to slear this up for me.

  • Recursive calculation on arrays

    I have a 3x10 input array.
    I take row 0, apply a high pass filter, take the log, and then plot it.
    Second round I have another 3x10 array, and apply the same thing on row 0. (all running in a while loop)recursiv
    So my plot would have 20 points, from row 0 (eventually I would do this for all 3 rows)
    Is this different from if I pass it in a 3x20 array at once, and do the processing and then plot it?
    Or is there a way I can save the plotted value on the graph, and just add the new result at the end?
    I am trying to avoid saving all values, so I dont want to use the 3x20 array. I want to do the calculations on 3x10 chunks of data while getting the same results.
    Thanks!!!!!!!!!

    You seem to love the word "recursive" in all your questions, but I don't think it makes sense the way you use it. If the calculations are independent (sometimes they are not!), it does not matter if you do the calculations all at once or piecewise.
    A 2x10 array is tiny. What is your actual concern?
    Your description is very fuzzy. If you want to save historic values inside a graph, you should use a chart instead. Does this have anything to do with your earlier question?
    LabVIEW Champion . Do more with less code and in less time .

  • How can I find the element with the closest value to a calculated "target value" in a 1D array?

    Hello all,
    may be the following question is very simple, but I am relatively new in labview and it would be great if somebody could help me:
    I have a acquaried 1D array of data-points. Now, I have to find the element in this array which value is the closest to a calculated "target value".
    After finding the element with the value close to the "target value", I have to get the position of this element (i.e. the index) in the 1D array.
    Now, I have to use this index to find and extract the element at this position in an other 1D array.
    It would be very nice if somebody could help me with this problem.
    Thank you,
    beam

    Find attached a sample vi that you can modify.
    Attachments:
    select_target_value.vi ‏22 KB

  • Array calculation in ABAP

    hi gurus,
    I have to use array for some calculations. I begin new project and have to calculate distance with using array. I searched forums but I found nothing. please help me?
    thanks,

    #include <stdio.h>
    int main()
    int m,n,mat[100][100],i,j,l;
    int a,b,top,max=50000;
    char k1='c';
    printf("total country = ");
    scanf(" %d", &n);
    printf(" total direction = ");  // total road: A-C is a road B-G is another road
    scanf(" %d", &m);
         for(i=1;i<=n;i++){
              for(j=1;j<=n;j++){
                   mat<i>[j]=max;
    for(i=1;i<=n;i++)
        mat<i><i>=0;
    for(i=1;i<=m;i++)
    printf("enter first country ");
    scanf("%d", &a);
    printf("enter second country",i);
    scanf(" %d", &b);
    printf("intervals of countries");
    scanf("%d", &mat[a]<b>);
    mat<b>[a]=mat[a]<b>;
    for(l=1;l<=n;l++)
         for(i=1;i<=n;i++)
                              for(j=1;j<=n;j++)
                                        top=mat<i>[l] + mat[l][j];
                                              if(top < mat<i>[j]){
                                                 mat<i>[j]=top;
    while(k1 != 'q')
    printf(" enter to find interval of 2 countries = ");
    scanf(" %d", &a);
    scanf(" %d", &b);
    printf(" min interval = %d \n",mat[a]<b>);
    printf(" q for quit any key for continue = ");
    scanf(" %c", &k1);
    intervals: 1) A-B = 600
    2) A-C=50 C-F=150 F-G= 200 G-B=50 (that is A-B = 450)
    3) A-D=100 D-H=200 H-G=50 G-B=50. (that is A-B = 400)
    example records in my table
         A   | B    | C  | D    | F    | G | H
    A | 0   | 600 | 50 | 100 | -     | -   | - 
    B |600 | 0    | -   | -      | -     | 50| -
    C | 50 |  -    | 0   | -      | 150| -   | -
    D |100 | -    | -    | 0     | -    | -   |200
    F |-     | -     |150|  -     | 0   |200|-
    G |-    | 50   |-    | -      | 200| 0  |50
    H |-    |-      | -    | 200 | -     | 50| 0
    after program run
         A   | B     | C   | D    | F    | G    | H
    A | 0    | 400 | 50  | 100 | 200 |350  | 300 
    B |400 | 0     | 400| 300 | 250 | 50   | 100
    C | 50  | 400 | 0    | 150 | 150 | 350 | 400
    D |100 |300  | 150 | 0    | 300 | 250 |200
    F |200 |250  |150  |300  | 0    | 200 |250
    G |350 | 50  |350  | 250 | 200 | 0    |50
    H |300 |100 | 400 | 200 | 250 | 50   | 0
    I dont update my table. I just want find direction and min interval to go from A to B.
    I think not hard for gurus.
    thank all for help.

  • Filtering and calculating averages of array subsets

    I've got a 2-D array coming out of a loop and I need to calculate average for subsets corresponding to iterations 0-9, 10-19, etc..  Additionally, I need to filter out values above and below acceptable limits before calculating average.  Any suggestions for how to approach this?
    Solved!
    Go to Solution.

    My suggestion is to slog through each array subset, use a for loop to add up the values you want, keep track of the number of values, then divide out for the average. 
    Every tenth reading you could clear the sum and counts.
    The results would be saved in an array that only adds a value every tenth loop.
    You could keep track of the one to ten value separately from the number of values accepted ( a.k.a. Filtering).
    So my slog suggestion would be a for loop, two counters ( # accepted values and one to ten count), an array to store the averages and a numeric to hold the sum.
    The filter criteria would produce a Boolean that would toggle adding to the sum and adding to the # accepted values.
    The Sum and the counters need to be shift registers, and as I mentioned, there would be some logic to clear these shift registers every time the 'one to ten' count got to ten
    Mark Ramsdale

  • Calculating Mean & SD in Test Stand Locals Array

    Hi,
    I have an array of data that I would like to process to extract the statistical info like mean, SD etc. Is there a ready made function available in Test Stand to do this without writing custom expressions?
    Thanks

    K_seeker,
    Unfortunately, TestStand does not have built in expression functions for calculating statistical information.  You can see a list of all of the expression functions here:  http://zone.ni.com/reference/en-XX/help/370052H-01/tssuppref/infotopics/operators_function_expr/
    The easiest way to get the information you want is to pass the array to a code module (LabVIEW VI, CVI .dll, .NET assembly, etc.), do the arithmetic there, and pass the final value back to TestStand.
    Josh W.
    Certified TestStand Architect
    Formerly blue

  • Simple Graphing Calculator with 2D array

    Hello,
    I am building a simple graphing calculator which reads in coefficients from a txt file. All is going well except when I plot the points, the graph is at the corner of the screen and sideways. As we all know, the origin of the array is at the top right corner, so how do I transform/slide it so that it is at the xy origin? Code is posted below, thanks!
    import javax.swing.*;
    import java.awt.*;
    public class baseClass extends JFrame{
         private shapesPanel panel;
         public baseClass(String title){
              panel = new shapesPanel();
              setTitle(title);
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              getContentPane().add(panel);
              pack();
              setVisible(true);
         public void drawLine(int x1, int y1, int x2, int y2){
              panel.addLine((short)x1,(short)y1,(short)x2,(short)y2);
              panel.repaint();
         public void drawDot(int x, int y){
              panel.addOval((short)x,(short)y,(short)1,(short)1);
              panel.repaint();
         private class shapesPanel extends JPanel{
              final private short max = 10000;
              private short[][] lines, ovals;
              private int numLines, numOvals;
              public shapesPanel(){
                   setBackground(Color.white);
                   setPreferredSize (new Dimension(500,500));
                   lines = new short[max][4];
                   ovals = new short[max][4];
                   numLines = 0;
                   numOvals = 0;
              public void paintComponent(Graphics g){
                   super.paintComponent(g);
                   g.setColor(new Color(0,0,255));
                   for(int i = 0; i < numLines;++i){
                        g.drawLine(lines[0],lines[i][1],lines[i][2],lines[i][3]);
                   g.setColor(new Color(255,0,0));
                   for(int i = 0; i < numOvals;++i){
                        g.drawOval(ovals[i][0],ovals[i][1],ovals[i][2],ovals[i][3]);
              public void addLine(short x1, short y1, short x2, short y2){
                   lines[numLines][0] = x1;
                   lines[numLines][1] = y1;
                   lines[numLines][2] = x2;
                   lines[numLines][3] = y2;
                   ++numLines;
              public void addOval(short x, short y, short w, short h){
                   ovals[numOvals][0] = x;
                   ovals[numOvals][1] = y;
                   ovals[numOvals][2] = w;
                   ovals[numOvals][3] = h;
                   ++numOvals;
    import java.util.Scanner;
    import java.io.*;
    public class graphingCalculator extends baseClass{
         // CONTAINS THE FOUR FUNCTION COEFFICIENTS
         private double[] theFunction;
    // CONTAINS THE DISCRETE FUNCTION PLOT
    private boolean[][] grid;
    // SIZE OF THE COORDINATE SYSTEM
    private final int columns = 500, rows = 500;
    public graphingCalculator(String filename) throws IOException{
         // INITIALIZATIONS ///////////////////////////////////////
    super("GRAPHING CALCULATOR");
    theFunction = new double[4];
         grid = new boolean[rows][columns];
    for(int i = 0;i<rows;++i){
    for(int j = 0;j<columns;++j){
    grid[i][j] = false;
    // DRAW THE COORDINATE SYSTEM ON THE SCREEN /////////////
    drawLine(0,250,500,250);
    drawLine(250,0,250,500);
    for(int i = 0; i < columns;i+=20){
    drawLine(i,247,i,253);
    for(int i = 0; i < rows;i+=20){
    drawLine(247,i,253,i);
    // GET THE FUNCTION COEFFICIENTS ///////////////////////
    // theFunction[0] will have the x^3 coefficient
    // theFunction[1] will have the x^2 coefficient
    // theFunction[2] will have the x^1 coefficient
    // theFunction[3] will have the x^0 coefficient
    Scanner scan1 = new Scanner(new File(filename));
    for(int i=0;i<4;++i){
         theFunction[i] = scan1.nextDouble();
    scan1.close();
    // DRAW THE FUNCTION ////////////////////////////////////
    computeGrid();
    drawDiscrete();
    drawContinuous();
    private double computeFunction(int x)
         double a=theFunction[0];
         double b=theFunction[1];
         double c=theFunction[2];
         double d=theFunction[3];
         double answer=(a*Math.pow(x,3.0)+b*Math.pow(x,2.0)+c*Math.pow(x,1.0)+d*Math.pow(x,0.0));
         return answer;
    private void computeGrid()
              // Populate the 'grid' array with true values that correspond
              // to the discrete function.
              // The 'grid' array is the internal representation of the function
         for(int x=0; x<columns; x++)
                   if(computeFunction(x)>=0&&computeFunction(x)<500)
                   grid[(int)computeFunction(x)][x]=true;
    private void drawDiscrete()
              // Use drawDot(x,y) to draw the discrete version of the function
         for(int x=0;x<columns;x++)
              for(int j=0;j<rows;j++)
         if(grid[x][j])
              drawDot(x,j);
    private void drawContinuous()
              // Use drawLine(x1,y1,x2,y2) to draw the continuous version of the function

    Rest of code:
    import java.util.Scanner;
    import java.io.*;
    public class Main {
        public static void main(String[] args) throws IOException{
        String infile;
        Scanner scan = new Scanner(System.in);
        // The input file should have 4 doubles in it
        // corresponding to the 4 coefficients of a cubic function.
        // A GOOD EXAMPLE:
        //                  0.01
        //                  0.0
        //                  -5.0
        //                          50.0
        // CORRESPONDS TO FUNCTION: 0.01*X^3 - 5.0*X + 50.0       
        // ANOTHER GOOD EXAMPLE:
        //                  0.0
        //                  0.01
        //                  -1.0
        //                          -100.0
        // CORRESPONDS TO FUNCTION: 0.01*X^2 - X - 100.0       
        System.out.println("Please enter filename of input file: ");
        infile = scan.next();
        graphingCalculator cal = new graphingCalculator(infile);
    }

  • Array size calculation

    Hi All,
    I have a small question.I am using SunOS 5.9 and gcc 4.0 compiler.
    Please take a look at the below code
    When I compile the following program under gcc 4.0 it doesn't give me any compiler error and even the size comes correctly.
    #include<stdio.h>
    int main()
    int c;
    scanf("%d",&c);
    int x[c];
    printf("sizeof =%d\n",sizeof(x));
    But when I use visual studio 2003 compiler it gives me error ( like cannot allocate an array of constant size 0).
    I am bit confused as normall array size should be static rather during runtime.And I am not using malloc in this case also.
    Could you please clarify this.Or is it possible to allocate the array size like this in advanced compilers?
    Looking forward for your response.

    Hello.
    I just tested initializing an array with a variable. It works under GCC 3.3.2. I know no other C compiler which is able to do this! In a C tutorial in the internet I found this:
    You cannot initialize an array using a variable. [...] For example:
      int x = 5;
      int ia[x];Obviously initializing arrays with variables is a GCC extension.
    If the compiler supports the "alloca" instruction you may use this instead:
      int x = 5;
      int *ia = (int *)alloca(sizeof(int) * x);
      // sizeof(ia) is 4 or 8 (32 or 64 bit) here independent of xMartin

  • Calculating mode with interger arrays.

    I'm having some trouble implementing code to search for modes inside of an interger array. The array is of values from 0 to 100.
    public static String modeFinder(int[] input)
    String output = "";
    int[] modes = new int[input.length/2];
    int[] occurances = new int[input.length/2];
    int counter = 0;
    int counter2 = 0;
    for (int i = 0; i < input.length; i++)
    int num1 = input;
    for (int j = 0; j < input.length; j++)
    if (input[i] == input[j])
    counter++;
    if (counter > 1)
    modes[counter2] = num1;
    occurances[counter2] = counter;
    counter2++;
    The last part is where i am having trouble. I esentially need to find the highest value in the occurances array and then check to see if there are multiple modes and then make a connection with the modes array of actual interger values that are a part of the mode. Thanks for any help.

    Now you get to figure out how I did it....
    public class Test {
      public static void main(String[] args) {
        int[] myInt = {1,2,3,4,5,6,7,6,5,4,3,2,1,2,3};
        int min=100, max=0;
        for (int x=0; x<myInt.length; x++) {
          if (myInt[x]>max) max=myInt[x];
          if (myInt[x]<min) min=myInt[x];
        System.out.println("min="+min+" max="+max);
        int[] cnts = new int[max-min+1];
        for (int x=0; x<myInt.length; x++) cnts[myInt[x]-min]++;
        int maxCnt = -1;
        for (int x=0; x<cnts.length; x++) if (cnts[x]>maxCnt) maxCnt = cnts[x];
        for (int x=0; x<cnts.length; x++) if (cnts[x]==maxCnt)  System.out.println("mode at "+(x+min));

Maybe you are looking for