Search code examples
javacharintinputstreamreader

How to read integer from InputStremReader


I'm a beginner... please bear with me :)

This is a code that supposedly reads 10 integers in an array. The InputStreamReader reads in char (that what java Docs said) how to convert the char into int to be saved in the array?

int[] array = new int[10];
System.out.println("Please enter 10 integers. ");
for(int x=1; x <11; x++){
    InputStreamReader keyboard = new InputStreamReader(System.in);
    // Change char into int   
    array[x] = keyboard;
}

Thanks


Solution

  • Try this -

    Scanner sc = new Scanner(System.in);
    int[] array = new int[10];
    for(int x=0; x <10; x++){
        array[x] = sc.nextInt();
    }
    

    Scanner#nextInt scans the next token of the input as an int. And throws

    InputMismatchException - if the next token does not match the Integer regular expression, or is out of range
    NoSuchElementException - if input is exhausted
    IllegalStateException - if this scanner is closed