-1

I want to enter in a few numbers in a single line like so,

14 53 296 12 1

and separate the numbers by a space, and place them all in an array. How would I go about doing this? Also, how could I make sure that every number they entered was an integer and they entered less than 10 numbers? Perhaps using try/catch exceptions?

Yoon Joon So
  • 29
  • 1
  • 5
  • An unnecessary duplucate of http://stackoverflow.com/questions/3806062/how-to-open-a-txt-file-and-read-numbers-in-java – Raedwald Mar 31 '15 at 22:15

3 Answers3

1

Read the line in

String line = // how ever you are reading it in

Split by space, Look at the docs for String.split()

String[] numbers = line.split("\\s");

Check size if(numbers.length > 10) //... to large

Check each is integer, Look at Integer.parseInt(), and put in your new array, all this together...

 String line = //How you read your line
 String[] numbers = line.split("\\s");

 if(numbers.length <= 10)
 {
     int[] myNumbers = new int[numbers.length]
     int i = 0;
     for(String s:numbers) {
        try {
             int num = Integer.parseInt(s);
             myNumbers[i] = num;
             i++;
         } catch (NumberFormatException nfex) {
             // was not a number
         }
     }
  }
  else
      // To many numbers
Java Devil
  • 10,629
  • 7
  • 33
  • 48
0

Here's some code to achieve the desired effect:

int[] nums;
try {
    String line = ...; // read one line and place it in line
    StringTokenizer tok = new StringTokenizer(line);
    if (tok.countTokens() >= 10)
        throw new IllegalArgumentException(); // can be any exception type you want, replace both here and in the catch below
    nums = new int[tok.countTokens()];
    int i = 0;
    while (tok.hasMoreTokens()) {
        nums[i] = Integer.parseInt(tok.nextToken());
        i++;
    }
} catch (NumberFormatException e) {
    // user entered a non-number
} catch (IllegalArgumentException e) {
    // user entered more that 10 numbers
}

The result is the nuns array has all the integers that the user entered. The catch blocks are activated when the user types a non-integer or more than 10 numbers.

tbodt
  • 16,609
  • 6
  • 58
  • 83
0
String line = "12 53 296 1";
String[] line= s.split(" ");
int[] numbers = new int[splitted.length];
boolean correct=true;
if(splitted.length <10)
{
    correct=false;
}
for(int i=0;i<splitted.length;i++)
{
    try
    {
        numbers[i] = Integer.parseInt(splitted[i]);
    }
    catch(NumberFormatException exception)
    {
        correct=false;
        System.out.println(splitted[i] + " is not a valid number!");
    }
}

now the array numbers contains the parsed numbers, and the boolean correct shows if every part was a number and there were not less than 10 numbers.

D180
  • 722
  • 6
  • 20