Search code examples
javaarraysparseint

use of parseInt


I want to use parseInt() method, but I don't now how to put array a my code:

import java.util.Scanner;

public class StaticMethodsWrapper {
public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    int n = input.nextInt();
    int[] a = new int[n];
    for (int i = 0; i < n; i++)
        a[i] = input.nextInt();
    for (int i = 0; i < a.length; i++)
        System.out.println(a[i]);

    int x = Integer.parseInt(a);//here is the error
}
}

Solution

  • parseInt(a) expects String type parameter for a. But you are providing it with int[] parameter. It is an array not a string.

    If you want to concatenate all numbers use this code when you have your a array populated:

    StringBuilder sb = new StringBuilder();
    for (int oneInt:a) {
      sb.append(oneInt);
    }
    
    System.out.println(sb.toString);
    

    And later you can parse this composed string to int or long variable type via parseInt of Integer class or parseLong of Long class. Like that:

    long myLong = Long.parseInt(sb.toString());