Try:

import java.util.Scanner;

public class NumAverage {

public static void main (String [] args)
{
    //int a,b;
    int[] numbers = new int [10];

    Scanner numreader = new Scanner(System.in);
    System.out.println("Enter 10 num");
    for (int i = 0; i < numbers.length; i++) {
        // Without the try and catch you get the appropriate exception,
        // NumberFormatException in this case
        String str = numreader.next();
        numbers[i] = Integer.parseInt(str);

        //try {
        //    numbers[i] = Integer.parseInt(numreader.next());
        //} catch(NumberFormatException e) {
        //    number[i] = 0; // or whatever you want
        //}
    }
  }
}
Answer from rendon on Stack Overflow
Top answer
1 of 3
1

Try:

import java.util.Scanner;

public class NumAverage {

public static void main (String [] args)
{
    //int a,b;
    int[] numbers = new int [10];

    Scanner numreader = new Scanner(System.in);
    System.out.println("Enter 10 num");
    for (int i = 0; i < numbers.length; i++) {
        // Without the try and catch you get the appropriate exception,
        // NumberFormatException in this case
        String str = numreader.next();
        numbers[i] = Integer.parseInt(str);

        //try {
        //    numbers[i] = Integer.parseInt(numreader.next());
        //} catch(NumberFormatException e) {
        //    number[i] = 0; // or whatever you want
        //}
    }
  }
}
2 of 3
1

This is what I would do for your case.

int[] numbers = new int[10];

Scanner numreader = new Scanner(System.in);

System.out.println("Enter 10 numbers");

// Get User Input
for (int i = 0; i < numbers.length; i++) {
    try {
        numbers[i] = Integer.parseInt((String) numreader.nextLine());
    } catch (NumberFormatException numFormatE) {
        System.out.println(numFormatE.getMessage() + "cannot be converted to integer");
        i = i - 1; // Restart current iteration.
    }
}
numreader.close();

// Loop through the number to get sum of the number.
int sum = 0;
for (int i = 0; i < numbers.length; i++) {
    sum += numbers[i];
}
System.out.println(sum);

However, if you want to combine sum in the main loop, this should work as well:

int[] numbers = new int[10];
int sum = 0;

Scanner numreader = new Scanner(System.in);

System.out.println("Enter 10 numbers");

// Get User Input
for (int i = 0; i < numbers.length; i++) {
    try {
        numbers[i] = Integer.parseInt((String) numreader.nextLine());
    } catch (NumberFormatException numFormatE) {
        System.out.println(numFormatE.getMessage() + "cannot be converted to integer");
        i = i - 1; // Restart current iteration.
    }
    sum += numbers[i]; // Add the number in loop
}
System.out.println(sum);
numreader.close();

UPDATE: FIXED CODE FORMATTING

Top answer
1 of 6
78

You could read the entire input line from scanner, then split the line by , then you have a String[], parse each number into int[] with index one to one matching...(assuming valid input and no NumberFormatExceptions) like

String line = scanner.nextLine();
String[] numberStrs = line.split(",");
int[] numbers = new int[numberStrs.length];
for(int i = 0;i < numberStrs.length;i++)
{
   // Note that this is assuming valid input
   // If you want to check then add a try/catch 
   // and another index for the numbers if to continue adding the others (see below)
   numbers[i] = Integer.parseInt(numberStrs[i]);
}

As YoYo's answer suggests, the above can be achieved more concisely in Java 8:

int[] numbers = Arrays.stream(line.split(",")).mapToInt(Integer::parseInt).toArray();  

To handle invalid input

You will need to consider what you want need to do in this case, do you want to know that there was bad input at that element or just skip it.

If you don't need to know about invalid input but just want to continue parsing the array you could do the following:

int index = 0;
for(int i = 0;i < numberStrs.length;i++)
{
    try
    {
        numbers[index] = Integer.parseInt(numberStrs[i]);
        index++;
    }
    catch (NumberFormatException nfe)
    {
        //Do nothing or you could print error if you want
    }
}
// Now there will be a number of 'invalid' elements 
// at the end which will need to be trimmed
numbers = Arrays.copyOf(numbers, index);

The reason we should trim the resulting array is that the invalid elements at the end of the int[] will be represented by a 0, these need to be removed in order to differentiate between a valid input value of 0.

Results in

Input: "2,5,6,bad,10"  
Output: [2,3,6,10]

If you need to know about invalid input later you could do the following:

Integer[] numbers = new Integer[numberStrs.length];
for(int i = 0;i < numberStrs.length;i++)        
{
    try 
    {
        numbers[i] = Integer.parseInt(numberStrs[i]);
    }
    catch (NumberFormatException nfe)   
    {
        numbers[i] = null;
    }
}

In this case bad input (not a valid integer) the element will be null.

Results in

Input: "2,5,6,bad,10"  
Output: [2,3,6,null,10]

You could potentially improve performance by not catching the exception (see this question for more on this) and use a different method to check for valid integers.

2 of 6
44

Line by line

int [] v = Stream.of(line.split(",\\s+"))
  .mapToInt(Integer::parseInt)
  .toArray();

With the Arrays.stream() alternative as

int [] v = Arrays.stream(line.split(",\\s+"))
  .mapToInt(Integer::parseInt)
  .toArray();

However much better for parsing bigger chunks of text is

int [] v = Pattern.compile(",\\s+").splitAsStream(line)
  .mapToInt(Integer::parseInt)
  .toArray();  

