This week's book giveaway is in the Design forum.
We're giving away four copies of Design for the Mind and have Victor S. Yocco on-line!
See this thread for details.
Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

how to i/p numbers

 
Sanjul Jain
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello!

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,
Sanjul
 
rahul V kumar
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
br.readLine();

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
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());
}
System.out.println(i);
}
}

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

good luck
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic