View Single Post
Old 04-10-2009, 12:55 AM   #23 (permalink)
kmote
 

Join Date: Jul 2005

Location: England

Posts: 2,182

kmote has a spectacular aura aboutkmote has a spectacular aura about

Default Re: Reading a book about C#. (newbie question)

Quote:
Originally Posted by Logarithms View Post
What part of it?

edit: Oh, I put "result double = 0;"
Yes, there was that. There is also your while loop. You've made it better but I don't think you want that semicolon there. You should also consider using String.format here System.out.println("The result of your addition was "+result+". \n");


My lazy attempt at this example essentially places the user in an infinite loop allowing them to specify very large positive or negative numbers to be added to a running total, hitting enter displays the running total as it stands.

Code:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import javax.swing.JOptionPane;
import java.math.*;

public class Main {

    public static void main(String[] args) {
        try
        {
            BigDecimal accumulatedTotal = new BigDecimal(0);
            int i = 1;
            BufferedReader buff = new BufferedReader(new InputStreamReader(System.in));
            while(true)
            {
                try
                {
                    System.out.print(String.format("Enter value %d here (hit enter to see current total): ", i));
                    BigDecimal inputVal = new BigDecimal(buff.readLine());
                    accumulatedTotal = accumulatedTotal.add(inputVal);
                    i++;
                }
                catch (NumberFormatException ex)
                {
                    System.out.println(accumulatedTotal.toString());
                }
            }
        }
        catch (IOException ex)
        {
            JOptionPane.showMessageDialog(null, "Oh Dear");
            ex.printStackTrace();
        }
    }

}

__________________
MSI P43 Neo|Enermax Pro82+ 425W|E5200|silent 8500GT|250GB Samsung spinpoint F1|Samsung SATA DVD RW|4GB Corsair|Antec SOLO|openSUSE11


There are in order of increasing severity: lies, darn lies, statistics, and computer benchmarks. - diskinfo man page
kmote is online now