• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
  • Campbell Ritchie
  • Liutauras Vilda
  • Jeanne Boyarsky
  • Devaka Cooray
  • Paul Clapham
  • Tim Cooke
  • Knute Snortum
  • Bear Bibeault
Saloon Keepers:
  • Ron McLeod
  • Tim Moores
  • Stephan van Hulst
  • Piet Souris
  • Ganesh Patekar
  • Frits Walraven
  • Carey Brown
  • Tim Holloway

how to i/p numbers

Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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,
Ranch Hand
Posts: 82
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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(System.in));
//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.
Ranch Hand
Posts: 97
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!