-4

I want to read in five numbers from the console. To convert the input strings into int[x] for each number i tried to use a for loop. But it turns out that #1 incrementation is dead code and #2 my array is not initialized, even though i just did. I'm on my first Java practices and would be happy to hear some advices.

My code:

public static void main(String[] args) throws IOException {

    System.out.println("Type in five Numbers");

    int [] array;       
    InputStreamReader isr = new InputStreamReader(System.in);
    BufferedReader br = new BufferedReader(isr);

    for(int x=0; x<5; x++){

    String eingabe = br.readLine();

    array[x] = Integer.parseInt(eingabe);
    break;
    }

    reserve(array); }

1 Answers1

1

First off, you didn't initialize your array, you only declared an array variable (named array). I highly suggest reading and practicing this fundamental concept of Java before proceeding further, because otherwise you will likely be confused later on. You can read more about the terms declaration, initialization, and assignment here.

Another issue, as Andrew pointed out, is that you used the keyword break in your first iteration of the loop. This keyword terminates a block of code, so your loop will only run once and then exit for good.


This code can be greatly simplified with a Scanner. A Scanner reads input from a specified location. The scanner's constructor accepts two inputs: System.in, for the default input device on your computer (keyboard), or a File object, such as a file on your computer.

Scanners, by default, have their delimeter set to the whitespace. A delimeter specifies the boundary between successive tokens, so if you input 2 3 5 5, for example, and then run a loop and invoke the scanVarName.nextInt() method, it will ignore the white spaces and treat each integer in that single line as its own token.

So if I understand correctly, you want to read input from the user (who will presumably enter integers) and you want to store these in an integer array, correct? You can do so using the following code if you know how many integers the user will enter. You can first prompt them to tell you how many integers they plan to enter:

// this declares the array
int[] array;       

// declares and initializes a Scanner object
Scanner scan = new Scanner(System.in); 

System.out.print("Number of integers: ");

int numIntegers = scan.nextInt();

// this initializes the array
array = new int[numIntegers];  

System.out.print("Enter the " + numIntegers + " integers: ");

for( int i = 0; i < numIntegers; i ++)
{
   // assigns values to array's elements
   array[i] = scan.nextInt();  
}

// closes the scanner
scan.close();     

You can then use a for-each loop to run through the items in your array and print them out to confirm that the above code works as intended.

Community
  • 1
  • 1
  • Thanks for your helpful answer. I just used your code and it worked out very well. –  Oct 02 '16 at 15:17