As this does not require the string array to be in memory, and we do an incremental parse to produce the integers. Moreover, as the input to splitAsStream is a CharSequece, and not just String, we can now also used buffered character sources to avoid even having the full input source in memory.

See also How do I create a Stream of regex matches? for some more interesting reading on incremental parsing.

๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ How-to-convert-string-to-array-of-integers-in-java
How to convert string to array of integers in java?
import java.util.Arrays; public class StringToIntegerArray { public static void main(String args[]) { String [] str = {"123", "345", "437", "894"}; int size = str.length; int [] arr = new int [size]; for(int i=0; i<size; i++) { arr[i] = Integer.parseInt(str[i]); } System.out.println(Arrays.toString(arr)); } } [123, 345, 437, 894] Samual Sam ยท
๐ŸŒ
Baeldung
baeldung.com โ€บ home โ€บ java โ€บ java array โ€บ converting a string array into an int array in java
Converting a String Array Into an int Array in Java | Baeldung
January 8, 2024 - Now that we understand Integer.parseInt() does the main conversion job, we can loop through the elements in the array and call the Integer.parseInt() method on each string element: int[] result = new int[stringArray.length]; for (int i = 0; ...
๐ŸŒ
Quora
quora.com โ€บ How-do-I-convert-a-string-to-integer-array-in-Java
How to convert a string to integer array in Java - Quora
Answer (1 of 24): There are two ways of converting a string to integer in java. 1- Integer.parseInt() Example to convert a String โ€œ50โ€ to a primitive int. > [code]String number = "50"; int result = Integer.parseInt(number); System.out.println(result); [/code] OutPut > [code]50 [/code] If...
๐ŸŒ
How to do in Java
howtodoinjava.com โ€บ home โ€บ java array โ€บ convert a string array to integer array in java
Convert a String Array to Integer Array in Java
January 20, 2023 - Java Streams provide a concise ... collection or array. In this approach, we iterate over the stream of string array, parse each string into int value using Integer::parseInt, ......
๐ŸŒ
Tutorialspoint
tutorialspoint.com โ€บ java โ€บ number_parseint.htm
Java - parseInt() Method
Java Vs. C++ ... This method is used to get the primitive data type of a certain String. parseXxx() is a static method and can have one argument or two. ... parseInt(int i) โˆ’ This returns an integer, given a string representation of decimal, ...
Find elsewhere
๐ŸŒ
Coderanch
coderanch.com โ€บ t โ€บ 663219 โ€บ java โ€บ Converting-string-array-int-array
Converting a string array into an int array (Beginning Java forum at Coderanch)
The Arrays#stream() method creates ... a ToIntFunction reference which converts things to ints. By passing Integer::parseInt you are telling the compiler to create a ToIntFunction which uses the parseInt() method....
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ java โ€บ java-program-to-convert-string-to-integer-array
Java Program to Convert String to Integer Array - GeeksforGeeks
Then, those sub-strings are converted to an integer using the Integer.parseInt() method and store that value integer value to the Integer array. ... // Java Program to Convert String to Integer Array using string.split() method import java.io.*; ...
Published ย  July 23, 2025
๐ŸŒ
Coderanch
coderanch.com โ€บ t โ€บ 728526 โ€บ java โ€บ Converting-String-Int-Array
Converting String to Int Array (Beginning Java forum at Coderanch)
No, he won't because he knows it will confuse OP's teacher even more If you are using Pattern#compile, what will happen to a String valued "0"? Or if you pass "2147483648" without a โˆ’? ... Well, I thought that 'Integer.parseInt("06")' would give an error, therefore I was desparately looking for a pattern that accepts either a single '0' or a number that did not start with a zero.
๐ŸŒ
Javatpoint
javatpoint.com โ€บ java-integer-parseint-method
Java Integer parseInt() Method - Javatpoint
Java program to find the percentage of uppercase, lowercase, digits and special characters in a string
๐ŸŒ
Upgrad
upgrad.com โ€บ home โ€บ tutorials โ€บ software & tech โ€บ parseint in java
parseInt in Java: Everything You should Know | upGrad
June 25, 2025 - Learn how to use parseInt in Java to convert strings to integers. Understand its parameters, return values, examples, and how it compares with valueOf().
๐ŸŒ
Study.com
study.com โ€บ courses โ€บ business courses โ€บ business 104: information systems and computer applications
How to Convert String to Int in Java - ParseInt Method - Lesson | Study.com
January 9, 2023 - In order to catch the exceptions, place the parseInt function within a try and catch block. The code you want to execute is inside the try statement. After the catch statement, you can display an error should the conversion fail. Since we're trying to convert a non-numeric number to numeric, the exception will be a NumberFormatException in the Java compiler. The code to wrap the pareseInt() function in a try and catch block is displayed here: String myString = newString("hello"); try { int makeNumber = Integer.parseInt(myString); System.out.println(makeNumber); } catch (NumberFormatexception e) { System.out.println("That wasn't a number!"); }
๐ŸŒ
Coderanch
coderanch.com โ€บ t โ€บ 376324 โ€บ java โ€บ parse-array
how do you parse an array (Java in General forum at Coderanch)
Originally posted by Robert Johnson: if i have... String[] homeTeamScores = request.getParameterValues("homeTeamScore"); can i use... int[] homeTeamScores = Integer.parseInt(homeTeamScore[]); No, homeTeamScore is of type Array, Integer.parseInt takes a String.