File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes how to i/p numbers Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "how to i/p numbers " Watch "how to i/p numbers " New topic

how to i/p numbers

Sanjul Jain

Joined: Oct 21, 2004
Posts: 14

I am a newbie to Java. I want to write a program that lets user input numbers(integers) seperated by whitespace. The program displays sum of the numbers. Can someone suggest me code for that.

Thanks in advance,
rahul V kumar
Ranch Hand

Joined: May 20, 2003
Posts: 82
You have posted similar question in another thread. And Its answered there.

I am not quite sure how the user is providing you with the values

Is it something like
1) java MyProgram 1 2 3 4
2) java MyProgram
Please enter the numbers that you want to add seperated by spaces

If you are taking the user input through step 1 then its easy. Look at the argument of your main method. Look through that array and see what you get.

If you want a solution for step 2 then you got to do something like this: In your main progam

// prompt the user to enter numbers seperated by spaces
// open up standard input
BufferedReader br = new BufferedReader(new InputStreamReader(;
//Now read the user entered string

The above line has to be in a try catch block.

Read up String Tokenizer and you should be ready to roll.
Jimmy Die
Ranch Hand

Joined: Nov 20, 2003
Posts: 97
Ohh You've probably passed this up, but hear is a way

import java.util.*;
public class TestIt {
public static void main(String args[]){
int i = 0;
StringTokenizer st = new StringTokenizer("20 30 40");
while (st.hasMoreTokens()) {
i += Integer.parseInt(st.nextToken());

Of course if you do not use correct numbers in your string you get the NFException from Integer.parseInt()

good luck

Jimmy Die
I agree. Here's the link:
subject: how to i/p numbers
It's not a secret anymore!