开发者

Input 5 integers using StringTokenizer

Below is the partial code.

import java.io.*;
import java.util.*;
public class inputting {
public static void main(String[] args) throws IOException {
    // TODO Auto-generated method stub
    int i,j;

    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
     System.out.println("enter numbers??");
     String str = br开发者_运维百科.readLine();
     StringTokenizer tokenizer = new StringTokenizer(str);
     j=Integer.parseInt(tokenizer);
}
}

Now I don't know where would StringTokenizer go and whether what I have done till now is correct or not. But basically I want user to ask for 5 integers and then let say just print it.

How do I take the integers out of the strings? If someone could complete the code for me, I would really appreciate.

P.S. This is not a homework question, I am learning object oriented programming and not Java. So our professor didn't care enough to teach us the syntax of Java completely.


You would use StringTokenizer to break up a string into multiple strings(or tokens) using a specified delimiter.

For example:

String sample = "1,2,3,4,5";
StringTokenizer tokenizer = new StringTokenizer(sample,",");

while(tokenizer.hasMoreTokens()) {
  int convertedToInt = Integer.parseInt(tokenizer.nextToken());
}

Note: didn't run this, might contain syntax error, but you get the idea.

StringTokenizer JavaDoc here: http://download.oracle.com/javase/1.4.2/docs/api/java/util/StringTokenizer.html


You may find it easier to use a string's split() method.

import java.io.*;
import java.util.*;
public class inputting {
public static void main(String[] args) throws IOException {
    // TODO Auto-generated method stub
    int i,j;

    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
     System.out.println("enter numbers??");
     String str = br.readLine();
     String[] nums = str.split(" "); //returns an array of strings split based on the parameter
     i = Integer.parseInt(nums[0]);
     j = Integer.parseint(nums[1]);
}
}

the line j=Integer.parseInt(tokenizer); will not compile, a StringTokenizer is not a string. j=Integer.parseInt(tokenizer.nextToken()); will compile because that is a string, so feel free to use that rather than the code presented above that uses the split() method from the String class.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