how to calculate the sum JAVA

Discussion in 'Software' started by pradiptalaras, Nov 29, 2012.

  1. pradiptalaras

    pradiptalaras Private E-2

    input number : 10
    output number : 1+2+3+4+5+6+7+8+9+10 = 55

    use looping "WHILE"
     
  2. PC-XT

    PC-XT Master Sergeant

    A for loop would be easier to use. It's basically a while loop combined with an initialization and iterator. What is this routine for?
     
  3. pradiptalaras

    pradiptalaras Private E-2


    yea i knew for loop is easier but my college teacher asked me to use while loop..

    damn..!! it's so complicated logic... help me pls.. its for my final project in my java algorithym class
     
  4. PC-XT

    PC-XT Master Sergeant

    It's best to ask your teacher for help, for many reasons. If you follow our instructions, it may not be what your teacher is looking for. It's your teacher's job to help you. We're just volunteering information. My advice would be to split the assignment into parts. Go through the process on paper or with beads or something to get that sequence, then make the computer do the same thing. Then, change it so the computer adds the sequence. Try to solve it with a for loop, if that's easier, then convert it to a while loop doing the same thing. Keep solving the small parts, then put them together into the final project. You can do it. :)
     
  5. pradiptalaras

    pradiptalaras Private E-2


    Okay, thanks for your advice, i'll keep try it.. complicated doesn't mean it can't be done.. :cool
     
  6. Speculant

    Speculant The Confused One

    Always ask the professor for help. I never did and it screwed me over, now I have to retake the class...
     
  7. skyler43@123

    skyler43@123 Private E-2

    package sumusingwhile;
    import java.util.*;
    public class SumUsingWhile {
    int number, index_, sum;

    public void read_input(){
    System.out.println("Give me the number: "); //10 in your case
    Scanner sc = new Scanner(System.in);
    number = sc.nextInt();
    }
    public void make_sum(){
    index_ = 1;
    sum = 0;
    while(index_ <= number){
    sum += index_;
    index_++;
    }
    }
    public void print_result(){
    System.out.println("The final sum is: " + sum);
    }

    public static void main(String[] args) {
    SumUsingWhile ob = new SumUsingWhile();
    ob.read_input();
    ob.make_sum();
    ob.print_result();
    }
    }
     
  8. red death68

    red death68 Command Sergeant Major

    most of these should work are you trying to accomplish a gui window with a textfield that they enter the number in and it basicly adds all the numbers in order as it counts so 10 becomes 1+2+3+4+5+6+7+8+9+10? and all with a while loop?
     
  9. red death68

    red death68 Command Sergeant Major

    ok finally fixed a few problems i was running into with how the string displayed but try this.

    Code:
    import java.awt.FlowLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JTextField;
    import javax.swing.JLabel;
    
    
    public class inputCounter extends JFrame
    {
    	protected JFrame frame = new JFrame();
    	protected JLabel inputLabel, outputLabel, errorlabel, answerLabel;
    	protected JTextField inputField;
    	protected JButton calc;
    	protected int input;
    	
    	public inputCounter()
    	{
    		setLayout(new FlowLayout());
    		inputLabel = new JLabel("Input");
    		add(inputLabel);
    		inputField = new JTextField(5);
    		add(inputField);
    		outputLabel = new JLabel("Answer");
    		add(outputLabel);
    		answerLabel = new JLabel();
    		add(answerLabel);
    		JButton button = new JButton("Calculate Sum");
    		add(button);
    		event e = new event();
    		button.addActionListener(e);
    		//answerField.setEditable(false);
    		errorlabel = new JLabel("");
    		add(errorlabel);	
    	}
    	
    	public static void main (String args[]) 
    	{
    		inputCounter gui = new inputCounter();
    		gui.setVisible(true);
    		gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		gui.setSize(230, 300);
    	}
    	
    	public class event implements ActionListener
    	{
    		public void actionPerformed(ActionEvent e)
    		{
    			try
    			{
    				input = (int) (Double.parseDouble(inputField.getText()));
    				boolean m = false;
    				String test = "";
    				int finalanswer = 0;
    				int k = 0;
    				
    				while (m == false)
    				{
    					if (k == 0)
    					{
    						test = "";
    					} else if(k == 1)
    					{
    						test = "" + k;
    					}
    					
    					test = test + " + " + k;
    					
    					finalanswer = finalanswer + k; 
    					if (k >= input)
    					{
    						m = true;
    					}
    					k++;
    				}
    				if (test.contains("1 + 1"))
    				{
    					test = test.replace("1 + 1", "1");
    				}
    				answerLabel.setText(test + " = " + finalanswer);
    				
    			} catch (Exception ex)
    			{
    				errorlabel.setText("Please enter only numbers");
    			}
    		}
    	}
    }
    

    It was an interesting experiment for me as I am still rather new at java and gui specifically but I hope this helps you I am definently keeping this one for myself lol
     
  10. PC-XT

    PC-XT Master Sergeant

    Case in point: I haven't seen an answer yet that follows the directions exactly. :p
    I don't mean to offend the others trying to help.:-o It's just that if I were the teacher, I might give these answers a bad grade for not following the directions properly, because you are supposed to know "between the lines," and we don't. I'm assuming you meant those directions literally, as a teacher would write them.

    jessieryder's code shows a good example of how to add numbers. Your assignment is more complicated than that, but I think you know that from experience shown in your other posts.

    skyler43@123's reply has more complication, but maybe too much. It's thought out, and satisfies the usual requirements for a programmer, however, this sounds like a code structure lesson, so that's where the teacher will be looking. It may be that your algorithm is supposed to decrement through the given sequence. There may be other code structure requirements your teacher has taught you that we don't use. In practice, it's not a big deal unless others are working on the same source, and even then, your teacher's job is to look even closer than that. It helps expand your abilities so that you can express yourself better when the requirements are removed.

    red death68's answer gives the sequence, as a text formula. It's also thought out and tested, however, an "output formula" is not an "output number". That sounds like a way I would get a question wrong. ;)

    In short, you know the requirements better than we do. I don't know enough to say if any of these would pass or not :confused but I wouldn't risk it, myself. I would read them, and learn from them, but write my own. You can do it. :)
     
    Last edited: Jan 7, 2013

MajorGeeks.Com Menu

Downloads All In One Tweaks \ Android \ Anti-Malware \ Anti-Virus \ Appearance \ Backup \ Browsers \ CD\DVD\Blu-Ray \ Covert Ops \ Drive Utilities \ Drivers \ Graphics \ Internet Tools \ Multimedia \ Networking \ Office Tools \ PC Games \ System Tools \ Mac/Apple/Ipad Downloads

Other News: Top Downloads \ News (Tech) \ Off Base (Other Websites News) \ Way Off Base (Offbeat Stories and Pics)

Social: Facebook \ YouTube \ Twitter \ Tumblr \ Pintrest \ RSS Feeds